问:
TypeError: v2.UpdataData is not a function

I am new to Angular and MVC , and I have created a code for display
  records into table view.

User can edit and delete that records by clicking the Edit and Delete
  Link

but it shows me error when i click on edit link TypeError:
  v2.UpdataData is not a function

and it also shows me error TypeError: $http.get is not a function
  when i click on Delete Link

Can anyone help me to solve this out. Thanks in advance.

Controller.js

```<code>    //update data of table
        $scope.UpdataData = [];
        //UpdateData();
        $scope.UpdateData = function (StateMaster) {
            var RetValData = DataService.UpdateStudent(StateMaster);
            debugger;
            getData.then(function (StateMaster) {
                debugger;
                StateID: $scope.StateID;
                StateName: $scope.StateName;
                CountryName: $scope.CountryName;
            }, function () {
                alert('Error in getting records');
            });
    }
 $scope.DeleteData = [];
    $scope.DeleteData = function (r, index) {
        var retval = DataService.DeleteData(r.StateID).success(function (msg) {
            $scope.countrydata.splice(index, 1);
             alert('Student has been deleted successfully.');
        }).error(function () {
            alert('Oops! something went wrong.');
        });
    }.factory('DataService', function ($http) {
    var fac={}
    debugger;
    fac.UpdateData= function($http)
    {
        return $http.get('/State/UpdateData');
    }
    return fac;
}).factory('DataService', function () {
    var fac={}
    debugger;
    fac.DeleteData = function ($http)
    {
        return $http.get('/State/DeleteData');
    }
    return fac;
});
</code>```

StateController.cs

```<code>    public string UpdateData(StateMaster r)
            {
                if (r != null)
                {
                    using (simpleEntities dbContext = new simpleEntities())
                    {
                        StateMaster lstdata = dbContext.StateMasters.Where(x => x.StateID == r.StateID).FirstOrDefault();
                        lstdata.StateName = r.StateName;
                        lstdata.CountryName = r.CountryName;
                        dbContext.SaveChanges();
                        return "Data Updated";
                    }
                }
                else
                {
                    return "something went worng";
                }
            }
[HttpPost]
        public string DeleteData(int id)
        {
            if (id != 0)
            {
                using (simpleEntities databContext = new simpleEntities())
                {
                    var lsdata = databContext.StateMasters.Where(x => x.StateID == id).FirstOrDefault();
                    databContext.StateMasters.Remove(lsdata);
                    databContext.SaveChanges();
                    return "Data Deleted Successfully";
                }
            }
            else {
                return "Error Occured";
            }
        }
</code>```

InsertState.cshtml

```<code><div ng-app="MyApp" ng-controller="StateController">
     <table class="table table-bordered">
            <tr>
                <td>Sr. No.</td>
                <td>Country Name</td>
                <td>State Name</td>
                <td></td>
                @*<td>Country Name</td>*@
            </tr>
            <tr ng-repeat="r in countrydata">
                <td>{{$index + 1}}</td>
                <td>{{r.CountryName}}</td>
                <td>{{r.StateName}}</td>
                @*<td>{{r.CountryName}}</td>*@
                <td>
                    <span ng-click="UpdataData(r)" class="btnAdd">Edit</span> |
                    <span ng-click="DeleteData(r)" class="btnRed">Delete</span>
                </td>
            </tr>

        </table>
</div>
</code>```

答:
there is problem in you code with this

