问:
Angular 2 type script define error
When define response data to array, error occured:

```<code>public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => this.esriLocation = response.json(),
                  (error) => console.log('ESRI ERROR: ' + error)
          );

          this.testLocation = this.esriLocation.suggestions;
</code>```

Property 'suggestions' does not exisits on type 'any'

Responce

```<code>{
    "suggestions": [{
        "text": "DEU",
        "key": "dHA9MCNsb2M9MTAzOTkwNTEjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzM=",
        "isCollection": false
    }, {
        "text": "ENG",
        "key": "dHA9MCNsb2M9MTA0MDAzOTcjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzU=",
        "isCollection": false
    }]
}
</code>```

How to fix?

答:
try to declare like  below :</p>

```<code>public esriLocation:any;
public testLocation:any;
    this.service.getData().subscribe(
                      (response) => {this.esriLocation = response.json()
                                     this.testLocation = this.esriLocation.suggestions;
                               },
                      (error) => console.log('ESRI ERROR: ' + error)
              );
</code>```

Title: Angular 2 type script define error

Body:
When define response data to array, error occured:

public esriLocation = [];
public testLocation  = [];

 this.service.getData().subscribe(
                  (response) => this.esriLocation = response.json(),
                  (error) => console.log('ESRI ERROR: ' + error)
          );

          this.testLocation = this.esriLocation.suggestions;

Property 'suggestions' does not exisits on type 'any'

Responce

{
    "suggestions": [{
        "text": "DEU",
        "key": "dHA9MCNsb2M9MTAzOTkwNTEjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzM=",
        "isCollection": false
    }, {
        "text": "ENG",
        "key": "dHA9MCNsb2M9MTA0MDAzOTcjbG5nPTQ0I2xicz0xMDk6NDI2MDI4NzU=",
        "isCollection": false
    }]
}

How to fix?

Body:
try to declare like  below :

public esriLocation:any;
public testLocation:any;
    this.service.getData().subscribe(
                      (response) => {this.esriLocation = response.json()
                                     this.testLocation = this.esriLocation.suggestions;
                               },
                      (error) => console.log('ESRI ERROR: ' + error)
              );


来源: stackexchange

问:
What's more readable naming conventions for lookup tables?
We always name lookup tables  - such as Countries,Cities,Regions ... etc  - as below :

EntityName_LK OR LK_EntityName ( Countries_LK OR LK_Countries )

But I ask if any one have more better naming conversions for lookup tables ?

Edit:

We think to make postfix or prefix to solve like a conflict :

if we have User tables and lookup table for UserTypes (ID-Name) and we have a relation many to many between User & UserTypes that make us a table which we can name it like Types_For_User that may make confusion between UserTypes &  Types_For_User So we like to make lookup table UserTypes to be like UserTypesLK to be obvious to all

答:
Before you decide you need the "lookup" moniker, you should try to understand why you are designating some tables as "lookups" and not others. Each table should represent an entity unto itself.

What happens when a table that was designated as a "lookup" grows in scope and is no longer considered a "lookup"? You are either left with changing the table name which can be onerous or leaving it as is and having to explain to everyone that a given table isn't really a "lookup".