line  $scope.UpdateData = function (StateMaster

as you are trying to run fuction of your $scop but fuction is of factory so you have to try like

```<code>factory.UpdateDate
</code>```

Seem like there is problem in defining factory in angular , you can try below way

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

    app.factory('testFactory', function(){
        return {
            sayHello: function(text){
                return "Factory says \"Hello " + text + "\"";
            },
            sayGoodbye: function(text){
                return "Factory says \"Goodbye " + text + "\"";
            }
        }
    });

   function HelloCtrl($scope, testService, testFactory)
   {
      $scope.fromFactory = testFactory.sayHello("World");
   }
</code>```

you can place your function and just try out it return you value or not

Body:
I am new to Angular and MVC , and I have created a code for display
  records into table view.

User can edit and delete that records by clicking the Edit and Delete
  Link

but it shows me error when i click on edit link TypeError:
  v2.UpdataData is not a function

and it also shows me error TypeError: $http.get is not a function
  when i click on Delete Link

Can anyone help me to solve this out. Thanks in advance.

Controller.js

    //update data of table
        $scope.UpdataData = [];
        //UpdateData();
        $scope.UpdateData = function (StateMaster) {
            var RetValData = DataService.UpdateStudent(StateMaster);
            debugger;
            getData.then(function (StateMaster) {
                debugger;
                StateID: $scope.StateID;
                StateName: $scope.StateName;
                CountryName: $scope.CountryName;
            }, function () {
                alert('Error in getting records');
            });
    }
 $scope.DeleteData = [];
    $scope.DeleteData = function (r, index) {
        var retval = DataService.DeleteData(r.StateID).success(function (msg) {
            $scope.countrydata.splice(index, 1);
             alert('Student has been deleted successfully.');
        }).error(function () {
            alert('Oops! something went wrong.');
        });
    }.factory('DataService', function ($http) {
    var fac={}
    debugger;
    fac.UpdateData= function($http)
    {
        return $http.get('/State/UpdateData');
    }
    return fac;
}).factory('DataService', function () {
    var fac={}
    debugger;
    fac.DeleteData = function ($http)
    {
        return $http.get('/State/DeleteData');
    }
    return fac;
});

StateController.cs

    public string UpdateData(StateMaster r)
            {
                if (r != null)
                {
                    using (simpleEntities dbContext = new simpleEntities())
                    {
                        StateMaster lstdata = dbContext.StateMasters.Where(x => x.StateID == r.StateID).FirstOrDefault();
                        lstdata.StateName = r.StateName;
                        lstdata.CountryName = r.CountryName;
                        dbContext.SaveChanges();
                        return "Data Updated";
                    }
                }
                else
                {
                    return "something went worng";
                }
            }
[HttpPost]
        public string DeleteData(int id)
        {
            if (id != 0)
            {
                using (simpleEntities databContext = new simpleEntities())
                {
                    var lsdata = databContext.StateMasters.Where(x => x.StateID == id).FirstOrDefault();
                    databContext.StateMasters.Remove(lsdata);
                    databContext.SaveChanges();
                    return "Data Deleted Successfully";
                }
            }
            else {
                return "Error Occured";
            }
        }

InsertState.cshtml

                Sr. No.
                Country Name
                State Name

                @*Country Name	*@

                {{$index + 1}}
                {{r.CountryName}}
                {{r.StateName}}
                @*{{r.CountryName}}	*@

                    Edit |
                    Delete

Body:
there is problem in you code with this

line  $scope.UpdateData = function (StateMaster

as you are trying to run fuction of your $scop but fuction is of factory so you have to try like

factory.UpdateDate

Seem like there is problem in defining factory in angular , you can try below way

    var app = angular.module('myApp', []);

    app.factory('testFactory', function(){
        return {
            sayHello: function(text){
                return "Factory says \"Hello " + text + "\"";
            },
            sayGoodbye: function(text){
                return "Factory says \"Goodbye " + text + "\"";
            }
        }
    });

   function HelloCtrl($scope, testService, testFactory)
   {
      $scope.fromFactory = testFactory.sayHello("World");
   }

you can place your function and just try out it return you value or not


来源: stackexchange

问:
How can I create a UILabel with strikethrough text?
I want to create a UILabel in which the text is like this

How can I do this? When the text is small, the line should also be small.

答:
SWIFT 4

```<code>    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text Goes Here")
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
    self.lbl_productPrice.attributedText = attributeString
</code>```

Other method is to used String Extension

Extension

```<code>extension String{
    func strikeThrough()->NSAttributedString{
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
        return attributeString
    }
}
</code>```

Calling the function : Used it like so

```<code>testUILabel.attributedText = "Your Text Goes Here!".strikeThrough()
</code>```

Credit to @Yahya - update Dec 2017

Credit to @kuzdu - update Aug 2018

ContentLicense: CC BY-SA 4.0

Body:
SWIFT 4

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text Goes Here")
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
    self.lbl_productPrice.attributedText = attributeString

Other method is to used String Extension

Extension

extension String{
    func strikeThrough()->NSAttributedString{
        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
        return attributeString
    }
}

Calling the function : Used it like so

testUILabel.attributedText = "Your Text Goes Here!".strikeThrough()

Credit to @Yahya - update Dec 2017

Credit to @kuzdu - update Aug 2018


问:
why are spreading and destructing different even though they seem to do a similar job
Spreading and destructing work differently but they both seem to do a similar job. Why are they different, why not use just one?</p>

```<code>let foo = [1,2,3];
let [o,t,th] = foo; //destructing works

let [o,t,th] = ...foo; // spreading doesn't work. will not compile

function test (a,b,c) {
 console.log(`${a}, ${b}, ${c}`)
}

test(...foo); //works but is sort of destructinng foo into a,b,c
test(foo) //assigns foo to a. b and c are undefined.
</code>```

答:
Destructuring

```<code>let [o,t,th] = [1, 2, 3];
</code>```

Here you are declaring three variables and at the same time assigning them values directly from array elements.

Therefore, destructuring is a way to directly access an object's(can
  also be an array) properties without need to explicitly assign them to
  variables.

It is equivalent to this:

```<code>let o = foo[0];
let t = foo[1];
let th = foo[2];
</code>```

Spread

```<code>test(...foo);
</code>```

Here you are spreading the array elements to comma separated array elements.

It is equivalent to this:

```<code>test(foo[0], foo[1], foo[2]);
</code>```

Therefore these two are different from each other.

ContentLicense: CC BY-SA 3.0

Body:
Spreading and destructing work differently but they both seem to do a similar job. Why are they different, why not use just one?

let foo = [1,2,3];
let [o,t,th] = foo; //destructing works

let [o,t,th] = ...foo; // spreading doesn't work. will not compile

function test (a,b,c) {
 console.log(`${a}, ${b}, ${c}`)
}

test(...foo); //works but is sort of destructinng foo into a,b,c
test(foo) //assigns foo to a. b and c are undefined.

Body:
Destructuring

let [o,t,th] = [1, 2, 3];

Here you are declaring three variables and at the same time assigning them values directly from array elements.

Therefore, destructuring is a way to directly access an object's(can
  also be an array) properties without need to explicitly assign them to
  variables.

It is equivalent to this:

let o = foo[0];
let t = foo[1];
let th = foo[2];

Spread

test(...foo);

Here you are spreading the array elements to comma separated array elements.

It is equivalent to this:

test(foo[0], foo[1], foo[2]);

Therefore these two are different from each other.


答:
First of all, you should beware that

```<code>[a, b, c]
</code>```

and

```<code>func(a, b, c)
</code>```

are two completely different things. Sure they both have commas and the same letters, but a, b, c in func(a, b, c) is not an array.

In test(...foo), ...foo spreads the content of the array as the comma separated arguments. It is not the same as passing an array into the function.

let [o,t,th] = ...foo; does not work because the specification does not allow such use. It doesn't make sense anyway. What are you trying to spread the content of foo into?

This, however, makes sense:

```<code>[...foo]  // spread the content into an array
</code>```

Destructure only works when you are assigning one thing to a bunch of variables. Examples include:

```<code>let [a, b] = [1, 2];
let {a, b} = {a: 1, b: 2};
function([a, b]){};
</code>```

Title: why are spreading and destructing different even though they seem to do a similar job

Body:
First of all, you should beware that

[a, b, c]

and

func(a, b, c)

are two completely different things. Sure they both have commas and the same letters, but a, b, c in func(a, b, c) is not an array.

In test(...foo), ...foo spreads the content of the array as the comma separated arguments. It is not the same as passing an array into the function.

let [o,t,th] = ...foo; does not work because the specification does not allow such use. It doesn't make sense anyway. What are you trying to spread the content of foo into?

This, however, makes sense:

[...foo]  // spread the content into an array

Destructure only works when you are assigning one thing to a bunch of variables. Examples include:

let [a, b] = [1, 2];
let {a, b} = {a: 1, b: 2};
function([a, b]){};


问:
How to call method in android so able to run code
I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?

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

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

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method

    //I want to call that fucntion, and i get an error
    calculator();

}
</code>```

答:
Try this</p>

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

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

    //Start my method

    public void calculator() {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method
}
</code>```

Body:
I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?

public class CalculatorActivity extends AppCompatActivity {

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

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method

    //I want to call that fucntion, and i get an error
    calculator();

}

Body:
Try this

public class CalculatorActivity extends AppCompatActivity {

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

    //Start my method

    public void calculator() {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method
}


问:
iBatis Silent Failure to Map Columns
When I am mapping a POJO with iBatis such as below:

```<code>Person {
    String firstName
    String lastName;
}
</code>```

To the query:

```<code>select firstName, last_name from Person
</code>```

I am finding that Person.firstName is populated correctly whereas Person.lastName is null - this happens silently. I can introduce a ResultMap to fix the null issue (by translating last_name -> lastName), but I would like iBatis to throw an error when attempting to map rather than doing the best it can silently...

Does anyone know how I can do this?

Thanks!

答:
You can try aliasing with AS:</p>

```<code>SELECT firstName, last_name AS lastName
FROM   Person
</code>```

ContentLicense: CC BY-SA 2.5

Title: iBatis Silent Failure to Map Columns

Body:
When I am mapping a POJO with iBatis such as below:

Person {
    String firstName
    String lastName;
}

To the query:

select firstName, last_name from Person

I am finding that Person.firstName is populated correctly whereas Person.lastName is null - this happens silently. I can introduce a ResultMap to fix the null issue (by translating last_name -> lastName), but I would like iBatis to throw an error when attempting to map rather than doing the best it can silently...

Does anyone know how I can do this?

Thanks!

Body:
You can try aliasing with AS:

SELECT firstName, last_name AS lastName
FROM   Person


答:
Use Below Code:</p>

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

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_calculator);
        //I want to call that fucntion, and i get an error
        calculator();
        }

        //Start my method

        public void calculator() {
            Button btn0 = (Button) findViewById(R.id.btn0);
            Button btn1 = (Button) findViewById(R.id.btn1);
            Button btn2 = (Button) findViewById(R.id.btn2);
            Button btn3 = (Button) findViewById(R.id.btn3);
            Button btn4 = (Button) findViewById(R.id.btn4);
            Button btn5 = (Button) findViewById(R.id.btn5);
            Button btn6 = (Button) findViewById(R.id.btn6);
            Button btn7 = (Button) findViewById(R.id.btn7);

            TextView textViewResult = (TextView) findViewById(R.id.textView);

            if (btn0.isPressed() == true) {

                textViewResult.setText(textViewResult + "0");
            } else if (btn1.isPressed() == true) {
                textViewResult.setText(textViewResult + "1");

            }

        }
           //End my method
    }
</code>```

Title: How to call method in android so able to run code

Body:
Use Below Code:

public class CalculatorActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_calculator);
        //I want to call that fucntion, and i get an error
        calculator();
        }

        //Start my method

        public void calculator() {
            Button btn0 = (Button) findViewById(R.id.btn0);
            Button btn1 = (Button) findViewById(R.id.btn1);
            Button btn2 = (Button) findViewById(R.id.btn2);
            Button btn3 = (Button) findViewById(R.id.btn3);
            Button btn4 = (Button) findViewById(R.id.btn4);
            Button btn5 = (Button) findViewById(R.id.btn5);
            Button btn6 = (Button) findViewById(R.id.btn6);
            Button btn7 = (Button) findViewById(R.id.btn7);

            TextView textViewResult = (TextView) findViewById(R.id.textView);

            if (btn0.isPressed() == true) {

                textViewResult.setText(textViewResult + "0");
            } else if (btn1.isPressed() == true) {
                textViewResult.setText(textViewResult + "1");

            }

        }
           //End my method
    }


问:
How can I remove padding property from an element? (CSS)
```<code>   <th style="padding-left:40px;" id="lbl_vehicleType">
     <h5> Vehicle Type </h5>
  </th>
</code>```

How can I remove the padding-left with media query I tried using this approach.

```<code>    @media only screen and (max-width: 480px){
        #drp_per_page2{
            color:red;
        }

        #lbl_vehicleType{
            padding-left: 0;
        }
    }
</code>```

I tried to change the color of the dropdown to see if it works.
    It did although the padding-left did not.
    I even tried making it padding-left: -40px; Still it didn't work.

答:
you need to add important tag if you want to remove anything from style if you want to achieve this with css</p>

```<code>@media only screen and (max-width: 480px){
        #lbl_vehicleType{
            padding-left: 0!important;
        }
    }
</code>```

Body:
 Vehicle Type

How can I remove the padding-left with media query I tried using this approach.

    @media only screen and (max-width: 480px){
        #drp_per_page2{
            color:red;
        }

        #lbl_vehicleType{
            padding-left: 0;
        }
    }

I tried to change the color of the dropdown to see if it works.
    It did although the padding-left did not.
    I even tried making it padding-left: -40px; Still it didn't work.

Body:
you need to add important tag if you want to remove anything from style if you want to achieve this with css

@media only screen and (max-width: 480px){
        #lbl_vehicleType{
            padding-left: 0!important;
        }
    }


问:
Python default (mutable) parameter initialization style
Let's have a function make_sandwich that takes a list of ingredients which has a default value of ['ham', 'ham', 'bacon', 'ham']

```<code>def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
    print("Making a sandwich with ", ingredients)
</code>```

However, since this default value is susceptible to this python "mutable default argument" <s>bug</s> feature, we should use an immutable instead like this:

```<code>def make_sandwich(ingredients=None):
    # initialized ingredients here
    print("Making a sandwich with ", ingredients)
</code>```

So here's the question. There're two ways that I am aware of to do this, but I am not sure which one is considered a better practice.

The first one:

```<code>if not ingredients:
    ingredients = ['ham', 'ham', 'bacon', 'ham']
</code>```

The second one:

```<code>ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']
</code>```

Personally I use the second one more often. Sometimes, I even inline that if the argument is used only once. e.g.

print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])

Is there any solid reason to prefer one over the others?

答:
a matter of personal style.  you could also do

```<code>ingredients = ingredients if ingredients else ['ham', 'ham', 'bacon', 'ham']
</code>```

just depends on who will be reading your code.
personally i'm fine with your second

```<code>ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']
</code>```

Body:
Let's have a function make_sandwich that takes a list of ingredients which has a default value of ['ham', 'ham', 'bacon', 'ham']

def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
    print("Making a sandwich with ", ingredients)

However, since this default value is susceptible to this python "mutable default argument" <s>bug</s> feature, we should use an immutable instead like this:

def make_sandwich(ingredients=None):
    # initialized ingredients here
    print("Making a sandwich with ", ingredients)

So here's the question. There're two ways that I am aware of to do this, but I am not sure which one is considered a better practice.

The first one:

if not ingredients:
    ingredients = ['ham', 'ham', 'bacon', 'ham']

The second one:

ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']

Personally I use the second one more often. Sometimes, I even inline that if the argument is used only once. e.g.

print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])

Is there any solid reason to prefer one over the others?

Body:
a matter of personal style.  you could also do

ingredients = ingredients if ingredients else ['ham', 'ham', 'bacon', 'ham']

just depends on who will be reading your code.
personally i'm fine with your second

ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']


问:
Onclick function button inside a javascript
I want to direct the button to another page

```<code>function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}
</code>```

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

答:
function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = "yourpage.php";" id ="newcust" class="btnRegister" value = "New Customer">';
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click To Get Button
<p id="demo"></p></code>```

Right Click And inspect Button.

Body:
I want to direct the button to another page

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

Body:
function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = "yourpage.php";" id ="newcust" class="btnRegister" value = "New Customer">';
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="showInput()" >Click To Get Button</a>
<p id="demo"></p>

Right Click And inspect Button.


答: call calculator() method inside your onCreate() method</p>


问:
Can AES-256 work on Android Devices with API Level 26+?
So I'm trying to implement an AES-256 encryption/decryption to my Android application. However, I don't want to include extra jar to enable AES-256 as there are export control policies in place.

I found this in official documentation and it seems like API level 26+ supports AES-256 and AES-128, is there a way to use this algorithms in older API levels?

答:
AES-256 is supported by android. You can use this helper class to make your work easy.

Warning: This code is insecure.  It uses a fixed IV and bad key management practices.  Don't use it in production or for anything that requires actual security.

```<code>import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;

public class AES256Cipher {

    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
            throws java.io.UnsupportedEncodingException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return cipher.doFinal(textBytes);
    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
            throws java.io.UnsupportedEncodingException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return cipher.doFinal(textBytes);
    }
}
</code>```

USAGE

```<code>String key = "e8ffc7e56311679f12b6fc91aa77a5eb";
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

String plainText;
byte[] cipherData;
String base64Text;

//############## Request(crypt) ##############
plainText  = "crypt text!!";
cipherData = AES256Cipher.encrypt(ivBytes, keyBytes, plainText.getBytes("UTF-8"));
base64Text = Base64.encodeToString(cipherData, Base64.DEFAULT);
Log.d("encrypt", base64Text);   //BhSJd4mRRJo+fGzpxIOUNg==

//############## Response(decrypt) ##############
base64Text = "72XrlydqnUzVrDfDE7ncnQ==";
cipherData = AES256Cipher.decrypt(ivBytes, keyBytes, Base64.decode(base64Text.getBytes("UTF-8"), Base64.DEFAULT));
plainText = new String(cipherData, "UTF-8");
Log.d("dcrypt", plainText);
</code>```

Body:
AES-256 is supported by android. You can use this helper class to make your work easy.

Warning: This code is insecure.  It uses a fixed IV and bad key management practices.  Don't use it in production or for anything that requires actual security.

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;

public class AES256Cipher {

    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
            throws java.io.UnsupportedEncodingException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return cipher.doFinal(textBytes);
    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
            throws java.io.UnsupportedEncodingException,
            NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return cipher.doFinal(textBytes);
    }
}

USAGE

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

String plainText;
byte[] cipherData;
String base64Text;

//############## Request(crypt) ##############
plainText  = "crypt text!!";
cipherData = AES256Cipher.encrypt(ivBytes, keyBytes, plainText.getBytes("UTF-8"));
base64Text = Base64.encodeToString(cipherData, Base64.DEFAULT);
Log.d("encrypt", base64Text);   //BhSJd4mRRJo+fGzpxIOUNg==

//############## Response(decrypt) ##############
base64Text = "72XrlydqnUzVrDfDE7ncnQ==";
cipherData = AES256Cipher.decrypt(ivBytes, keyBytes, Base64.decode(base64Text.getBytes("UTF-8"), Base64.DEFAULT));
plainText = new String(cipherData, "UTF-8");
Log.d("dcrypt", plainText);


问:
Iterate on an EF objects to see only "new values" before saving changes
I'm adding new objects in any EF object.
Just before to saves the changes from EF to the database, i would like to iterate on my object in order see all the value i add.

If i made a simple:

```<code>var Categories = myDb.category;
foreach (var category in Categories)
{
    .....
}
</code>```

It will give me "all" the values no ? Values i add, and, values already in the database.

How can I get all the values "in standby" to be "saved in database" ?

答:
Try this approach:</p>

```<code>var Categories = myDb.ChangeTracker.Entries<Category>()
                     .Where(x => x.State == EntityState.Added);

foreach (var category in Categories)
{
    //your logic
}
</code>```

Body:
I'm adding new objects in any EF object.
Just before to saves the changes from EF to the database, i would like to iterate on my object in order see all the value i add.

If i made a simple:

var Categories = myDb.category;
foreach (var category in Categories)
{
    .....
}

It will give me "all" the values no ? Values i add, and, values already in the database.

How can I get all the values "in standby" to be "saved in database" ?

Body:
Try this approach:

var Categories = myDb.ChangeTracker.Entries<Category>()
                     .Where(x => x.State == EntityState.Added);

foreach (var category in Categories)
{
    //your logic
}


问:
How to use c library in .net
Hi I have created c library in visual studio 2017. I followed following steps to create C library. Under visual cpp I selected windows console application and I created simple hello world program. Please find the below screen shot.

Inside project CLibrary I got below folders after compiling

```<code>CLibrary.exe
CLibrary.ilk
Clibrary.pdb
</code>```

Now I want to use this program in C#. I created one web api project. I want to access this CLibrary in my weapi project. Can someone tell me how can I use this c program in c#. Any help would be greatly appreciated. Thank you.

答:
Do not start with console application.
You should create library in visual studio, after this you can use your cpp.dll as external.

c++ code

```<code>extern "C" __declspec(dllexport) int sum(int x,int y){return x+y;}//for windows
</code>```

c# code for calling

```<code>[DllImport("yourdll.dll", EntryPoint = "sum")]
    internal unsafe static extern int Sum(int x,int y);