A common scenario mentioned in the comments related to a junction table. For example, suppose a User can have multiple "Types" which are expressed in a junction table with two foreign keys. Should that table be called User_UserTypes? To this scenario, I would first say that I prefer to use the suffix Member on the junction table. So we would have Users, UserTypes, UserTypeMembers. Secondly, the word "type" in this context is quite generic. Does a UserType really mean a Role? The term you use can make all the difference. If UserTypes are really Roles, then our table names become Users, Roles, RoleMembers which seems quite clear.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
iOS FBSDKGraphRequest won't return e-mail
I've upgraded an iOS app from using v2.3 to using v2.7 but no matter what I try FBSDKGraphRequest won't return email address compared to the Android counterpart (it's authorized)

My login button

```<code>self.hiddenButton.readPermissions = @[@"email"];
</code>```

Here's my request code

```<code>[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, link, first_name, last_name, email"}]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result2, NSError *error) {
</code>```

here is what it returns

```<code>{
    "first_name" = James;
    id = ********************;
    "last_name" = Mahy;
    link = "https://www.facebook.com/app_scoped_user_id/**************/";
    name = "James Mahy";
}
</code>```

and these are the permissions the login says I have access to

```<code>(
    email,
    "contact_email",
    "public_profile"
)
</code>```

I have tried the answer from https://stackoverflow.com/a/31503463/555148 it doesn't change anything, I have tried recreating the app and still get the same problem.

I've also tried the same request on https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Did%2Cname%2Cemail&version=v2.7 with multiple Facebook users and it just doesn't return email.

Appreciate your help
James

Body:
I've upgraded an iOS app from using v2.3 to using v2.7 but no matter what I try FBSDKGraphRequest won't return email address compared to the Android counterpart (it's authorized)

My login button

self.hiddenButton.readPermissions = @[@"email"];

Here's my request code

[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, link, first_name, last_name, email"}]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result2, NSError *error) {

here is what it returns

{
    "first_name" = James;
    id = ********************;
    "last_name" = Mahy;
    link = "https://www.facebook.com/app_scoped_user_id/**************/";
    name = "James Mahy";
}

and these are the permissions the login says I have access to

(
    email,
    "contact_email",
    "public_profile"
)

I have tried the answer from https://stackoverflow.com/a/31503463/555148 it doesn't change anything, I have tried recreating the app and still get the same problem.

I've also tried the same request on https://developers.facebook.com/tools/explorer?method=GET&path=me%3Ffields%3Did%2Cname%2Cemail&version=v2.7 with multiple Facebook users and it just doesn't return email.

Appreciate your help
James

Body: self.hiddenButton.readPermissions = @[@"public_profile",@"email"];


问:
get the elements from a nested list in LISP
I am trying to figure out how to access the elements in a nested list in LISP. For example:

((3 (1 7) (((5)))) 4)

If I use dolist, i run into the brackets. Is there any method to just get the elements from the list?

答:
This is actually a surprisingly subtle question!  It's in some ways the equivalent of asking: how do I get the nested elements of an HTML DOM, by specifying a pattern. (more on that aspect later)

If you just want to get the non-list elements as a sequence, e.g.

```<code>((3 (1 7) (((5)))) 4) -->
(nth 3 (3 1 7 5 4)) -->
5
</code>```

You can use the 'cheat' way: the flatten function in the CL alexandria library. (via quicklisp)

```<code>(ql:quicklisp :alexandria)
(nth 3 (alexandria:flatten '((3 (1 7) (((5)))) 4)))
</code>```

Which gives us the sought after,

```<code>5
</code>```

But, the alexandrian function is simple enough that we can take a look at the source code itself:

```<code>(defun flatten (list)
  (cond
    ((null list)
     nil)
    ((consp (car list))
     (nconc (flatten (car list)) (flatten (cdr list))))
    ((null (cdr list))
     (cons (car list) nil))
    (t
     (cons (car list) (flatten (cdr list))))))
</code>```

As you can see, it's a recursive function -- at each level of recursion it asks the question: what is the object that I'm flattening?  If it's the empty list, return nil. I'm done!

Otherwise it has to be a non empty list.  If the first element of the list is also a list then flatten that and also flatten the cdr of the function argument list and concatenate the results.

If the first element is not a list and the second element is '(), that must mean we have a list with one element: return it.

The final case case, which exhausts our possibilities is that the first element in the list is an atom while the rest of the list is a list with at least one element.  In that case concatenate the first element with the results of a flatten performed on the rest of the list.

The fact that the description in English is so ponderous shows the power of recursion, (and also my own lack of fluency when describing it).

But there's actually another way your question could interpreted: if I have a list that looks something like: ((n1 (n2 n3) (((n4)))) n5)  How do I get at n2, even if n2 is itself a list?  Our previous recursive algorithm won't work -- it depends on n2 not being a list to know when to stop.  But, we can still use recursion and the very list we're searching as the basis for a pattern:

```<code>;; For each element in our pattern list look for a corresponding
;; element in the target, recursing on lists and skipping atoms that
;; don't match.
(defun extract-from-list (pattern target to-find)
  (dotimes (i (length pattern))
    (let ((ith-pattern (nth i pattern)))
      (cond
        ((consp ith-pattern)
          (let ((results
             (extract-from-list (nth i pattern)
                   (nth i target)
                   to-find)))
             (when results
               (return results))))
         (t
          (if (eq to-find ith-pattern)
             (return (nth i target))))))))
</code>```

Note that,

```<code>(extract-from-list
 '((n1 (n2 n3) (((n4)))) n5)   ;; The pattern describing the list.
 '((3 (1 7) (((5)))) 4)        ;; The list itself.
 'n4)                          ;; which of the elements we want.
</code>```

still returns the old answer:

```<code> 5
</code>```

But,

```<code>(extract-from-list
 '((n1 (n2 n3) (n4)) n5)   ;; The pattern describing the list, note (n4) rather than (((n4)))
 '((3 (1 7) (((5)))) 4)    ;; The list itself.
 'n4)                      ;; The element we want to pull from the list
</code>```

Returns

```<code> ((5))
</code>```

Magic!  One of the aspects of Lisp that makes it so extraordinarily powerful.

Body:
This is actually a surprisingly subtle question!  It's in some ways the equivalent of asking: how do I get the nested elements of an HTML DOM, by specifying a pattern. (more on that aspect later)

If you just want to get the non-list elements as a sequence, e.g.

((3 (1 7) (((5)))) 4) -->
(nth 3 (3 1 7 5 4)) -->
5

You can use the 'cheat' way: the flatten function in the CL alexandria library. (via quicklisp)

(ql:quicklisp :alexandria)
(nth 3 (alexandria:flatten '((3 (1 7) (((5)))) 4)))

Which gives us the sought after,

5

But, the alexandrian function is simple enough that we can take a look at the source code itself:

(defun flatten (list)
  (cond
    ((null list)
     nil)
    ((consp (car list))
     (nconc (flatten (car list)) (flatten (cdr list))))
    ((null (cdr list))
     (cons (car list) nil))
    (t
     (cons (car list) (flatten (cdr list))))))

As you can see, it's a recursive function -- at each level of recursion it asks the question: what is the object that I'm flattening?  If it's the empty list, return nil. I'm done!

Otherwise it has to be a non empty list.  If the first element of the list is also a list then flatten that and also flatten the cdr of the function argument list and concatenate the results.

If the first element is not a list and the second element is '(), that must mean we have a list with one element: return it.

The final case case, which exhausts our possibilities is that the first element in the list is an atom while the rest of the list is a list with at least one element.  In that case concatenate the first element with the results of a flatten performed on the rest of the list.

The fact that the description in English is so ponderous shows the power of recursion, (and also my own lack of fluency when describing it).

But there's actually another way your question could interpreted: if I have a list that looks something like: ((n1 (n2 n3) (((n4)))) n5)  How do I get at n2, even if n2 is itself a list?  Our previous recursive algorithm won't work -- it depends on n2 not being a list to know when to stop.  But, we can still use recursion and the very list we're searching as the basis for a pattern:

;; For each element in our pattern list look for a corresponding
;; element in the target, recursing on lists and skipping atoms that
;; don't match.
(defun extract-from-list (pattern target to-find)
  (dotimes (i (length pattern))
    (let ((ith-pattern (nth i pattern)))
      (cond
        ((consp ith-pattern)
          (let ((results
             (extract-from-list (nth i pattern)
                   (nth i target)
                   to-find)))
             (when results
               (return results))))
         (t
          (if (eq to-find ith-pattern)
             (return (nth i target))))))))

Note that,

(extract-from-list
 '((n1 (n2 n3) (((n4)))) n5)   ;; The pattern describing the list.
 '((3 (1 7) (((5)))) 4)        ;; The list itself.
 'n4)                          ;; which of the elements we want.

still returns the old answer:

 5

But,

(extract-from-list
 '((n1 (n2 n3) (n4)) n5)   ;; The pattern describing the list, note (n4) rather than (((n4)))
 '((3 (1 7) (((5)))) 4)    ;; The list itself.
 'n4)                      ;; The element we want to pull from the list

Returns

 ((5))

Magic!  One of the aspects of Lisp that makes it so extraordinarily powerful.


问:
Regex operation to match a white-space not working
I'm trying to make a condition that matches any amount of spaces in a file name $f. But what I have seems to be matching everything?

```<code>if [[ $f =~ [[:space:]]* ]]; then
    echo found a space
fi
</code>```

This matches i-have-no-spaces.jpg as well as i have spaces.jpg

答:
Don't use *, it means 0 or more matches.

Use

```<code>if [[ $f =~ [[:space:]] ]]; then
    echo "found a space"
fi
</code>```

However in BASH, I suggest to not to use regex for this, just use glob matching with =:

```<code>if [[ $f = *[[:space:]]* ]]; then
    echo "found a space"
fi
</code>```

Body:
I'm trying to make a condition that matches any amount of spaces in a file name $f. But what I have seems to be matching everything?

if [[ $f =~ [[:space:]]* ]]; then
    echo found a space
fi

This matches i-have-no-spaces.jpg as well as i have spaces.jpg

Body:
Don't use *, it means 0 or more matches.

Use

if [[ $f =~ [[:space:]] ]]; then
    echo "found a space"
fi

However in BASH, I suggest to not to use regex for this, just use glob matching with =:

if [[ $f = *[[:space:]]* ]]; then
    echo "found a space"
fi


问:
How to select multiple event date in MaterialCalenderView
I am using MaterialCalendarView library, I want to select events dates problematically (no to be select by user in run time) which will  be multiple, After reading the documentation i saw four cases.

SELECTION_MODE_NONE

SELECTION_MODE_SINGLE

SELECTION_MODE_RANGE

SELECTION_MODE_MULTIPLE

I used SELECTION_MODE_NONE as i don't want user to select date.
I tried this but it doesn't show  me selected days which i passed.

```<code>private MaterialCalendarView materialCalendarView;
materialCalendarView = view.findViewById(R.id.newCal);
 Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 1);
    calendar.set(2017, 12, 7);
    calendar.set(2017, 12, 8);
    calendar.set(2017, 12, 9);
    calendar.set(2017, 12, 10);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);
</code>```

How to implement that? where i am going wrong?

UPDATE:
After taking the login of Umar and Manny i updated my code like this:

```<code>materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 14);

    Calendar calendar2 = Calendar.getInstance();
    calendar.set(2017, 12, 15);

    Calendar calendar3 = Calendar.getInstance();
    calendar.set(2017, 12, 16);

    Calendar calendar4 = Calendar.getInstance();
    calendar.set(2017, 12, 17);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar2, true);
    materialCalendarView.setDateSelected(calendar3, true);
    materialCalendarView.setDateSelected(calendar4, true);
</code>```

So, now i get only the last date selected which is calendar4. But still i am unable to select multiple dates. and by default materialCalendarView selects today's date.

答:
Okay, after doing lots of tweaks and with the suggestions of Manny and Umar i finally found the way how to set multiple days in materialCalendarView. So this is how it done.

I dont want user to select dates from calendar, so added this line in my code:

```<code>materialCalendarView.setSelectionMode (MaterialCalendarView.SELECTION_MODE_NONE);
</code>```

Now i want to set multiple dates, for this i am creating multiple calendar objects and padding dates in it like this...

```<code>Calendar calendar = Calendar.getInstance();
calendar.set(2017, 11, 14);

Calendar calendar1 = Calendar.getInstance();
calendar1.set(2017, 11, 16);
</code>```

And finally it was selecting multiple dates, but it is also selecting today's date which is not a problem. but now when i pass month as 12(december) it is showin me next month 12+1 which means january of next year. So for this i am passing a value less than what i want.

Final Code:

```<code>materialCalendarView.setSelectionMode (MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 11, 14);

    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(2017, 11, 16);

    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar1, true);
</code>```

Thanks Manny and Umar :)

Body:
I am using MaterialCalendarView library, I want to select events dates problematically (no to be select by user in run time) which will  be multiple, After reading the documentation i saw four cases.

SELECTION_MODE_NONE

SELECTION_MODE_SINGLE

SELECTION_MODE_RANGE

SELECTION_MODE_MULTIPLE

I used SELECTION_MODE_NONE as i don't want user to select date.
I tried this but it doesn't show  me selected days which i passed.

private MaterialCalendarView materialCalendarView;
materialCalendarView = view.findViewById(R.id.newCal);
 Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 1);
    calendar.set(2017, 12, 7);
    calendar.set(2017, 12, 8);
    calendar.set(2017, 12, 9);
    calendar.set(2017, 12, 10);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

How to implement that? where i am going wrong?

UPDATE:
After taking the login of Umar and Manny i updated my code like this:

materialCalendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 12, 14);

    Calendar calendar2 = Calendar.getInstance();
    calendar.set(2017, 12, 15);

    Calendar calendar3 = Calendar.getInstance();
    calendar.set(2017, 12, 16);

    Calendar calendar4 = Calendar.getInstance();
    calendar.set(2017, 12, 17);

    materialCalendarView.addDecorator(new CurrentDayDecatator(getActivity()));
    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar2, true);
    materialCalendarView.setDateSelected(calendar3, true);
    materialCalendarView.setDateSelected(calendar4, true);

So, now i get only the last date selected which is calendar4. But still i am unable to select multiple dates. and by default materialCalendarView selects today's date.

Body:
Okay, after doing lots of tweaks and with the suggestions of Manny and Umar i finally found the way how to set multiple days in materialCalendarView. So this is how it done.

I dont want user to select dates from calendar, so added this line in my code:

materialCalendarView.setSelectionMode (MaterialCalendarView.SELECTION_MODE_NONE);

Now i want to set multiple dates, for this i am creating multiple calendar objects and padding dates in it like this...

Calendar calendar = Calendar.getInstance();
calendar.set(2017, 11, 14);

Calendar calendar1 = Calendar.getInstance();
calendar1.set(2017, 11, 16);

And finally it was selecting multiple dates, but it is also selecting today's date which is not a problem. but now when i pass month as 12(december) it is showin me next month 12+1 which means january of next year. So for this i am passing a value less than what i want.

Final Code:

materialCalendarView.setSelectionMode (MaterialCalendarView.SELECTION_MODE_NONE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(2017, 11, 14);

    Calendar calendar1 = Calendar.getInstance();
    calendar1.set(2017, 11, 16);

    materialCalendarView.setDateSelected(calendar, true);
    materialCalendarView.setDateSelected(calendar1, true);

Thanks Manny and Umar :)


问:
Factory Design Pattern - Which class should I use to create a Factory
I have successfully used strategy design pattern to for a Ducks Class and its Subtypes. Below is the diagram of relationships between different classes.

Now, I want to create a Factory to generate instances of different types of ducks. Should I use behavior classes (FlyBehavior and QuackBehavior) or should I use just Duck class to create a Factory class? Thanks. Your help will be appreciated.

答:
Between the options you gave, I would go with factory class to get duck instances on some options.

But I would suggest considering builder pattern here.


问:
Possible to use output of one cell as input to another?
I'd like to take the output from one cell (probably a code cell) and use it as input to the next code cell.  Is that possible?</p>

答: It is possible! Simply store the output from your first cell into a variable and then use the variable as the input in your second cell. Hopefully, that helps, let me know if you need more clarification!</p>


问:
Disable COD when exceeded specific amount

I need to disable Woocommerce COD option and make it unchecked when total price exceeded certain amount.

I tried this code, but does nothing!

```<code>add_filter('woocommerce_available_payment_gateways', 'unsetting_payment_gateway', 10, 1);
function unsetting_payment_gateway( $available_gateways ) {
    global $woocommerce;
    $shipping_cost = WC()->cart->get_cart_shipping_total();
    $amount = $woocommerce->cart->cart_contents_total + $woocommerce->cart->tax_total + $shipping_cost;

  $max = 999.9 * WCPBC()->customer->exchange_rate;

    if($amount >= $max){   ?>
    <script type="text/javascript">
        jQuery(document).ready(function ($) {
          $("#payment_method_cod").disabled = true;
          $("#payment_method_cod").checked = false;
        });
    </script>
    <?php
    add_action( 'woocommerce_review_order_before_payment', 'COD_exceed_amount_before_paying_notice' );
  }
    return $available_gateways;
}

function COD_exceed_amount_before_paying_notice() {
  wc_print_notice( __( 'COD amount exceeded!', 'woocommerce' ), 'notice' );
}
</code>```

答:
You should change your jquery code. Can you please try below code and check your code again. Because that is working for me.</p>

```<code><script type="text/javascript">
        jQuery( document ).ready(function($) {
          $("#payment_method_cod").prop('checked', false);
          $("#payment_method_cod").attr('disabled', true);
        });
    </script>
</code>```

Body:
I need to disable Woocommerce COD option and make it unchecked when total price exceeded certain amount.

I tried this code, but does nothing!

add_filter('woocommerce_available_payment_gateways', 'unsetting_payment_gateway', 10, 1);
function unsetting_payment_gateway( $available_gateways ) {
    global $woocommerce;
    $shipping_cost = WC()->cart->get_cart_shipping_total();
    $amount = $woocommerce->cart->cart_contents_total + $woocommerce->cart->tax_total + $shipping_cost;

  $max = 999.9 * WCPBC()->customer->exchange_rate;

    if($amount >= $max){   ?>

    <?php
    add_action( 'woocommerce_review_order_before_payment', 'COD_exceed_amount_before_paying_notice' );
  }
    return $available_gateways;
}

function COD_exceed_amount_before_paying_notice() {
  wc_print_notice( __( 'COD amount exceeded!', 'woocommerce' ), 'notice' );
}

Body:
You should change your jquery code. Can you please try below code and check your code again. Because that is working for me.

<script type="text/javascript">
        jQuery( document ).ready(function($) {
          $("#payment_method_cod").prop('checked', false);
          $("#payment_method_cod").attr('disabled', true);
        });
    </script>


问:
C# built-in events
After reading the following piece of code :

```<code>[SerializableAttribute]
public delegate void EventHandler<TEventArgs>
(
   object sender,
   TEventArgs e
)
</code>```

Why did not Microsoft guys give Object type for the "e" parameter just like the sender parameter? am I missing something major here?

答:
If they had done that, people would constantly have to cast the args parameter. The point is that you can do things like:

```<code>public event EventHandler<SomeInterestingEventArgs> SomeEvent;
</code>```

and:

```<code>obj.SomeEvent += (sender, args) => Console.WriteLine(args.SomeSpecificProperty);
</code>```

This is a convenient way of replacing the need to declare:

```<code>public delegate void SomeInterestingEventHandler(
    object sender, SomeInterestingEventArgs args);
</code>```

which is what you would have to do without this.

Title: C# built-in events

Body:
After reading the following piece of code :

[SerializableAttribute]
public delegate void EventHandler<TEventArgs>
(
   object sender,
   TEventArgs e
)

Why did not Microsoft guys give Object type for the "e" parameter just like the sender parameter? am I missing something major here?

Body:
If they had done that, people would constantly have to cast the args parameter. The point is that you can do things like:

public event EventHandler<SomeInterestingEventArgs> SomeEvent;

and:

obj.SomeEvent += (sender, args) => Console.WriteLine(args.SomeSpecificProperty);

This is a convenient way of replacing the need to declare:

public delegate void SomeInterestingEventHandler(
    object sender, SomeInterestingEventArgs args);

which is what you would have to do without this.


问:
Webservice behaviour changes with VB and C#
I am trying to communicate with a webservice over SOAP method. The code works with C# and not with VB. Which is strange, I need it to work with VB. Any ideas?

C#

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wsdltest
{
    class Program
    {
        static void Main(string[] args)
        {
        hpsm.APSServer_Service apsServer = new hpsm.APSServer_Service();
        int serviceReturn = 24081987;
        var aTime = new hpsm.Timing();
        aTime.id = "something";
        aTime.endMillis = 100;
        aTime.startMillis = 0;
        aTime.subsystem = "aSubsystem";
        aTime.threadID = "someThreadID";

        var timing = new hpsm.Timing[] { aTime };
        var message = "this is a message";
        var payload = "payload";
        var status = 24081987;

        hpsm.service("testOp", "correlationID", "version", "environment", true, out serviceReturn, ref payload, out status, out message, out timing);

        Console.WriteLine("service return = " +serviceReturn);
        Console.WriteLine("message = " +message);
        Console.WriteLine("status = " +status);
        Console.WriteLine("timing = " + timing);
        Console.WriteLine("payload = " + payload);
        Console.ReadLine();
    }
}
}
</code>```

VB

```<code>Module Module1

    Sub Main()

        Dim hpsm As hpsm.APSServer_Service = New hpsm.APSServer_Service()

        Dim serviceReturn As Integer = 24081987

        Dim message As String = "this is a message"
        Dim payload As String = "payload"
        Dim status = 24081987

        Dim aTime = New hpsm.Timing()
        aTime.id = "something"
        aTime.endMillis = 100
        aTime.startMillis = 0
        aTime.subsystem = "aSubsystem"
        aTime.threadID = "someThreadID"

        Dim timingArray() As hpsm.Timing = {aTime}

        ' call WebService

        hpsm.service("testop", "correlationid", "version", "enviornment", True, serviceReturn, payload, status, message, timingArray)

    End Sub

End Module
</code>```

ERROR

```<code>(from Visual Studio 2017)
System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There was an error generating the XML document.
  Source=System.Xml
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Serialize(SoapClientMessage message)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
       at wsdlVB.hpsm.APSServer_Service.service(String operationName, String correlationID, String version, String environment, Boolean respTimeMonitoring, Int32& serviceReturn, String& payload, Int32& status, String& message, Timing[]& timings) in C:\Users\admhishaam\Documents\Visual Studio 2015\Projects\wsdlVB\wsdlVB\Web References\hpsm\Reference.vb:line 87
       at wsdlVB.Module1.Main() in C:\Users\admhishaam\Documents\Visual Studio 2015\Projects\wsdlVB\wsdlVB\Module1.vb:line 24
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
       HResult=-2147467262
       Message=Specified cast is not valid.
       Source=021yt0yo
       StackTrace:
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAPSServer_Service.Write5_service(Object[] p)
            at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer5.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
            at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
       InnerException:
</code>```

From among the parameters I pass to the "hpsm.service" method, it seems that on VB it is not happy with the parameter 'timing', and complains that it is not able to serialize it. 'timing' is a custom class of that method. Here is the method

```<code>Public Sub service(ByVal operationName As String, ByVal correlationID As String, ByVal version As String, ByVal environment As String, ByVal respTimeMonitoring As Boolean, ByRef serviceReturn As Integer, ByRef payload As String, ByRef status As Integer, ByRef message As String, ByRef timings() As Timing)
            Dim results() As Object = Me.Invoke("service", New Object() {operationName, correlationID, version, environment, respTimeMonitoring, payload})
            serviceReturn = CType(results(0),Integer)
            payload = CType(results(1),String)
            status = CType(results(2),Integer)
            message = CType(results(3),String)
            timings = CType(results(4),Timing())
        End Sub
</code>```

Which is a bit strange.

答: Maybe you could try this converter : http://converter.telerik.com</p>

Body:
I am trying to communicate with a webservice over SOAP method. The code works with C# and not with VB. Which is strange, I need it to work with VB. Any ideas?

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wsdltest
{
    class Program
    {
        static void Main(string[] args)
        {
        hpsm.APSServer_Service apsServer = new hpsm.APSServer_Service();
        int serviceReturn = 24081987;
        var aTime = new hpsm.Timing();
        aTime.id = "something";
        aTime.endMillis = 100;
        aTime.startMillis = 0;
        aTime.subsystem = "aSubsystem";
        aTime.threadID = "someThreadID";

        var timing = new hpsm.Timing[] { aTime };
        var message = "this is a message";
        var payload = "payload";
        var status = 24081987;

        hpsm.service("testOp", "correlationID", "version", "environment", true, out serviceReturn, ref payload, out status, out message, out timing);

        Console.WriteLine("service return = " +serviceReturn);
        Console.WriteLine("message = " +message);
        Console.WriteLine("status = " +status);
        Console.WriteLine("timing = " + timing);
        Console.WriteLine("payload = " + payload);
        Console.ReadLine();
    }
}
}

VB

Module Module1

    Sub Main()

        Dim hpsm As hpsm.APSServer_Service = New hpsm.APSServer_Service()

        Dim serviceReturn As Integer = 24081987

        Dim message As String = "this is a message"
        Dim payload As String = "payload"
        Dim status = 24081987

        Dim aTime = New hpsm.Timing()
        aTime.id = "something"
        aTime.endMillis = 100
        aTime.startMillis = 0
        aTime.subsystem = "aSubsystem"
        aTime.threadID = "someThreadID"

        Dim timingArray() As hpsm.Timing = {aTime}

        ' call WebService

        hpsm.service("testop", "correlationid", "version", "enviornment", True, serviceReturn, payload, status, message, timingArray)

    End Sub

End Module

ERROR

(from Visual Studio 2017)
System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=There was an error generating the XML document.
  Source=System.Xml
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Serialize(SoapClientMessage message)
       at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
       at wsdlVB.hpsm.APSServer_Service.service(String operationName, String correlationID, String version, String environment, Boolean respTimeMonitoring, Int32& serviceReturn, String& payload, Int32& status, String& message, Timing[]& timings) in C:\Users\admhishaam\Documents\Visual Studio 2015\Projects\wsdlVB\wsdlVB\Web References\hpsm\Reference.vb:line 87
       at wsdlVB.Module1.Main() in C:\Users\admhishaam\Documents\Visual Studio 2015\Projects\wsdlVB\wsdlVB\Module1.vb:line 24
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
       HResult=-2147467262
       Message=Specified cast is not valid.
       Source=021yt0yo
       StackTrace:
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAPSServer_Service.Write5_service(Object[] p)
            at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer5.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
            at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
       InnerException:

From among the parameters I pass to the "hpsm.service" method, it seems that on VB it is not happy with the parameter 'timing', and complains that it is not able to serialize it. 'timing' is a custom class of that method. Here is the method

Public Sub service(ByVal operationName As String, ByVal correlationID As String, ByVal version As String, ByVal environment As String, ByVal respTimeMonitoring As Boolean, ByRef serviceReturn As Integer, ByRef payload As String, ByRef status As Integer, ByRef message As String, ByRef timings() As Timing)
            Dim results() As Object = Me.Invoke("service", New Object() {operationName, correlationID, version, environment, respTimeMonitoring, payload})
            serviceReturn = CType(results(0),Integer)
            payload = CType(results(1),String)
            status = CType(results(2),Integer)
            message = CType(results(3),String)
            timings = CType(results(4),Timing())
        End Sub

Which is a bit strange.


问:
What is new name of load_defaults() function in mysql c api?
What is new name of load_defaults() function in mysql c api?

I tried the following code from this link (http://www.kitebird.com/mysql-book/ch06-2ed.pdf). I am using MySQL 5.7 and Visual Studio 2013 on Windows 7/64bit. The load_defaults() function no more exists. There is no documentation on it. What is the new name of load_defaults() function?

```<code>#include <my_global.h>
#include <sql.h>
#include <my_sys.h> //#include <my_getopt.h>

static const char *client_groups[] = { "show_argv","client", NULL };

int main(int argc, char *argv[]) {  int i;

    printf("Original argument vector:\n");  for (i = 0; i < argc; i++)      printf("arg %d: %s\n", i, argv[i]);

    my_init();  my_load_defaults("my", client_groups, &argc, &argv);

    printf("Modified argument vector:\n");  for (i = 0; i < argc; i++)      printf("arg %d: %s\n", i, argv[i]);         exit(0); }
</code>```

答: load_defaults was never meant to be used outside of the client lib. It had therefore been removed from the library exports. I assumed this would still be the case, but then I found: https://bugs.mysql.com/bug.php?id=25535, which seems to indicate this function has been renamed and re-exported. Didn't check this myself, though .

Body:
What is new name of load_defaults() function in mysql c api?

I tried the following code from this link (http://www.kitebird.com/mysql-book/ch06-2ed.pdf). I am using MySQL 5.7 and Visual Studio 2013 on Windows 7/64bit. The load_defaults() function no more exists. There is no documentation on it. What is the new name of load_defaults() function?

#include <my_global.h>
#include <sql.h>
#include <my_sys.h> //#include <my_getopt.h>

static const char *client_groups[] = { "show_argv","client", NULL };

int main(int argc, char *argv[]) {  int i;

    printf("Original argument vector:\n");  for (i = 0; i < argc; i++)      printf("arg %d: %s\n", i, argv[i]);

    my_init();  my_load_defaults("my", client_groups, &argc, &argv);

    printf("Modified argument vector:\n");  for (i = 0; i < argc; i++)      printf("arg %d: %s\n", i, argv[i]);         exit(0); }


问:
How to fetch the latest records and status from a group?
This is what my data looks like

You will notice there are 3 groups of rows; only the createdAt, Status columns are different. I want to fetch the "latest" record from each group, i.e the highlighted rows, with PK = {3,6,9}.

Can this be done with one SQL statement? (dialect is Microsoft SQL Server)

答:
You have the TOP command in MS SQLSERVER so you can do

```<code>SELECT * FROM (
      SELECT TOP 1 * FROM Table WHERE your_where_clauses
      order by your-order-field ASC (DESC IF YOU WANT LAST RECORDS)
)
</code>```

Even if the question is answered with other approach you can achieve the expected result with TOP command.

Hope this helps

Body:
You have the TOP command in MS SQLSERVER so you can do

SELECT * FROM (
      SELECT TOP 1 * FROM Table WHERE your_where_clauses
      order by your-order-field ASC (DESC IF YOU WANT LAST RECORDS)
)

Even if the question is answered with other approach you can achieve the expected result with TOP command.

Hope this helps


问:
css active class not working for Tabs
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

```<code>.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}
</code>```

答:
There have a simple problem with your jquery , you writhe the condition outside the click function , thats why the active class didn't added , now thats solved check with snippet run this working snippet

$(document).ready(function(){

    $(".filter-button").click(function(){
        var value = $(this).attr('data-filter');

        if(value == "all")
        {
            //$('.filter').removeClass('hidden');
            $('.filter').show('1000');
        }
        else
        {
//            $('.filter[filter-item="'+value+'"]').removeClass('hidden');
//            $(".filter").not('.filter[filter-item="'+value+'"]').addClass('hidden');
            $(".filter").not('.'+value).hide('3000');
            $('.filter').filter('.'+value).show('3000');

        }
  $(".filter-button").removeClass('active');
  $(this).addClass("active");
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a, a:focus, a:active, * {
    outline:0 !important;
   }

.gallery-title
{
    font-size: 36px;
    color: #42B32F;
    text-align: center;
    font-weight: 500;
    margin-bottom: 70px;
}
.gallery-title:after {
    content: "";
    position: absolute;
    width: 7.5%;
    left: 46.5%;
    height: 45px;
    border-bottom: 1px solid #5e5e5e;
}
.filter-button
{
     padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}

.port-image
{
    width: 100%;
}

.gallery_product
{
    margin-bottom: 30px;
}

.gallery_heading_pan {
 width: 96%;
 text-align: center;
 float: left;
 padding: 15px 2%;
 font-size: 20px;
 font-weight: 500;
 color: #333;
 }

.image_gly {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.gallery_nf:hover .image_gly {
  opacity: 0.3;
}

.gallery_nf:hover .middle {
  opacity: 1;
}

.text {
  border-radius: 10px;
  background-color: #fd0009;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
} </code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

            <button class="btn btn-default filter-button" data-filter="all">All</button>
            <button class="btn btn-default filter-button active" data-filter="hdpe">HDPE Pipes</button>
            <button class="btn btn-default filter-button" data-filter="sprinkle">Sprinkle Pipes</button>
            <button class="btn btn-default filter-button" data-filter="spray">Spray Nozzle</button>
            <button class="btn btn-default filter-button" data-filter="irrigation">Irrigation Pipes</button>

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

Heading Text here

   ```

Title: css active class not working for Tabs

Body:
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}

Body:
There have a simple problem with your jquery , you writhe the condition outside the click function , thats why the active class didn't added , now thats solved check with snippet run this working snippet

$(document).ready(function(){

    $(".filter-button").click(function(){
        var value = $(this).attr('data-filter');

        if(value == "all")
        {
            //$('.filter').removeClass('hidden');
            $('.filter').show('1000');
        }
        else
        {
//            $('.filter[filter-item="'+value+'"]').removeClass('hidden');
//            $(".filter").not('.filter[filter-item="'+value+'"]').addClass('hidden');
            $(".filter").not('.'+value).hide('3000');
            $('.filter').filter('.'+value).show('3000');

        }
  $(".filter-button").removeClass('active');
  $(this).addClass("active");
    });

});

a, a:focus, a:active, * {
    outline:0 !important;
   }

.gallery-title
{
    font-size: 36px;
    color: #42B32F;
    text-align: center;
    font-weight: 500;
    margin-bottom: 70px;
}
.gallery-title:after {
    content: "";
    position: absolute;
    width: 7.5%;
    left: 46.5%;
    height: 45px;
    border-bottom: 1px solid #5e5e5e;
}
.filter-button
{
     padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}

.port-image
{
    width: 100%;
}

.gallery_product
{
    margin-bottom: 30px;
}

.gallery_heading_pan {
 width: 96%;
 text-align: center;
 float: left;
 padding: 15px 2%;
 font-size: 20px;
 font-weight: 500;
 color: #333;
 }

.image_gly {
  opacity: 1;
  display: block;
  width: 100%;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.middle {
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.gallery_nf:hover .image_gly {
  opacity: 0.3;
}

.gallery_nf:hover .middle {
  opacity: 1;
}

.text {
  border-radius: 10px;
  background-color: #fd0009;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
        <div class="row">
        <div class="gallery col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <h1 class=""></h1>
        </div>

        <div align="center">
            <button class="btn btn-default filter-button" data-filter="all">All</button>
            <button class="btn btn-default filter-button active" data-filter="hdpe">HDPE Pipes</button>
            <button class="btn btn-default filter-button" data-filter="sprinkle">Sprinkle Pipes</button>
            <button class="btn btn-default filter-button" data-filter="spray">Spray Nozzle</button>
            <button class="btn btn-default filter-button" data-filter="irrigation">Irrigation Pipes</button>
        </div>
        <br>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter hdpe" style="display: block;"> <a href="http://dev.ktimes.co/was20378/tab/index-nw2.html#"><img src="./Bootstrap_files/saved_resource" class="img-responsive"></a>
              <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter hdpe" style="display: block;"> <a href="http://dev.ktimes.co/was20378/tab/index-nw2.html#"><img src="./Bootstrap_files/saved_resource" class="img-responsive"></a>
              <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter hdpe" style="display: block;"> <a href="http://dev.ktimes.co/was20378/tab/index-nw2.html#"><img src="./Bootstrap_files/saved_resource" class="img-responsive"></a>
              <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter irrigation" style="display: none;">
            <a href="http://dev.ktimes.co/was20378/tab/index-nw2.html#"><img src="./Bootstrap_files/saved_resource" class="img-responsive"></a>
              <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter spray" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter irrigation" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter spray" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter irrigation" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter irrigation" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter hdpe" style="display: block;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter spray" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>

            <div class="gallery_product col-lg-3 col-md-3 col-sm-4 col-xs-6 filter sprinkle" style="display: none;">
                <img src="./Bootstrap_files/saved_resource" class="img-responsive">
                <div class="gallery_heading_pan">Heading Text here</div>
            </div>
        </div>
    </div>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


问:
Issue with returning object from a function in asp.net MVC
i am little confused about my code:

Here is some function from my controller:

```<code>  public void signIn(string userName, string userPass)
        {
            User user = new User();
            user.getUser(userName , userPass);

            if (user.userName != null)
            {
                Response.Redirect("/Home/Menu");
            }
            else
            {
                Response.Redirect("/Index/Index?Fail=" + "fail");
            }
        }
</code>```

the " user.getUser" suppose to return a User object.. here is the code from my Model directory:

```<code>public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public User getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();

        User uObj = new User();
        uObj = list.FirstOrDefault();

        return uObj;
    }
}
</code>```

when i am debugging the code i can see the uJob object contain values. but when the function end and i return to the controller i see that the user object contain only null values, and the condition - "   if (user.userName != null)" is returning FALSE!.. instead of TRUE..

i would like to get some help. Thanks !

答:
Either you assign the value returned by the getUser method in calling program like this

```<code>user = user.getUser(userName , userPass);
</code>```

Or you change the code in Model like this

```<code>public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public void getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        var user = coll.FirstOrDefault(x => x.userName == name && x.userPass == pass);

        if(user != null)
        {
            this._id = user._id;
            this.userName = user.userName;
            this.userPass = user.userPass;
        }
    }
}
</code>```

Body:
i am little confused about my code:

Here is some function from my controller:

  public void signIn(string userName, string userPass)
        {
            User user = new User();
            user.getUser(userName , userPass);

            if (user.userName != null)
            {
                Response.Redirect("/Home/Menu");
            }
            else
            {
                Response.Redirect("/Index/Index?Fail=" + "fail");
            }
        }

the " user.getUser" suppose to return a User object.. here is the code from my Model directory:

public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public User getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();

        User uObj = new User();
        uObj = list.FirstOrDefault();

        return uObj;
    }
}

when i am debugging the code i can see the uJob object contain values. but when the function end and i return to the controller i see that the user object contain only null values, and the condition - "   if (user.userName != null)" is returning FALSE!.. instead of TRUE..

i would like to get some help. Thanks !

Body:
Either you assign the value returned by the getUser method in calling program like this

user = user.getUser(userName , userPass);

Or you change the code in Model like this

public class User
{
    public ObjectId _id { get; set; }
    public string userName { get; set; }
    public string userPass { get; set; }

    public void getUser(string name , string pass)
    {
        var client = new MongoClient("mongodb://localhost:27017");
        var db = client.GetDatabase("testdb");
        var coll = db.GetCollection<User>("user");

        var user = coll.FirstOrDefault(x => x.userName == name && x.userPass == pass);

        if(user != null)
        {
            this._id = user._id;
            this.userName = user.userName;
            this.userPass = user.userPass;
        }
    }
}


问:
What is best text container for multiline text in IOS
I try to make Android/IOS app with chat in Visual Studio with Xamarin. And I have a problem with chat baloons.  For Android it's ok, I use Text View as message container. But in IOS I met a problem - If I use TextView I got only white rectangles. To implement list of messages I use UITableView with this code

```<code>public override void ViewDidLoad(){
  _chatsMessagesListAdapter = new MessagesTableSourceClass(chatData._messages);
  messagesList.Source = _chatsMessagesListAdapter;
}

public class MessagesTableSourceClass : UITableViewSource
    {
        readonly List<MessageData> _dataList;
        public MessagesTableSourceClass(List<MessageData> dataList)
        {
            _dataList = dataList;
        }
        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return _dataList.Count;
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
OwnerMessageTableViewCell cell = tableView.DequeueReusableCell(MessageTableViewCell.Key) as OwnerMessageTableViewCell ?? OwnerMessageTableViewCell.Create();
cell.BindData(_dataList[indexPath.Row]._message, _dataList[indexPath.Row]._image);
return cell;
        }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);
        }
        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
            return new UIView();
        }
    }
</code>```

OwnerMessageTableViewCell.xib is simple structure TableViewCell -> View -> TextView

But in result TableView messagesList is shown like white rectangle.
Can anybody help me with this problem?

UPDATED
Here the implementation of OwnerMessageTableViewCell

```<code>public partial class OwnerMessageTableViewCell : UITableViewCell
    {
        public static readonly UINib Nib = UINib.FromName("OwnerMessageTableViewCell", NSBundle.MainBundle);
        public static readonly NSString Key = new NSString("OwnerMessageTableViewCell");
        public OwnerMessageTableViewCell (IntPtr handle) : base (handle)
        {
        }
        public static OwnerMessageTableViewCell Create()
        {
            return (OwnerMessageTableViewCell)Nib.Instantiate(null, null)[0];
        }
        internal void BindData(string message, UIImage avatar)
        {
            messageIcon.Image = avatar;
            workerIcon.Hidden = false;
            messageText.Text = message;
        }
    }
</code>```

Here xib file content

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13527"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="252" customClass="OwnerMessageTableViewCell" rowHeight="44">
            <rect key="frame" x="0.0" y="0.0" width="240" height="44"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="252" id="253">
                <rect key="frame" x="0.0" y="0.0" width="240" height="43"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="280" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" clipsSubviews="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="190" y="0.0" width="50" height="50"/>
                        <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="25"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </imageView>
                    <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" textAlignment="justified" id="307" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" text="Message Text here..." editable="NO" selectable="NO">
                        <rect key="frame" x="0.0" y="0.0" width="182" height="50"/>
                        <autoresizingMask key="autoresizingMask"/>
                        <color key="backgroundColor" colorSpace="calibratedRGB" red="0.094117647058823528" green="0.31372549019607843" blue="0.63921568627450975" alpha="1"/>
                        <fontDescription key="fontDescription" type="system" pointSize="14"/>
                        <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                        <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                        <inset key="scrollIndicatorInsets" minX="5" minY="5" maxX="5" maxY="5"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="15"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </textView>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="384" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="220" y="30" width="20" height="20"/>
                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                    </imageView>
                </subviews>
            </tableViewCellContentView>
            <point key="canvasLocation" x="-132.5" y="-317"/>
            <connections>
                <outlet property="messageIcon" destination="280" id="name-outlet-280"/>
                <outlet property="messageText" destination="307" id="name-outlet-307"/>
                <outlet property="workerIcon" destination="384" id="name-outlet-384"/>
            </connections>
            <color key="backgroundColor" colorSpace="calibratedRGB" red="0.54117647058823526" green="0.54117647058823526" blue="0.54117647058823526" alpha="1"/>
        </tableViewCell>
    </objects>
    <resources>
        <image name="chat_bg.jpg" width="414" height="648"/>
    </resources>
</document>
</code>```

UPDATED

Here a screens of VS designer window

;

;

;

答:
You need to adjust the cell height depending on the text .

There are several solutions in native ios, I recommend you to have a look at Auto-Sizing Row Height.

Steps:

modify the Content Hugging Priority and Content Compression Resistance Priority on the UITextView to operate the cell layout

set Estimated RowHeight to enable the Auto-Resizing.

ContentLicense: CC BY-SA 4.0

Body:
I try to make Android/IOS app with chat in Visual Studio with Xamarin. And I have a problem with chat baloons.  For Android it's ok, I use Text View as message container. But in IOS I met a problem - If I use TextView I got only white rectangles. To implement list of messages I use UITableView with this code

public override void ViewDidLoad(){
  _chatsMessagesListAdapter = new MessagesTableSourceClass(chatData._messages);
  messagesList.Source = _chatsMessagesListAdapter;
}

public class MessagesTableSourceClass : UITableViewSource
    {
        readonly List<MessageData> _dataList;
        public MessagesTableSourceClass(List<MessageData> dataList)
        {
            _dataList = dataList;
        }
        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return _dataList.Count;
        }
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
OwnerMessageTableViewCell cell = tableView.DequeueReusableCell(MessageTableViewCell.Key) as OwnerMessageTableViewCell ?? OwnerMessageTableViewCell.Create();
cell.BindData(_dataList[indexPath.Row]._message, _dataList[indexPath.Row]._image);
return cell;
        }
        public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
        {
            tableView.DeselectRow(indexPath, true);
        }
        public override UIView GetViewForFooter(UITableView tableView, nint section)
        {
            return new UIView();
        }
    }

OwnerMessageTableViewCell.xib is simple structure TableViewCell -> View -> TextView

But in result TableView messagesList is shown like white rectangle.
Can anybody help me with this problem?

UPDATED
Here the implementation of OwnerMessageTableViewCell

public partial class OwnerMessageTableViewCell : UITableViewCell
    {
        public static readonly UINib Nib = UINib.FromName("OwnerMessageTableViewCell", NSBundle.MainBundle);
        public static readonly NSString Key = new NSString("OwnerMessageTableViewCell");
        public OwnerMessageTableViewCell (IntPtr handle) : base (handle)
        {
        }
        public static OwnerMessageTableViewCell Create()
        {
            return (OwnerMessageTableViewCell)Nib.Instantiate(null, null)[0];
        }
        internal void BindData(string message, UIImage avatar)
        {
            messageIcon.Image = avatar;
            workerIcon.Hidden = false;
            messageText.Text = message;
        }
    }

Here xib file content

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13527"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="252" customClass="OwnerMessageTableViewCell" rowHeight="44">
            <rect key="frame" x="0.0" y="0.0" width="240" height="44"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="252" id="253">
                <rect key="frame" x="0.0" y="0.0" width="240" height="43"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="280" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" clipsSubviews="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="190" y="0.0" width="50" height="50"/>
                        <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="25"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </imageView>
                    <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" textAlignment="justified" id="307" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" text="Message Text here..." editable="NO" selectable="NO">
                        <rect key="frame" x="0.0" y="0.0" width="182" height="50"/>
                        <autoresizingMask key="autoresizingMask"/>
                        <color key="backgroundColor" colorSpace="calibratedRGB" red="0.094117647058823528" green="0.31372549019607843" blue="0.63921568627450975" alpha="1"/>
                        <fontDescription key="fontDescription" type="system" pointSize="14"/>
                        <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                        <color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
                        <inset key="scrollIndicatorInsets" minX="5" minY="5" maxX="5" maxY="5"/>
                        <userDefinedRuntimeAttributes>
                            <userDefinedRuntimeAttribute keyPath="layer.cornerRadius" type="number">
                                <real key="value" value="15"/>
                            </userDefinedRuntimeAttribute>
                        </userDefinedRuntimeAttributes>
                    </textView>
                    <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" id="384" translatesAutoresizingMaskIntoConstraints="NO" fixedFrame="YES" image="Images/worker_icon.png">
                        <rect key="frame" x="220" y="30" width="20" height="20"/>
                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                    </imageView>
                </subviews>
            </tableViewCellContentView>
            <point key="canvasLocation" x="-132.5" y="-317"/>
            <connections>
                <outlet property="messageIcon" destination="280" id="name-outlet-280"/>
                <outlet property="messageText" destination="307" id="name-outlet-307"/>
                <outlet property="workerIcon" destination="384" id="name-outlet-384"/>
            </connections>
            <color key="backgroundColor" colorSpace="calibratedRGB" red="0.54117647058823526" green="0.54117647058823526" blue="0.54117647058823526" alpha="1"/>
        </tableViewCell>
    </objects>
    <resources>
        <image name="chat_bg.jpg" width="414" height="648"/>
    </resources>
</document>

UPDATED

Here a screens of VS designer window

;

;

;


问:
Recursive Feature Elimination (RFE) SKLearn
I created a table to test my understanding

```<code>    F1  F2  Outcome
0   2   5        1
1   4   8        2
2   6   0        3
3   9   8        4
4  10   6        5
</code>```

From F1 and F2 I tried to predict Outcome

As you can see F1 have a strong correlation to Outcome,F2 is random noise

I tested

```<code>pca = PCA(n_components=2)
fit = pca.fit(X)
print("Explained Variance")
print(fit.explained_variance_ratio_)
Explained Variance
[ 0.57554896  0.42445104]
</code>```

Which is what I expected and shows that F1 is more important

However when I do RFE (Recursive Feature Elimination)

```<code>model = LogisticRegression()
rfe = RFE(model, 1)
fit = rfe.fit(X, Y)
print(fit.n_features_)
print(fit.support_)
print(fit.ranking_)
1
[False  True]
[2 1]
</code>```

It asked me to keep F2 instead? It should ask me to keep F1 since F1 is a strong predictor while F2 is random noise... why F2?

Thanks

答:
You are using LogisticRegression model. This is a classifier, not a regressor. So your outcome here is treated as labels (not numbers). For good training and prediction, a classifier needs multiple samples of each class. But in your data, only single row is present for each class. Hence the results are garbage and not to be taken seriously.

Try replacing that with any regression model and you will see the outcome which you thought would be.

```<code>model = LinearRegression()
rfe = RFE(model, 1)
fit = rfe.fit(X, y)

print(fit.n_features_)
print(fit.support_)
print(fit.ranking_)

# Output
1
[ True False]
[1 2]
</code>```

Body:
I created a table to test my understanding

    F1  F2  Outcome
0   2   5        1
1   4   8        2
2   6   0        3
3   9   8        4
4  10   6        5

From F1 and F2 I tried to predict Outcome

As you can see F1 have a strong correlation to Outcome,F2 is random noise

I tested

pca = PCA(n_components=2)
fit = pca.fit(X)
print("Explained Variance")
print(fit.explained_variance_ratio_)
Explained Variance
[ 0.57554896  0.42445104]

Which is what I expected and shows that F1 is more important

However when I do RFE (Recursive Feature Elimination)

model = LogisticRegression()
rfe = RFE(model, 1)
fit = rfe.fit(X, Y)
print(fit.n_features_)
print(fit.support_)
print(fit.ranking_)
1
[False  True]
[2 1]

It asked me to keep F2 instead? It should ask me to keep F1 since F1 is a strong predictor while F2 is random noise... why F2?

Thanks

Body:
You are using LogisticRegression model. This is a classifier, not a regressor. So your outcome here is treated as labels (not numbers). For good training and prediction, a classifier needs multiple samples of each class. But in your data, only single row is present for each class. Hence the results are garbage and not to be taken seriously.

Try replacing that with any regression model and you will see the outcome which you thought would be.

model = LinearRegression()
rfe = RFE(model, 1)
fit = rfe.fit(X, y)

print(fit.n_features_)
print(fit.support_)
print(fit.ranking_)

# Output
1
[ True False]
[1 2]


问:
How can I activate USB debugging on my phone?
I found a problem with USB debugging in my phone LG V10, that option not accessible to activate.

I am serching for a solution

答:
Please connect your Phone to PC and install all drivers required then you can enable USB Debug option.
Use this for installing Drivers</p>


问:
Calculate the Last day and Hour of the day from Year_Month_Snap String in SQL Server 2014
I am learning SQL Server and am stuck at this conversion issue. Any help is greatly appreciated.

I have a table in SQL Server 2014 with a column Year_Month_Snap which has data in the nvarchar datatype.

I need to obtain the last day and hour of the monthend for 35 consecutive months from 2016 jan.

I see there are many suggestions to snap the fixed day to the YYYY-MM part to make it as YYYY-MM-DD part and convert it to date & datetime, but since the last date of every month varies every month (it may be 30 days month or 31 days or 28/29 days February month) so I need to calculate the last date and hour of the given month from the YYYY-MM nvarchar datatype in the Year_Month_Snap column.

When I try to convert it to the date/datetime, it throws the following error:

Msg 241, Level 16, State 1, Line 25

  Conversion failed when converting date and/or time from character string.

Year_Month_Snap column

Any help is greatly appreciated!!

答:
SQL Server has the function EOMONTH() that gets the last day of each month. Add a day and subtract an hour to get what you need, then stick it in a recursive CTE and off you go :)

```<code>DECLARE @StartDate DATETIME = N'20160101';

WITH times AS
(
    SELECT 1 AS MonthId,
    DATEADD(HOUR, -1, DATEADD(DAY, 1, CONVERT(DATETIME, EOMONTH(@StartDate, 0)))) AS MonthEndTime

    UNION ALL

    SELECT MonthId + 1,
           DATEADD(HOUR, -1, DATEADD(DAY, 1, CONVERT(DATETIME, EOMONTH(MonthEndTime, 1)))) AS MonthEndTime
    FROM times AS t
    WHERE t.MonthId < 35
)

SELECT * FROM times
</code>```

Body:
SQL Server has the function EOMONTH() that gets the last day of each month. Add a day and subtract an hour to get what you need, then stick it in a recursive CTE and off you go :)

DECLARE @StartDate DATETIME = N'20160101';

WITH times AS
(
    SELECT 1 AS MonthId,
    DATEADD(HOUR, -1, DATEADD(DAY, 1, CONVERT(DATETIME, EOMONTH(@StartDate, 0)))) AS MonthEndTime

    UNION ALL

    SELECT MonthId + 1,
           DATEADD(HOUR, -1, DATEADD(DAY, 1, CONVERT(DATETIME, EOMONTH(MonthEndTime, 1)))) AS MonthEndTime
    FROM times AS t
    WHERE t.MonthId < 35
)

SELECT * FROM times


问:
Difference in Load balancing on Azure LoadBancer and Application Gateway?
I have done Load balancing on Azure using Azure Load Balancing and Application Gateway for HTTPS traffic.

In Azure Load Balancer, we can do health check at port 443 while in Application Gateway there are options to upload SSL certs and for health check we can specify a file like index.html on which we can perform health check.

I know that Application Gateway is the right way, but what is the drawback of using Azure Load balancer.

Can someone explain me this.
Thanks

答: Maybe the following table helps understanding the difference between Azure load balancer and Application Gateway:


问:
Trying to retreive int type from function and compare it with $_Get value (mysql PHP)
I trying to  retreive int type from database and compare it with $_Get value

Here is the code for when the user click on the button

```<code>if(isset($_GET['btn_placeorder']))
{

$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];

**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable        ($Blood_BankID,$Type_Ordered);

  try
   {

     if ($Type_Ordered=="" || $Quantity_Ordered=="")
    {
    $error[] = "Valid data is required!";
}

else if($Quantity_Ordered >$number) {
    $error[] = "This Number is not avaliable in our Stock !";
}
</code>```

Here is the code for the function

```<code>function  Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
      global $conn;
# query for getting the value from the database
    $query = "select sum(Blood_quantity) as d from Donor_Blood_Bank   where     Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
  try {

    $statement = $this->conn->prepare($query);
    $statement->execute();
   $result = $statement->fetchall;

   return $result;
} catch(PDOException $e)
    {
        echo $e->getMessage();
    }
</code>```

}

I don't know what is the problem with my code  any help?

答:
First, it should be $result = $statement->fetchAll();(a function or method), not $result = $statement->fetchall (a property).

Second, please read the manul, fetchall() return an array. therefore you can't cast it to int directly. run print_r( $auth_user->Blood_Bankavaliable($Blood_BankID,$Type_Ordered) ); to see yourself.

Body:
I trying to  retreive int type from database and compare it with $_Get value

Here is the code for when the user click on the button

if(isset($_GET['btn_placeorder']))
{

$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];

**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable        ($Blood_BankID,$Type_Ordered);

  try
   {

     if ($Type_Ordered=="" || $Quantity_Ordered=="")
    {
    $error[] = "Valid data is required!";
}

else if($Quantity_Ordered >$number) {
    $error[] = "This Number is not avaliable in our Stock !";
}

Here is the code for the function

function  Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
      global $conn;
# query for getting the value from the database
    $query = "select sum(Blood_quantity) as d from Donor_Blood_Bank   where     Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
  try {

    $statement = $this->conn->prepare($query);
    $statement->execute();
   $result = $statement->fetchall;

   return $result;
} catch(PDOException $e)
    {
        echo $e->getMessage();
    }

}

I don't know what is the problem with my code  any help?


问:
Why is matrix subtraction much slower than dot product in numpy?
Let's say we have a vector and a matrix:

```<code>X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')
</code>```

Why is np.dot(X, Y.T) much faster than X - Y?

```<code>In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop
</code>```

What can I do to make subtraction like this as faster as dot product?

答:
This is just a comment, although you already have checked.

I tested whether the broadcast is a cause, but it was not related to performance at all in this case.

```<code>In [1]: import numpy as np

In [2]: X = np.random.random((1, 384)).astype('float32')
   ...: Y = np.random.random((500000, 384)).astype('float32')

In [3]: %timeit np.dot(X, Y.T)
   ...: %timeit X - Y
27.4 ms ± 910 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
324 ms ± 16.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [4]: import numpy.matlib
   ...: X = np.matlib.repmat(X, 500000, 1)
   ...: print(X.shape)
   ...: %timeit X - Y
(500000, 384)
351 ms ± 20.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Please forgive me I'm not sure how to improve this performance.

Body:
Let's say we have a vector and a matrix:

X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')

Why is np.dot(X, Y.T) much faster than X - Y?

In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop

What can I do to make subtraction like this as faster as dot product?

Body:
This is just a comment, although you already have checked.

I tested whether the broadcast is a cause, but it was not related to performance at all in this case.

In [1]: import numpy as np

In [2]: X = np.random.random((1, 384)).astype('float32')
   ...: Y = np.random.random((500000, 384)).astype('float32')

In [3]: %timeit np.dot(X, Y.T)
   ...: %timeit X - Y
27.4 ms ± 910 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
324 ms ± 16.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [4]: import numpy.matlib
   ...: X = np.matlib.repmat(X, 500000, 1)
   ...: print(X.shape)
   ...: %timeit X - Y
(500000, 384)
351 ms ± 20.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Please forgive me I'm not sure how to improve this performance.


问:
I'd like to produce a function like split (arr, i, j) which divides array arr by axis i, j
I'd like to produce a function like split(arr, i, j), which divides array arr by axis i, j?

But I do not know how to do it. In the following method using array_split. It is impossible for me to obtain the two-dimensional array that we are seeking by merely dividing N-dimensional arrays into N-1 dimensional arrays.

```<code>import numpy as np

arr = np.arange(36).reshape(4,9)
dim = arr.ndim
ax = np.arange(dim)
arritr = [np.array_split(arr, arr.shape[ax[i]], ax[i]) for i in range(dim)]
print(arritr[0])
print(arritr[1])
</code>```

How can I achieve this?

答:
I'm guessing a bit here, but it sounds like you want to divide the array into 4 blocks.

```<code>In [120]: arr = np.arange(36).reshape(6,6)

In [122]: [arr[:3,:4], arr[:3:,4:], arr[3:, :4], arr[3:,4:]]
Out[122]:
[array([[ 0,  1,  2,  3],
        [ 6,  7,  8,  9],
        [12, 13, 14, 15]]),
 array([[ 4,  5],
        [10, 11],
        [16, 17]]),
 array([[18, 19, 20, 21],
        [24, 25, 26, 27],
        [30, 31, 32, 33]]),
 array([[22, 23],
        [28, 29],
        [34, 35]])]
</code>```

Don't worry about efficiency.  array_split does the same sort of slicing.  Check its code to verify that.

If you want more slices, you could add more arr[i1:i2, j1:j2], for any mix of indices.

Body:
I'd like to produce a function like split(arr, i, j), which divides array arr by axis i, j?

But I do not know how to do it. In the following method using array_split. It is impossible for me to obtain the two-dimensional array that we are seeking by merely dividing N-dimensional arrays into N-1 dimensional arrays.

import numpy as np

arr = np.arange(36).reshape(4,9)
dim = arr.ndim
ax = np.arange(dim)
arritr = [np.array_split(arr, arr.shape[ax[i]], ax[i]) for i in range(dim)]
print(arritr[0])
print(arritr[1])

How can I achieve this?

Body:
I'm guessing a bit here, but it sounds like you want to divide the array into 4 blocks.

In [120]: arr = np.arange(36).reshape(6,6)

In [122]: [arr[:3,:4], arr[:3:,4:], arr[3:, :4], arr[3:,4:]]
Out[122]:
[array([[ 0,  1,  2,  3],
        [ 6,  7,  8,  9],
        [12, 13, 14, 15]]),
 array([[ 4,  5],
        [10, 11],
        [16, 17]]),
 array([[18, 19, 20, 21],
        [24, 25, 26, 27],
        [30, 31, 32, 33]]),
 array([[22, 23],
        [28, 29],
        [34, 35]])]

Don't worry about efficiency.  array_split does the same sort of slicing.  Check its code to verify that.

If you want more slices, you could add more arr[i1:i2, j1:j2], for any mix of indices.


问:
Which tag should be used as paragraph separator in Javadoc?
Which is the more appropriate HTML tag for breaking up paragraphs/long sections of javadoc so according to best practices?

Is it
  or
?  Why?

答:
With Java 8, a single starting element(
) works.

Note that javadoc doesn't like the closing element (
).

Body:
With Java 8, a single starting element(<p>) works.

Note that javadoc doesn't like the closing element (</p>).


问:
How to backup entire hdfs data on local machine
We have small CDH cluster of 3 nodes with approx 2TB data. we are planning to expand it but before that current hadoop machines/racks are being relocated. And I just want to make sure I have backup in local machine, in case racks somehow are not relocated (or gets damaged on the way) and we have to install new ones. How do I ensure this?

I have taken snapshot of HDFS data from cloudera manager as backup and it resides on the cluster. But in this case I need to take backup of whole data on local machine or hard drive. Please advise.

答:
Distcp the data somewhere.

Posslible options:

own solution - the temporary cluster - 2TB is not so much, hardware is cheap.

managed solution - to the cloud. There are plenty of storage as a service providers. If not sure, S3 should work for You. Of course data transfer is Your cost, but there is always a trade of between managed service and own crafted.


问:
Unable to get the hidden field Value via ng-model
I'm new to Angular js and I'm Struggling to access the hidden field value via ng-model.Basically I'm using the Modal for editing.Here is my code for controller:

```<code>$scope.update = function(){
            $http({
                method:'POST',
                url:'http://localhost:8000/api/v1/edit',
                data: {id: $scope.editId , name: $scope.edit_name, email: $scope.edit_email, password: $scope.edit_password}
            }).then(function(response){
                $scope.updated_form_data_list = response.data;
            });
        };
    });
</code>```

I'm trying to set the Id for each record via javascript:

```<code><tbody ng-repeat="form_data in form_data_list"> //Displaying records from DB inside the Table
               <tr>
               <td>@{{ form_data.name }}</td>
               <td>@{{ form_data.email }}</td>
               <td>@{{ form_data.password }}</td>
               <td><Button type="button" onclick="setEditId(this.id)" data-toggle="modal" data-target="#modal_content" id="@{{form_data.id}}" ><span class="glyphicon glyphicon-pencil"></span></Button></td>
               </tr>
    </tbody>
</code>```

And I have set the value for hidden via javascript,Here it goes:

```<code><script type="text/javascript"> //setting the value of hidden field with id
    function setEditId(id){
        document.getElementById('editId').value=id;
    }
</script>
</code>```

I have ng-model as editId in the below code:

```<code><div class="modal fade" id="modal_content" role="dialog">
   ...
  <input type="hidden" name="id" id="editId" ng-model="editId">
   ...
<button ng-click="update()">Submit</button>
</code>```

When I click the Submit button I'm able to post other values except the id. Suggest me any Solution for this. Thanking You in Advance!

答:
simple trick...Instead of calling javascript for setting the Id, set that via a controller using ng-click.

```<code>$scope.storeId=function(id){
                $scope.id=id;
}
</code>```

And Called it via

```<code><Button type="button" ng-click="storeId(form_data.id)" data-toggle="modal" data-target="#modal_content">
<span class="glyphicon glyphicon-pencil">
</code>```

Body:
I'm new to Angular js and I'm Struggling to access the hidden field value via ng-model.Basically I'm using the Modal for editing.Here is my code for controller:

$scope.update = function(){
            $http({
                method:'POST',
                url:'http://localhost:8000/api/v1/edit',
                data: {id: $scope.editId , name: $scope.edit_name, email: $scope.edit_email, password: $scope.edit_password}
            }).then(function(response){
                $scope.updated_form_data_list = response.data;
            });
        };
    });