</code>```

Title: How to use c library in .net

Body:
Hi I have created c library in visual studio 2017. I followed following steps to create C library. Under visual cpp I selected windows console application and I created simple hello world program. Please find the below screen shot.

Inside project CLibrary I got below folders after compiling

CLibrary.exe
CLibrary.ilk
Clibrary.pdb

Now I want to use this program in C#. I created one web api project. I want to access this CLibrary in my weapi project. Can someone tell me how can I use this c program in c#. Any help would be greatly appreciated. Thank you.

Body:
Do not start with console application.
You should create library in visual studio, after this you can use your cpp.dll as external.

c++ code

extern "C" __declspec(dllexport) int sum(int x,int y){return x+y;}//for windows

c# code for calling

[DllImport("yourdll.dll", EntryPoint = "sum")]
    internal unsafe static extern int Sum(int x,int y);


问:
Use JWT (Authorization: Bearer) in Swagger in ASP.NET Core
I'm creating a REST api in ASP.NET Core 1.0. I was using Swagger to test but now I added JWT authorization for some routes. (with UseJwtBearerAuthentication)

Is it possible to modify the header of the Swagger requests so the routes with the [Authorize] attribute can be tested?

答:
Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header (I'm using Swashbuckle.AspNetCore 1.1.0).

The following code should help achieve this.

In the Startup.ConfigureServices():

```<code>services.AddSwaggerGen(c =>
{
    // Your custom configuration
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    c.DescribeAllEnumsAsStrings();
    // JWT-token authentication by password
    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
    {
        Type = "oauth2",
        Flow = "password",
        TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/token"),
        // Optional scopes
        //Scopes = new Dictionary<string, string>
        //{
        //    { "api-name", "my api" },
        //}
    });
});
</code>```

Check and configure TokenUrl if your endpoint is different.

In the Startup.Configure():

```<code>app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");

    // Provide client ID, client secret, realm and application name (if need)

    // Swashbuckle.AspNetCore 4.0.1
    c.OAuthClientId("swagger-ui");
    c.OAuthClientSecret("swagger-ui-secret");
    c.OAuthRealm("swagger-ui-realm");
    c.OAuthAppName("Swagger UI");

    // Swashbuckle.AspNetCore 1.1.0
    // c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI");
});
</code>```

If your endpoint for authentication by token follows the OAuth2 standard, all should work. But just in case, I have added sample of this endpoint:

```<code>public class AccountController : Controller
{
    [ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.Unauthorized)]
    [HttpPost("/token")]
    public async Task<IActionResult> Token([FromForm] LoginModel loginModel)
    {
        switch (loginModel.grant_type)
        {
            case "password":
                var accessTokens = // Authentication logic
                if (accessTokens == null)
                    return BadRequest("Invalid user name or password.");
                return new ObjectResult(accessTokens);

            case "refresh_token":
                var accessTokens = // Refresh token logic
                if (accessTokens == null)
                    return Unauthorized();
                return new ObjectResult(accessTokens);

            default:
                return BadRequest("Unsupported grant type");
        }
    }
}

public class LoginModel
{
    [Required]
    public string grant_type { get; set; }

    public string username { get; set; }
    public string password { get; set; }
    public string refresh_token { get; set; }
    // Optional
    //public string scope { get; set; }
}

public class AccessTokens
{
    public string access_token { get; set; }
    public string refresh_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}
</code>```

Body:
Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header (I'm using Swashbuckle.AspNetCore 1.1.0).

The following code should help achieve this.

In the Startup.ConfigureServices():

services.AddSwaggerGen(c =>
{
    // Your custom configuration
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    c.DescribeAllEnumsAsStrings();
    // JWT-token authentication by password
    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
    {
        Type = "oauth2",
        Flow = "password",
        TokenUrl = Path.Combine(HostingEnvironment.WebRootPath, "/token"),
        // Optional scopes
        //Scopes = new Dictionary<string, string>
        //{
        //    { "api-name", "my api" },
        //}
    });
});

Check and configure TokenUrl if your endpoint is different.

In the Startup.Configure():

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");

    // Provide client ID, client secret, realm and application name (if need)

    // Swashbuckle.AspNetCore 4.0.1
    c.OAuthClientId("swagger-ui");
    c.OAuthClientSecret("swagger-ui-secret");
    c.OAuthRealm("swagger-ui-realm");
    c.OAuthAppName("Swagger UI");

    // Swashbuckle.AspNetCore 1.1.0
    // c.ConfigureOAuth2("swagger-ui", "swagger-ui-secret", "swagger-ui-realm", "Swagger UI");
});

If your endpoint for authentication by token follows the OAuth2 standard, all should work. But just in case, I have added sample of this endpoint:

public class AccountController : Controller
{
    [ProducesResponseType(typeof(AccessTokens), (int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.Unauthorized)]
    [HttpPost("/token")]
    public async Task<IActionResult> Token([FromForm] LoginModel loginModel)
    {
        switch (loginModel.grant_type)
        {
            case "password":
                var accessTokens = // Authentication logic
                if (accessTokens == null)
                    return BadRequest("Invalid user name or password.");
                return new ObjectResult(accessTokens);

            case "refresh_token":
                var accessTokens = // Refresh token logic
                if (accessTokens == null)
                    return Unauthorized();
                return new ObjectResult(accessTokens);

            default:
                return BadRequest("Unsupported grant type");
        }
    }
}

public class LoginModel
{
    [Required]
    public string grant_type { get; set; }

    public string username { get; set; }
    public string password { get; set; }
    public string refresh_token { get; set; }
    // Optional
    //public string scope { get; set; }
}

public class AccessTokens
{
    public string access_token { get; set; }
    public string refresh_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
}


问:
React nested Routes implementation
I am new to reactjs. i am trying to develop website who's home page or landing page has different design then signin user. after user logs in header changes and there is a sidebar. I have placed my signed routes inside signed in component but still its not working

```<code><Switch>
 <Route exact path="/" component={HomePage} />
 <Route path="/Resident" component={customer} />
 <Route path="/search" component={search} />
 <Route component={EmptyPage} />
</Switch>

    class customer extends Component {

        constructor() {
            super()
            this.setLayout = this.setLayout.bind(this)
            // Listen for changes to the current location.
            history.listen((location, action) => {
                // location is an object like window.location
                //console.log('history', location.pathname, this.setLayout(location.pathname))
                this.setLayout(location.pathname)
            })
        }

        componentWillMount() {
            this.setLayout(this.props.pathname)
        }

        setLayout(url) {
            const emptyView1 = [
                '/pages/error-page',
                '/pages/create-account',
                '/pages/login',
                '/pages/under-maintenance',
            ];

            let isEmptyView = indexOf(emptyView1, url) !== -1 ? true : false
            let currentLayout = this.props.config.layout
            if(isEmptyView && currentLayout !== 'empty-view-1') {
                this.props.setConfig('layout', 'empty-view-1')
            } else if(!isEmptyView && currentLayout !== 'default-sidebar-1') {
                this.props.setConfig('layout', 'default-sidebar-1')
            }
        }

        render() {
            let {layout, background, navbar, logo, leftSidebar, topNavigation, collapsed} = this.props.config
            // let {pathname} = this.props
            let isEmptyView = layout === 'empty-view-1' ? true : false
            return (
                <ConnectedRouter history={history}>
                    <div
                        data-layout={layout}
                        data-background={background}
                        data-navbar={navbar}
                        data-logo={logo}
                        data-left-sidebar={leftSidebar}
                        data-top-navigation={topNavigation}
                        data-collapsed={collapsed}
                    >
                        <Shortcuts />
                        <Backdrops />
                        {!isEmptyView &&
                        <RightSidebar1 />
                        }
                        {!isEmptyView &&
                        <Navbar1 />
                        }
                        <div className="container-fluid">
                            <div className="row">
                                {!isEmptyView &&
                                <LeftSidebar1 />
                                }
                                <div className="col main">
                                    <Switch>
                                        <Route path="/dashboard" component={Dashboard} />
                                        <Route path="/policies/index" component={Policies}/>
                                        <Route path="/pages/create-account" component={CreateAccount} />
                                        <Route path="/pages/empty-page" component={EmptyPage} />
                                        <Route path="/pages/under-maintenance" component={UnderMaintenance} />
                                        <Route path="/pages/error-page" component={ErrorPage} />
                                        <Route path="/pages/user-profile" component={UserProfile} />
                                        <Route path="/on-notice" component={OnNotice} />
                                        <Route path="/profile" component={UserProfile} />
                                        <Route path="/kyc-documents" component={KYCDocuments} />
                                        <Route path="/booking" component={Booking} />
                                        <Route path="/bookings" component={Bookings} />

                                        <Route path="/pay-amount" component={Payment} />
                                        <Route path="/security-deposit" component={Deposit} />
                                        <Route path="/transactions" component={Transactions} />
                                        <Route path="/notice-board" component={NoticeBoard} />
                                        <Route path="/deals" component={Deals} />

                                        <Route path="/checkin" component={Checkin} />
                                        <Route path='/subscriptions' component={MySubscriptions} />
                                        <Route path='/view-ticket' component={ViewTicket} />
                                        <Route path="/new-ticket" component={NewTicket} />
                                        <Route component={EmptyPage} />
                                    </Switch>
                                </div>
                            </div>
                        </div>
                    </div>
                </ConnectedRouter>
            )
        }
    }

    const mapStateToProps = (state, ownProps) => {
        return {
            pathname: state.router.location && state.router.location.pathname ? state.router.location.pathname : window.location.pathname,
            config: state.config,
            tickets : state.ticket
        }
    }
    const mapDispatchToProps = dispatch => {
        return {
            setConfig: (key, value) => dispatch(setConfig(key, value))
        }
    }
    export default connect(mapStateToProps, mapDispatchToProps)(customer)
</code>```

I want to know how to do routing header and sidebar shouldn't be shown for non logged in user, there are few pages user can access without sign in

Above code which i have written is not routing.

Please guide me in right direction

答:
router is old one method you can use ReactRouter (flowRouter kadira) package for easy routing

```<code>group.route('/', {
        name: 'Routes.Task.List',
        action () {
            let props = {
                content: (<Containers.List />),
                title: 'title xyz',
                pageTitle: 'title xyz',
            };

            mount(Wrapper, { props });
        },
    });
</code>```

and now you can use this as flowRouter.path('Routes.Task.List')

Title: React nested Routes implementation

Body:
I am new to reactjs. i am trying to develop website who's home page or landing page has different design then signin user. after user logs in header changes and there is a sidebar. I have placed my signed routes inside signed in component but still its not working

<Switch>
 <Route exact path="/" component={HomePage} />
 <Route path="/Resident" component={customer} />
 <Route path="/search" component={search} />
 <Route component={EmptyPage} />
</Switch>

    class customer extends Component {

        constructor() {
            super()
            this.setLayout = this.setLayout.bind(this)
            // Listen for changes to the current location.
            history.listen((location, action) => {
                // location is an object like window.location
                //console.log('history', location.pathname, this.setLayout(location.pathname))
                this.setLayout(location.pathname)
            })
        }

        componentWillMount() {
            this.setLayout(this.props.pathname)
        }

        setLayout(url) {
            const emptyView1 = [
                '/pages/error-page',
                '/pages/create-account',
                '/pages/login',
                '/pages/under-maintenance',
            ];

            let isEmptyView = indexOf(emptyView1, url) !== -1 ? true : false
            let currentLayout = this.props.config.layout
            if(isEmptyView && currentLayout !== 'empty-view-1') {
                this.props.setConfig('layout', 'empty-view-1')
            } else if(!isEmptyView && currentLayout !== 'default-sidebar-1') {
                this.props.setConfig('layout', 'default-sidebar-1')
            }
        }

        render() {
            let {layout, background, navbar, logo, leftSidebar, topNavigation, collapsed} = this.props.config
            // let {pathname} = this.props
            let isEmptyView = layout === 'empty-view-1' ? true : false
            return (
                <ConnectedRouter history={history}>

                        <Shortcuts />
                        <Backdrops />
                        {!isEmptyView &&
                        <RightSidebar1 />
                        }
                        {!isEmptyView &&
                        <Navbar1 />
                        }

                                {!isEmptyView &&
                                <LeftSidebar1 />
                                }

                                    <Switch>
                                        <Route path="/dashboard" component={Dashboard} />
                                        <Route path="/policies/index" component={Policies}/>
                                        <Route path="/pages/create-account" component={CreateAccount} />
                                        <Route path="/pages/empty-page" component={EmptyPage} />
                                        <Route path="/pages/under-maintenance" component={UnderMaintenance} />
                                        <Route path="/pages/error-page" component={ErrorPage} />
                                        <Route path="/pages/user-profile" component={UserProfile} />
                                        <Route path="/on-notice" component={OnNotice} />
                                        <Route path="/profile" component={UserProfile} />
                                        <Route path="/kyc-documents" component={KYCDocuments} />
                                        <Route path="/booking" component={Booking} />
                                        <Route path="/bookings" component={Bookings} />

                                        <Route path="/pay-amount" component={Payment} />
                                        <Route path="/security-deposit" component={Deposit} />
                                        <Route path="/transactions" component={Transactions} />
                                        <Route path="/notice-board" component={NoticeBoard} />
                                        <Route path="/deals" component={Deals} />

                                        <Route path="/checkin" component={Checkin} />
                                        <Route path='/subscriptions' component={MySubscriptions} />
                                        <Route path='/view-ticket' component={ViewTicket} />
                                        <Route path="/new-ticket" component={NewTicket} />
                                        <Route component={EmptyPage} />
                                    </Switch>

                </ConnectedRouter>
            )
        }
    }

    const mapStateToProps = (state, ownProps) => {
        return {
            pathname: state.router.location && state.router.location.pathname ? state.router.location.pathname : window.location.pathname,
            config: state.config,
            tickets : state.ticket
        }
    }
    const mapDispatchToProps = dispatch => {
        return {
            setConfig: (key, value) => dispatch(setConfig(key, value))
        }
    }
    export default connect(mapStateToProps, mapDispatchToProps)(customer)

I want to know how to do routing header and sidebar shouldn't be shown for non logged in user, there are few pages user can access without sign in

Above code which i have written is not routing.

Please guide me in right direction

Body:
router is old one method you can use ReactRouter (flowRouter kadira) package for easy routing

group.route('/', {
        name: 'Routes.Task.List',
        action () {
            let props = {
                content: (<Containers.List />),
                title: 'title xyz',
                pageTitle: 'title xyz',
            };

            mount(Wrapper, { props });
        },
    });

and now you can use this as flowRouter.path('Routes.Task.List')


问:
how to notify a UIViewController that a button was clicked in a xib file using a delegate in swift?
I'm a bit stuck.
I have a UIViewController and a custom pop.xib that extends UIView.
pop.xib is connected to pop.swift.
In the UIViewController a button makes the .xib file pop up.

And in pop.xib there is a button that is clicked to send some data to the database.

But when that button is clicked in pop.xib to send data I want the UIViewController to

a) know when the @IBAction func sendDataToDbAction(_ sender: Any) is clicked and

b) when the if statement returns false from inside sendDataToDbAction then present an alert on the UIViewController

```<code>//pop.swift

     class Pop: UIView {

            @IBOutlet var delegate: AnswerDelegate?

            @IBAction func sendDataToDbAction(_ sender: Any)
            {
                     if(answer == false)
                     {
                          don't send to db
                          alert pops up saying answer is false
                     }
                     else
                     {

                     }

            }
         }
</code>```

I've set up a delegate in pop.swift

```<code>//pop.swift

@objc protocol AnswerDelegate {

    func isCorrectAnswer()
}

//UIViewController

extension UIViewController:AnswerDelegate{

//set the pop.xib delegate to self
// implement func isCorrectAnswer

}
</code>```

I'm just not sure how I can use the delegate to do what I want.

Thanks.

答:
Check this out, you can do it like this.

Pop.swift

```<code>@objc protocol AnswerDelegate {
    func isCorrectAnswer()
}

class Pop: UIView {

    var answerDelegate: AnswerDelegate?

    class func instanceFromNib() -> Pop {
        return UINib(nibName: "Pop", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! Pop
    }