I'm trying to set the Id for each record via javascript:

 //Displaying records from DB inside the Table

               @{{ form_data.name }}
               @{{ form_data.email }}
               @{{ form_data.password }}
               <Button type="button" onclick="setEditId(this.id)" data-toggle="modal" data-target="#modal_content" id="@{{form_data.id}}" ></Button>

And I have set the value for hidden via javascript,Here it goes:

I have ng-model as editId in the below code:

   ...
  <input type="hidden" name="id" id="editId" ng-model="editId">
   ...
<button ng-click="update()">Submit</button>

When I click the Submit button I'm able to post other values except the id. Suggest me any Solution for this. Thanking You in Advance!

Body:
simple trick...Instead of calling javascript for setting the Id, set that via a controller using ng-click.

$scope.storeId=function(id){
                $scope.id=id;
}

And Called it via

<Button type="button" ng-click="storeId(form_data.id)" data-toggle="modal" data-target="#modal_content">
<span class="glyphicon glyphicon-pencil">


问:
Trigger hourly build from scripted Jenkinsfile
Is there a way to trigger a Jenkins job to run every hour using the Jenkinsfile scripted pipeline syntax?

I have seen examples using the declarative syntax, but none using the pipeline syntax.

Declarative Syntax Example

```<code>pipeline {
    agent any

    triggers {
        cron '@daily'
    }

   ...
}
</code>```