    @IBAction func sendDataToDbAction(_ sender: Any)
    {
        if(answer == false) {
            //Alert
        }
        else {
            answerDelegate?.isCorrectAnswer()
        }
    }
}
</code>```

Controller:

```<code>class ViewController: UIViewController, AnswerDelegate {

    func isCorrectAnswer() {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let popView = Pop.instanceFromNib()
        popView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        popView.answerDelegate = self

        self.view.addSubview(popView)
    }
}
</code>```

Body:
I'm a bit stuck.
I have a UIViewController and a custom pop.xib that extends UIView.
pop.xib is connected to pop.swift.
In the UIViewController a button makes the .xib file pop up.

And in pop.xib there is a button that is clicked to send some data to the database.

But when that button is clicked in pop.xib to send data I want the UIViewController to

a) know when the @IBAction func sendDataToDbAction(_ sender: Any) is clicked and

b) when the if statement returns false from inside sendDataToDbAction then present an alert on the UIViewController

//pop.swift

     class Pop: UIView {

            @IBOutlet var delegate: AnswerDelegate?

            @IBAction func sendDataToDbAction(_ sender: Any)
            {
                     if(answer == false)
                     {
                          don't send to db
                          alert pops up saying answer is false
                     }
                     else
                     {

                     }

            }
         }

I've set up a delegate in pop.swift

//pop.swift

@objc protocol AnswerDelegate {

    func isCorrectAnswer()
}

//UIViewController

extension UIViewController:AnswerDelegate{

//set the pop.xib delegate to self
// implement func isCorrectAnswer

}

I'm just not sure how I can use the delegate to do what I want.

Thanks.

Body:
Check this out, you can do it like this.

Pop.swift

@objc protocol AnswerDelegate {
    func isCorrectAnswer()
}

class Pop: UIView {

    var answerDelegate: AnswerDelegate?

    class func instanceFromNib() -> Pop {
        return UINib(nibName: "Pop", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! Pop
    }

    @IBAction func sendDataToDbAction(_ sender: Any)
    {
        if(answer == false) {
            //Alert
        }
        else {
            answerDelegate?.isCorrectAnswer()
        }
    }
}

Controller:

class ViewController: UIViewController, AnswerDelegate {

    func isCorrectAnswer() {

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let popView = Pop.instanceFromNib()
        popView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        popView.answerDelegate = self

        self.view.addSubview(popView)
    }
}


答:
Call calculator(); inside your onCreate()

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

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

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
}
</code>```

Now it's going to working charm

Body:
I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?

public class CalculatorActivity extends AppCompatActivity {

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

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method

    //I want to call that fucntion, and i get an error
    calculator();

}

Body:
Call calculator(); inside your onCreate()

   public class CalculatorActivity extends AppCompatActivity {

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

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
}

Now it's going to working charm


问:
Toast stop working/showing after updated the gradle version to 3.0.1
I have updated the Gradle version from 2.3.3 to 3.0.1
and also updated the JAVA Version from 1.7 to 1.8
Toast which were working perfectly fine before, it stops showing now

the code which I am using in the project

```<code>Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
</code>```

答: please check that in Settings-> Application -> Manager check notification is on. if by accidentally you have set it off then also it affect Toast.

Body:
I have updated the Gradle version from 2.3.3 to 3.0.1
and also updated the JAVA Version from 1.7 to 1.8
Toast which were working perfectly fine before, it stops showing now

the code which I am using in the project

Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();


问:
How can we run performance testing manually for any webpage?
I am not able to find out anywhere that how can we do performance test manually.
Please help me out for this query.
Thanks!</p>

答:
The best way to go for Performance Testing without any tool is to provide a Standard loading time for each page as per one's experience knowledge. Else request the client to provide an ideal time for each page. Against which the loading time can be verified. But in case of multiple user simultaneously JMeter is the best hands on Approach available. Its Open source. Easy to understand. And you get reports too.

But of course there are multiple factors that would hinder the Performance. They are :

Your network speed

The Server speed on which your application is hosted

The number of Simultaneous users using

The Heavy images in pages

Last but not the least unnecessary links, codes, in short memory consumption in Code, could be loops not required. All the gifts from Developer Teams !!


问:
How can I change the program header in sap abap?
I want to change the header name of the ABAP program. What can I do or where can I find the option to edit the header?

答:
To change the program header is more easier than it seems.

Just open you program via SE38 -> Goto -> Properties -> Check the title field and change -> Save

And you are done. :)


问:
I want to drag and drop the image on canvas
I want to drag the image on canvas and it should be dragging again inside canvas when dropped i have done some work i have completed dragging of navbar and buttons and divs  .I am attaching my fiddle please check,
I tried lots of thing but could not  find any solution to resolve this issue.

```<code>my fiddle
</code>```

https://jsfiddle.net/Yousuf_007/d3tyrwp6/

答:
Wrap the img tag with div

```<code><div class="fake tool button ">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" style="width:104px;height:142px;" class=" tool-1">
</div>
</code>```

I updated your example here

EDIT:

If you don't want to wrap the img with div change

```<code>var handle = $("<div>", {
              class: "tool_handle ui-widget-header"
            })
</code>```

to

```<code>var handle = $("<div>, <img>", {
              class: "tool_handle ui-widget-header"
            })
</code>```

This is the updated jsFiddle

Body:
I want to drag the image on canvas and it should be dragging again inside canvas when dropped i have done some work i have completed dragging of navbar and buttons and divs  .I am attaching my fiddle please check,
I tried lots of thing but could not  find any solution to resolve this issue.

my fiddle

https://jsfiddle.net/Yousuf_007/d3tyrwp6/

Body:
Wrap the img tag with div

<div class="fake tool button ">
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" style="width:104px;height:142px;" class=" tool-1">
</div>

I updated your example here

EDIT:

If you don't want to wrap the img with div change

var handle = $("<div>", {
              class: "tool_handle ui-widget-header"
            })

to

var handle = $("<div>, <img>", {
              class: "tool_handle ui-widget-header"
            })

This is the updated jsFiddle


问:
What should be the order of filters in query to optimize queries to use Indexing
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

```<code>Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns
</code>```

Query 2

```<code>Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)
</code>```

Query 3

```<code>Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards
</code>```

Query 4

```<code>Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition
</code>```

EDIT :

Query 5

```<code>Select * from MyTable WHERE T3=1 AND T2=1
</code>```

Query 6

```<code>Select * from MyTable WHERE T3=1 AND T1=1
</code>```

Query 7

```<code>Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2
</code>```

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.

答:
Besides all other points made, if you always use SELECT * FROM MyTable in your queries, more often than not SQL Server's query optimizer will opt to ignore any indices at all and do a table scan - even if there is an index.

Why?

If you ask SQL Server to return all columns in your table, it will eventually have to read the actual data page for each row anyway. Finding rows in the index, and then doing a bookmark lookup into the actual data pages, is a fairly expensive operation - so unless you are very selective with your WHERE clause (selecting a few percent only of the data), then most likely, SQL Server will do a full table scan to get all the data needed.

If you can, always use SELECT (list of columns) FROM Mytable and keep that list of columns as small as possible. In that case, you might be able to have an index that has most of those columns already in it, and then you could add those additional two or three columns as included columns into your index, in order to make it a covering index. This would allow SQL Server to return the values you ask for by simply scanning the non-clustered index - instead of having to do either a lot of expensive bookmark lookup, or do a full table scan.

Body:
I have few doubts. I have heard from some of my colleagues that, if we have created composite Nonclustured index on following table order of all the filters should be in order of Indexed column then Filter.

MyTable (T1, T2, T3, T4, T5)

  Non
  Clustured index(T1, T2) in the order
  T1 then T2

Questions

Which of the queries works faster ?

Does order of Indexed column affects
performance ?

Should Indexed Columns
come first to optimize queries ?

What is the order of processing a
query. Which filter is taken first
while processing a query ? Does it
starts from Last filter and goes on
to first filter ?

Query 1

Select * from MyTable WHERE T1=1 AND T2=2 AND T3=1
--(Indexing will be used) Fastest as T3 has been included after indexed columns

Query 2

Select * from MyTable WHERE T2=1 AND T1=2 AND T3=1
--(No Indexing will be used)

Query 3

Select * from MyTable WHERE T3=1 AND T1=1 AND T2=2
--(Indexing will be used) slower than Query 1 as indexed columns included afterwards

Query 4

Select * from MyTable WHERE T3=1 AND T2=1 AND T1=2
--(No Indexing will be used) slower than Query 2 as indexed columns occurs after non indexed column condition

EDIT :

Query 5

Select * from MyTable WHERE T3=1 AND T2=1

Query 6

Select * from MyTable WHERE T3=1 AND T1=1

Query 7

Select * from MyTable WHERE T3=1 AND T2=1 OR T1=2

Query 8

What does the following order in SSMS index creation means i.e. which filter should come first ?

When I tried to shuffle the order of columns shown in index columns. I saw Bookmark lookups were increasing and Clustured index scan was being used.
But when I uses the same order as shown in image. Then bookmark lookup got removed and also got Index Seek. So I can see order of Columns in index is playing some vital role here but could not sense how.


问:
merge sort program in c++ not working
I have written this program in c++ to implement the merge sort algorithm, but it seems to be giving a run-time error. The moment I enter the data of the array elements it stops responding. Now, I don't know what else to write, as stack overflow can't accept a question mostly code, so here is my code. Please someone tell me what is causing the error.

```<code>#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right)
{
    int i, j, count = left, l[mid-left +1], r[right-mid];
    for(i = 0; i <= mid-left; i++)
    {
        l[i] = arr[left + i];
    }
    for(j = 0; j <= right-mid-1; j++)
    {
        r[j] = arr[j + mid + 1];
    }

    i = j = 0;
    while(i <= mid-left && j <= right-mid-1)
    {
        if(l[i] <= r[j])
        {
            arr[count] = l[i];
            i++;
        }
        else if(r[j] < l[i])
        {
            arr[count] = r[j];
            j++;
        }
        count++;
    }
   while(i <= mid-left)
   {
        arr[count] = l[i];
        i++;count++;
   }
   while(j <= right-mid-1)
   {
        arr[count] = r[j];
        j++;count++;
   }
}
void mergesort(int arr[], int left, int right)
{
    if(left > right) return;
    int mid = (left + right)/2;

    mergesort(arr, left, mid);
    mergesort(arr, mid+1, right);

    merge(arr, left, mid, right);
}
int main()
{
    int n;
    cout<<"No. of elements : ";
    cin>>n;
    int arr[n] ;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    mergesort(arr,0,n-1);
    cout<<"sorted array : \n";
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
</code>```

Edit : Everyone i am using c++14 (GCC compiler) and variable sized array is not a problem in my compiler .I ave used it many times .The main thing i am asking is ,is there any problem in my algorithm usage.

答:
Your main problem was the condition you used for termination of merge sort. When you use if (left > right) and left and right are same, then mid is same as left. So the recursion never stops. Use the following condition.

```<code>void mergesort(int arr[],int left,int right)
{
    if(left >= right) return ;
</code>```

Title: merge sort program in c++ not working

Body:
I have written this program in c++ to implement the merge sort algorithm, but it seems to be giving a run-time error. The moment I enter the data of the array elements it stops responding. Now, I don't know what else to write, as stack overflow can't accept a question mostly code, so here is my code. Please someone tell me what is causing the error.

#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right)
{
    int i, j, count = left, l[mid-left +1], r[right-mid];
    for(i = 0; i <= mid-left; i++)
    {
        l[i] = arr[left + i];
    }
    for(j = 0; j <= right-mid-1; j++)
    {
        r[j] = arr[j + mid + 1];
    }

    i = j = 0;
    while(i <= mid-left && j <= right-mid-1)
    {
        if(l[i] <= r[j])
        {
            arr[count] = l[i];
            i++;
        }
        else if(r[j] < l[i])
        {
            arr[count] = r[j];
            j++;
        }
        count++;
    }
   while(i <= mid-left)
   {
        arr[count] = l[i];
        i++;count++;
   }
   while(j <= right-mid-1)
   {
        arr[count] = r[j];
        j++;count++;
   }
}
void mergesort(int arr[], int left, int right)
{
    if(left > right) return;
    int mid = (left + right)/2;

    mergesort(arr, left, mid);
    mergesort(arr, mid+1, right);

    merge(arr, left, mid, right);
}
int main()
{
    int n;
    cout<<"No. of elements : ";
    cin>>n;
    int arr[n] ;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    mergesort(arr,0,n-1);
    cout<<"sorted array : \n";
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

Edit : Everyone i am using c++14 (GCC compiler) and variable sized array is not a problem in my compiler .I ave used it many times .The main thing i am asking is ,is there any problem in my algorithm usage.

Body:
Your main problem was the condition you used for termination of merge sort. When you use if (left > right) and left and right are same, then mid is same as left. So the recursion never stops. Use the following condition.

void mergesort(int arr[],int left,int right)
{
    if(left >= right) return ;


问:
What is causing this error - "Fatal error: Unable to find local grunt"
I removed the old version of grunt first, then I installed the new grunt version, and then I got this error:

D:\www\grunt-test\grunt grunt-cli: The grunt command line interface.
  (v0.1.4)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or
  grunt hasn't been installed locally to your project. For more
  information about installing and configuring grunt, please see the
  Getting Started guide: http://gruntjs.com/getting-started

Is this because there is not a reference to grunt in my system path? Or something else? I tried to re-install it a few times already.

答:
You can simply run this command:</p>

```<code>npm install grunt --save-dev
</code>```

Body:
You can simply run this command:

npm install grunt --save-dev


问:
Retrieve and print data from dynamic sql query with linq
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

```<code>private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}
</code>```

...

```<code>string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}
</code>```

答: There is Dynamic LINQ by Scott Gu which can be found here but as tvanfosson has already said you really aren't going to solve much with moving to Linq and most likely is more effort then result.</p>

OwnerDisplayName: Noit

Body:
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}

...

string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}

OwnerDisplayName: Nathan W


问:
JUnit Test to test conversion of primitive to wrapper class
What is the best way to unit test conversion of primitive to a Wrapper.
I have written where i pass an array of ints and get back an array of Integers. I know  I could use ClassUtils.isPrimitiveOrWrapper() to check if its a primitive or wrapper but is there another way to do this without using external dependency.

Thanks

答: I suggest you use guava's Ints.asList()</p>

Body: I suggest you use guava's Ints.asList()


问:
Why socketIO call too much connections?
I created my Socket server with Express, SocketIO and Redis

server.js

```<code>var app    = require('express')();
var server = require('http').Server(app);
var io     = require('socket.io')(server);
var redis  = require('redis');

server.listen(8890, function (e) {
    console.log(e);
});
io.on('connection', function (socket) {
    console.log("new client connected");
    var redisClient = redis.createClient();
    redisClient.subscribe('message');

    redisClient.on("message", function(channel, message) {
        console.log("mew message in queue "+ message + "channel");
        socket.emit(channel, message);
    });

    socket.on('disconnect', function() {
        redisClient.quit();
    });

    socket.on('connect_error', function() {
        redisClient.quit();
    });
});
</code>```

From command line, I run node server.js. Its worked.

I also created a html file to connect to that server.
From Browser Console, I run io.connect('http://localhost:8890'). I got as the result

As I see, too much connections (requests).
What happens? What wrong from my code?

答:
You have mismatched client and server versions causing the initial connection to fail and the older client is dumb enough to just keep trying over and over again.  If you are using 2.0.4 on the server, then you must use that version for the client too.  If you serve the client version directly from your server with:

```<code><script src="http://localhost:8890/socket.io/socket.io.js"></script>
</code>```

Then, the socket.io server will automatically give you the right client version.

Or, you can manually link to the right version on your CDN such as https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js.  But client and server versions MUST match.

The advantage of getting the client directly from your own server is that anytime you update your server version of socket.io, the client version will automatically be upgraded for you and kept in perfect sync since the matching client version is built into the server version.

Title: Why socketIO call too much connections?

Body:
I created my Socket server with Express, SocketIO and Redis

server.js

var app    = require('express')();
var server = require('http').Server(app);
var io     = require('socket.io')(server);
var redis  = require('redis');

server.listen(8890, function (e) {
    console.log(e);
});
io.on('connection', function (socket) {
    console.log("new client connected");
    var redisClient = redis.createClient();
    redisClient.subscribe('message');

    redisClient.on("message", function(channel, message) {
        console.log("mew message in queue "+ message + "channel");
        socket.emit(channel, message);
    });

    socket.on('disconnect', function() {
        redisClient.quit();
    });

    socket.on('connect_error', function() {
        redisClient.quit();
    });
});

From command line, I run node server.js. Its worked.

I also created a html file to connect to that server.
From Browser Console, I run io.connect('http://localhost:8890'). I got as the result

As I see, too much connections (requests).
What happens? What wrong from my code?