答:
The correct version is in a Jenkinsfile "Declarative Pipeline":</p>

```<code>pipeline {
    agent any
    triggers {
        cron('H */4 * * 1-5')
    }
...
}
</code>```

Body:
Is there a way to trigger a Jenkins job to run every hour using the Jenkinsfile scripted pipeline syntax?

I have seen examples using the declarative syntax, but none using the pipeline syntax.

Declarative Syntax Example

pipeline {
    agent any

    triggers {
        cron '@daily'
    }

   ...
}

Body:
The correct version is in a Jenkinsfile "Declarative Pipeline":

pipeline {
    agent any
    triggers {
        cron('H */4 * * 1-5')
    }
...
}


问:
How to break a line of chained methods in Python?
I have a line of the following code (don't blame for naming conventions, they are not mine):

```<code>subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()
</code>```

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

答:
You seems using SQLAlchemy, if it is true, sqlalchemy.orm.query.Query.filter_by() method takes multiple keyword arguments, so you could write like:

```<code>subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word) \
                    .filter_by(subkeyword_company_id=self.e_company_id,
                               subkeyword_word=subkeyword_word,
                               subkeyword_active=True) \
                    .one()
</code>```

But it would be better:

```<code>subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word)
subkeyword = subkeyword.filter_by(subkeyword_company_id=self.e_company_id,
                                  subkeyword_word=subkeyword_word,
                                  subkeyword_active=True)
subkeuword = subkeyword.one()
</code>```

Body:
I have a line of the following code (don't blame for naming conventions, they are not mine):

subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

Body:
You seems using SQLAlchemy, if it is true, sqlalchemy.orm.query.Query.filter_by() method takes multiple keyword arguments, so you could write like:

subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word) \
                    .filter_by(subkeyword_company_id=self.e_company_id,
                               subkeyword_word=subkeyword_word,
                               subkeyword_active=True) \
                    .one()

But it would be better:

subkeyword = Session.query(Subkeyword.subkeyword_id,
                           Subkeyword.subkeyword_word)
subkeyword = subkeyword.filter_by(subkeyword_company_id=self.e_company_id,
                                  subkeyword_word=subkeyword_word,
                                  subkeyword_active=True)
subkeuword = subkeyword.one()