Body:
You have mismatched client and server versions causing the initial connection to fail and the older client is dumb enough to just keep trying over and over again.  If you are using 2.0.4 on the server, then you must use that version for the client too.  If you serve the client version directly from your server with:

<script src="http://localhost:8890/socket.io/socket.io.js"></script>

Then, the socket.io server will automatically give you the right client version.

Or, you can manually link to the right version on your CDN such as https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js.  But client and server versions MUST match.

The advantage of getting the client directly from your own server is that anytime you update your server version of socket.io, the client version will automatically be upgraded for you and kept in perfect sync since the matching client version is built into the server version.


问:
HTML onclick button not calling javascript function
My HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <script src="scorecard.js"></script>
</head>
<body>
    <div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div>
</body>
</html>
</code>```

My Javascript:

```<code>var a;
var b;
var c;
total;

var scorecard = function()
    {
    a = prompt("What was your score on a?","A");
    b = prompt("What was your score on b?","B");
    c = prompt("What was your score on c?","C");
    total = (a + b + c);
    document.getElementById("A").innerHTML = a;
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };
</code>```

What am I missing? Everything validates yet I can't get it to run in any browser. I'm sure it must be something obvious, however, I have looked at this code and played with it all day and I'm just lost and very frustrated. Any help would be great.

答:
```<code><html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script>
        var a;
        var b;
        var c;
        var total;

        function scorecard()
        {

            a = prompt("What was your score on a?", "A");
            b = prompt("What was your score on b?", "B");
            c = prompt("What was your score on c?", "C");
            total = (a + b + c);
            document.getElementById("A").innerHTML = a;
            document.getElementById("B").innerHTML = b;
            document.getElementById("C").innerHTML = c;
            document.getElementById("Total").innerHTML = total;
        };
    </script>
</head>
<body>
     <div id="scoreButton"><button onclick="scorecard()">Calculate Score</button></div>
     <h3 id="A"></h3>
     <h3 id="B"></h3>
     <h3 id="C"></h3>
</body>
</code>```

Body:
My HTML:

<!DOCTYPE html>

<button onclick="javascript: scorecard();">Calculate Score</button>

My Javascript:

var a;
var b;
var c;
total;

var scorecard = function()
    {
    a = prompt("What was your score on a?","A");
    b = prompt("What was your score on b?","B");
    c = prompt("What was your score on c?","C");
    total = (a + b + c);
    document.getElementById("A").innerHTML = a;
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };

What am I missing? Everything validates yet I can't get it to run in any browser. I'm sure it must be something obvious, however, I have looked at this code and played with it all day and I'm just lost and very frustrated. Any help would be great.


问:
Allow user to edit label and change text - c# winform
I have a winform with a custom label inherited from a Windows Form Label. I need to allow user to edit this label and change the value.

I know we can use textbox to allow user to edit by changing the readonly property to false.

But the reason why i use label is that i might need to change the orientation of the text and hence the custom label.

So my question is, is it possible to allow user to edit a normal Winform Label?

The post: Editable Label Controls is not a working solution. That also doesn't have an accepted answer.

答:
This isn't the best option by far, however, it's still an option. Set your forms KeyPreview to true, add a KeyDown key event handler to your form and a Click event handler to your label. In the click event handler, have it set a bool to true. Inside the keydown handler, have an if statement that adds the keys pressed to the labels Text property if the bool is true, that way, if the user clicks the label then anything they type will go into the label.

Example code for my horrible description:

```<code>public static Form f1 = new Form();
public static Label l1 = new Label();
public static bool isLabelClicked = false;
</code>```

Then put these in whatever method sets the properties for your form and it's objects.

```<code>f1.KeyPreview = true;
l1.Click += new EventHandler (l1_Clicked);
f1.KeyDown += new KeyEventHandler (f1_keydown);
</code>```

Then have these two methods in your project

```<code>public static void l1_Clicked(object sender, EventArgs e)
{
    isLabelClicked = true;
}

public static void f1_keydown(object sender, KeyEventArgs e)
{
    if (isLabelClicked == true)
    {
        if (e.KeyCode == Keys.A)
        {
            l1.Text += "a";
        }
        else if (e.KeyCode == Keys.B)
        {
            //Etc. For each key
        }
    }
}
</code>```

It's not the most efficient way to do it and you'd need to set a way to make the bool false afterwards so it didn't keep changing the Labels value every time you typed, but it would work.

I'm sure there's also an easier way to handle each different key without writing out a giant if, else if block, just be weary of converting KeyCode since "," can be "Oemcomma". Good luck with your coding :)

Body:
This isn't the best option by far, however, it's still an option. Set your forms KeyPreview to true, add a KeyDown key event handler to your form and a Click event handler to your label. In the click event handler, have it set a bool to true. Inside the keydown handler, have an if statement that adds the keys pressed to the labels Text property if the bool is true, that way, if the user clicks the label then anything they type will go into the label.

Example code for my horrible description:

public static Form f1 = new Form();
public static Label l1 = new Label();
public static bool isLabelClicked = false;

Then put these in whatever method sets the properties for your form and it's objects.

f1.KeyPreview = true;
l1.Click += new EventHandler (l1_Clicked);
f1.KeyDown += new KeyEventHandler (f1_keydown);

Then have these two methods in your project

public static void l1_Clicked(object sender, EventArgs e)
{
    isLabelClicked = true;
}

public static void f1_keydown(object sender, KeyEventArgs e)
{
    if (isLabelClicked == true)
    {
        if (e.KeyCode == Keys.A)
        {
            l1.Text += "a";
        }
        else if (e.KeyCode == Keys.B)
        {
            //Etc. For each key
        }
    }
}

It's not the most efficient way to do it and you'd need to set a way to make the bool false afterwards so it didn't keep changing the Labels value every time you typed, but it would work.

I'm sure there's also an easier way to handle each different key without writing out a giant if, else if block, just be weary of converting KeyCode since "," can be "Oemcomma". Good luck with your coding :)


问:
calling website home page with access token
I want to call website home page from postman.I have one AD application(Ad1) for which I can get accesstoken. Website AD application has given access to this AD applicaiton(Ad).

I can get access token for AD1 application. Now when I try to make get request to home page with that access token, it is sending response with page which says signin to azure active directory.

Why signin is required in this case , since I already have access token?

When I see via fiddler , once I login to website subsequent calls to that website don't pass token but instead pass cookie.I can see that webpage via fiddler also if I pass that same cookie.

For my case is it possible to access webpage with access token?

答:
Your website uses cookie + OpenID Connect authentication probably. It will not accept a Bearer token unless you configure it so.

It is possible if you configure JWT Bearer token authentication to be used as well.


问:
how to scroll the page to bottom whenever the page load?
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

```<code><ion-content  style="background-color: #f5f8fa;">
  <p style="line-height:24px;padding-left:10px;margin-top:20px;text-transform:capitalize;font-size:16px;">{{this.TASKDESC}}</p>
 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">
      <div [style.margin]="list.TAG_FROM === loggedinuser ? '0px 0px 0px -12px':'0px -12px 0px 0px'" [style.float]="list.TAG_FROM === loggedinuser ? 'right':'left'" style="width:33px;height:33px;background-color:#818993;overflow:hidden;color:#fff;z-index:9.9999999;border-radius:50%;font-size:14px;text-align:center;padding-top:7px;" >{{list.TAG_FROM.substring(0,2)}}</div>
      </div>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

答:
try this below code </p>

```<code>import { Component, ViewChild } from '@angular/core';
import { Content } from 'ionic-angular';

...

export class ScrollToBottom {

  @ViewChild(Content) content: Content;

  constructor(){}

  ionViewDidLoad()
  {
     setTimeout(() => {
        this.content.scrollToBottom(300);
     }, 1000);
  }

}
</code>```

Body:
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

<ion-content  style="background-color: #f5f8fa;">

{{this.TASKDESC}}

 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">

{{list.TAG_FROM.substring(0,2)}}

    </ion-item>
  </ion-list>
</ion-content>

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

Body:
try this below code

import { Component, ViewChild } from '@angular/core';
import { Content } from 'ionic-angular';

...

export class ScrollToBottom {

  @ViewChild(Content) content: Content;

  constructor(){}

  ionViewDidLoad()
  {
     setTimeout(() => {
        this.content.scrollToBottom(300);
     }, 1000);
  }

}