问:
SQL query to combine data from 2 tables with pivot
I have 2 tables:

```<code>CREATE TABLE [ObIndex](
    [idx] [int] IDENTITY(1,1) NOT NULL,
    [dtg] [smalldatetime] NOT NULL,
    [site] [varchar](6) NOT NULL,
    [name] [varchar](32) NOT NULL,
    [lat] [float] NOT NULL,
    [lon] [float] NOT NULL,
    [el] [int] NOT NULL,
 CONSTRAINT [PK_SurfaceObIndex] PRIMARY KEY CLUSTERED
(
    [icao] ASC,
    [dtg] ASC
)
</code>```

and

```<code>CREATE TABLE [ObData](
    [idx] [int] NOT NULL,
    [label] [varchar](32) NOT NULL,
    [value] [varchar](128) NOT NULL,
 CONSTRAINT [PK_SurfaceObData] PRIMARY KEY CLUSTERED
(
    [idx] ASC,
    [label] ASC
)
</code>```

where for each record in ObIndex there will exist one or more records in ObData, each containing a single parameter from the observation (note that stations may have different instruments):

```<code>ObIndex (metadata)
    1,"2017-11-15 12:00:00","C104","AWS 104",-77.100,-167.100,33
    2,"2017-11-15 12:00:00","C105","AWS 105",-77.200,-167.200,55
    etc.

ObData (instrument data)
    1,"Temperature", -10
    1,"DewPoint", -20
    1,"WindDirection", 123
    1,"WindSpeed", 45
    1,"Humidity",66
    2,"Temperature", -10
    2,"DewPoint", -20
    2,"WindDirection", 123
    2,"WindSpeed", 45
    2,"Pressure",998
    etc.
</code>```

There is also a third table of current station locations that is not relevant to this question.

I want to use a single query, if possible, to extract all the values from the ObData table for each ObIndex record, and convert the 'label' values to column names.  This query works for a single observation (or record in ObIndex):

```<code>select
Min(Case label When 'Temperature' Then value End) Temperature,
Min(Case label When 'DewPoint' Then value End) DewPoint
Min(Case label When 'WindSpeed' Then value End) WindSpeed,
Min(Case label When 'WindDirection' Then value End) WindDirection,
From SurfaceObData Where SurfaceObData.idx = 138586
</code>```

Can anyone help me complete the query to return data from all observations?
The results would ideally look like:

```<code>idx,site,dtg,WindDirection,WindSpeed,Temperature,Humidity,Dewpoint,Pressure
1,"C104",2017-11-15 12:00:00,123,45,-10,66,-20,
2,"C106",2017-11-15 12:00:00,123,45,-10,,-20,998
</code>```

(Not sure how to put it in table format... First post.)

Thanks in advance!

答:
just group by the SurfaceObData.idx column

```<code>select SurfaceObData.idx,
       Min(Case label When 'Temperature' Then value End) Temperature,
       Min(Case label When 'DewPoint' Then value End) DewPoint
       Min(Case label When 'WindSpeed' Then value End) WindSpeed,
       Min(Case label When 'WindDirection' Then value End) WindDirection,
From   SurfaceObData
Group By SurfaceObData.idx
</code>```

Body:
I have 2 tables:

CREATE TABLE [ObIndex](
    [idx] [int] IDENTITY(1,1) NOT NULL,
    [dtg] [smalldatetime] NOT NULL,
    [site] [varchar](6) NOT NULL,
    [name] [varchar](32) NOT NULL,
    [lat] [float] NOT NULL,
    [lon] [float] NOT NULL,
    [el] [int] NOT NULL,
 CONSTRAINT [PK_SurfaceObIndex] PRIMARY KEY CLUSTERED
(
    [icao] ASC,
    [dtg] ASC
)

and

CREATE TABLE [ObData](
    [idx] [int] NOT NULL,
    [label] [varchar](32) NOT NULL,
    [value] [varchar](128) NOT NULL,
 CONSTRAINT [PK_SurfaceObData] PRIMARY KEY CLUSTERED
(
    [idx] ASC,
    [label] ASC
)

where for each record in ObIndex there will exist one or more records in ObData, each containing a single parameter from the observation (note that stations may have different instruments):

ObIndex (metadata)
    1,"2017-11-15 12:00:00","C104","AWS 104",-77.100,-167.100,33
    2,"2017-11-15 12:00:00","C105","AWS 105",-77.200,-167.200,55
    etc.

ObData (instrument data)
    1,"Temperature", -10
    1,"DewPoint", -20
    1,"WindDirection", 123
    1,"WindSpeed", 45
    1,"Humidity",66
    2,"Temperature", -10
    2,"DewPoint", -20
    2,"WindDirection", 123
    2,"WindSpeed", 45
    2,"Pressure",998
    etc.

There is also a third table of current station locations that is not relevant to this question.

I want to use a single query, if possible, to extract all the values from the ObData table for each ObIndex record, and convert the 'label' values to column names.  This query works for a single observation (or record in ObIndex):

select
Min(Case label When 'Temperature' Then value End) Temperature,
Min(Case label When 'DewPoint' Then value End) DewPoint
Min(Case label When 'WindSpeed' Then value End) WindSpeed,
Min(Case label When 'WindDirection' Then value End) WindDirection,
From SurfaceObData Where SurfaceObData.idx = 138586

Can anyone help me complete the query to return data from all observations?
The results would ideally look like:

idx,site,dtg,WindDirection,WindSpeed,Temperature,Humidity,Dewpoint,Pressure
1,"C104",2017-11-15 12:00:00,123,45,-10,66,-20,
2,"C106",2017-11-15 12:00:00,123,45,-10,,-20,998

(Not sure how to put it in table format... First post.)

Thanks in advance!

Body:
just group by the SurfaceObData.idx column

select SurfaceObData.idx,
       Min(Case label When 'Temperature' Then value End) Temperature,
       Min(Case label When 'DewPoint' Then value End) DewPoint
       Min(Case label When 'WindSpeed' Then value End) WindSpeed,
       Min(Case label When 'WindDirection' Then value End) WindDirection,
From   SurfaceObData
Group By SurfaceObData.idx


来源: stackexchange

问:
Initialize boolean Array [Java]
i have 2 classes:

```<code>public class A {

    public int min, max;

    public A(int min_arg, int max_arg)
    {
        min = min_arg;
        max = max_arg;
    }

    public int getMin()
    {
        return this.min;
    }
    public int getMax()
    {
        return this.max;
    }
}

public class B
{
    private final boolean[] myBoolean;
    private final A testObject;

    public B(A testObject)
    {
        // I want to do something like this:
        for(int i = testObject.min(); i != testObject.max(); i++)
        {
            myBoolean[i] = false;
        }
    }
}
</code>```

I want to initialize the Array "myBoolean" in the class B and set all Values to false. The problem is, that it won't let me do it.
All it says is that the blank final field "myBoolean" may not be initialized.
I've seen that there's a function called Arrays.fill(array, true/false); but that doesn't help me either.
Does someone know a way to initialize the Array myBoolean with the min->max from class A?
I know that

```<code>private final boolean[] myBoolean;
</code>```

has no size, the size should be the min->max from the class A object. I just can't find a way to do that.

答:
You need to initialize the array first,

myBoolean = new boolean[size];

Additionally, values within boolean arrays are set to false by default.
See here

ContentLicense: CC BY-SA 3.0

Title: Initialize boolean Array [Java]

Body:
i have 2 classes:

public class A {

    public int min, max;

    public A(int min_arg, int max_arg)
    {
        min = min_arg;
        max = max_arg;
    }

    public int getMin()
    {
        return this.min;
    }
    public int getMax()
    {
        return this.max;
    }
}

public class B
{
    private final boolean[] myBoolean;
    private final A testObject;

    public B(A testObject)
    {
        // I want to do something like this:
        for(int i = testObject.min(); i != testObject.max(); i++)
        {
            myBoolean[i] = false;
        }
    }
}

I want to initialize the Array "myBoolean" in the class B and set all Values to false. The problem is, that it won't let me do it.
All it says is that the blank final field "myBoolean" may not be initialized.
I've seen that there's a function called Arrays.fill(array, true/false); but that doesn't help me either.
Does someone know a way to initialize the Array myBoolean with the min->max from class A?
I know that

private final boolean[] myBoolean;

has no size, the size should be the min->max from the class A object. I just can't find a way to do that.


问:
How to call a method on a class through the delegate (multitasking methods)?
I need to call a "refresh method" on one of my classes every time the user returns to my app (multitasking). It seem that for multitasking I need to do this through the app delegate. So what is the best way to call the "refresh method" on my classes self, but from the app delegate?</p>

答:
As mentioned by Vin, you can add it in the applicationWillEnterForeground method.
To update your UI, you can set the application delegate to have a reference to your view controllers and call the update method from there. Or better yet, you can use NSNotificationCenter to simply notify your other classes of the update.

If you decided to add a reference to your view controller from the application delegate, you just have to create a property. This is one way to do it. Please note however that it still depends on the structure of your project.

SampleAppDelegate.h

```<code>SampleViewController *viewController;
...
@property (nonatomic, retain) SampleViewController *sampleViewController;
...
</code>```

SampleAppDelegate.m

```<code>...
@synthesize sampleViewController;
...
// don't forget to release in dealloc
[sampleViewController release]
</code>```

...

You can then assign the value of the app delegate's sampleViewController property wherever you loaded your view controller. So, for example, if you initialized your view controller programmatically on the app delegate's didFinishLaunchingWithOptions method, just assign it there.

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    SampleViewController *_sampleViewController = [[SampleViewController alloc] initWithFrame:CGRectMake(0,0,320,480)];
    self.sampleViewController = _sampleViewController;

    [window addSubview:_sampleViewController.view];
    [sampleViewController release];

    [self.window makeKeyAndVisible];
    return YES;
}
</code>```

If you loaded the view controller outside of the application delegate, you will need to access the app delegate via the sharedApplication's delegate property.

```<code>((SampleAppDelegate*)[UIApplication sharedApplication] delegate).sampleViewController = _sampleViewController;
</code>```

You can then call the update method from the applicationWillEnterForeground method.

```<code>- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background.
     */
    [self.sampleViewController updateMyView];
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As mentioned by Vin, you can add it in the applicationWillEnterForeground method.
To update your UI, you can set the application delegate to have a reference to your view controllers and call the update method from there. Or better yet, you can use NSNotificationCenter to simply notify your other classes of the update.

If you decided to add a reference to your view controller from the application delegate, you just have to create a property. This is one way to do it. Please note however that it still depends on the structure of your project.

SampleAppDelegate.h

SampleViewController *viewController;
...
@property (nonatomic, retain) SampleViewController *sampleViewController;
...

SampleAppDelegate.m

...
@synthesize sampleViewController;
...
// don't forget to release in dealloc
[sampleViewController release]

...

You can then assign the value of the app delegate's sampleViewController property wherever you loaded your view controller. So, for example, if you initialized your view controller programmatically on the app delegate's didFinishLaunchingWithOptions method, just assign it there.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    SampleViewController *_sampleViewController = [[SampleViewController alloc] initWithFrame:CGRectMake(0,0,320,480)];
    self.sampleViewController = _sampleViewController;

    [window addSubview:_sampleViewController.view];
    [sampleViewController release];

    [self.window makeKeyAndVisible];
    return YES;
}

If you loaded the view controller outside of the application delegate, you will need to access the app delegate via the sharedApplication's delegate property.

((SampleAppDelegate*)[UIApplication sharedApplication] delegate).sampleViewController = _sampleViewController;

You can then call the update method from the applicationWillEnterForeground method.

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background.
     */
    [self.sampleViewController updateMyView];
}


问:
When to break up a function
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

```<code>def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
</code>```

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

答:
This code is the correct implementation</p>

```<code>def anti_vowel(c):
    newstr = c
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in c.lower():
        if x in vowels:
            newstr = newstr.replace(x,"")

    return newstr
</code>```

Title: When to break up a function

Body:
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

Body:
This code is the correct implementation

def anti_vowel(c):
    newstr = c
    vowels = ('a', 'e', 'i', 'o', 'u')
    for x in c.lower():
        if x in vowels:
            newstr = newstr.replace(x,"")

    return newstr


问:
How can I perform a generic cast to the correct subclass type?
Currently I have the following code for a method that I have created:

```<code>public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}
</code>```

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

```<code>return this.overlaps((collider.subclassType()) collider);
</code>```

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

```<code>BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}
</code>```

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?

答:
I believe you can do something along the lines of
(exception handling omited)</p>

```<code>public boolean overlaps(CollisionBody2D collider)
{
    Class c = collider.getClass();

    return this.overlaps( c.cast( collider) );
}
</code>```

Body:
Currently I have the following code for a method that I have created:

public boolean overlaps(CollisionBody2D collider)
{
    //other method code
    if (collider instanceof ArcBody2D)
        return this.overlaps((ArcBody2D) collider);
    else if (collider instanceof CircleBody2D)
        return this.overlaps((CircleBody2D) collider);
    else if (collider instanceof PointBody2D)
        return this.overlaps((PointBody2D) collider);
    else if (collider instanceof LineBody2D)
        return this.overlaps((LineBody2D) collider);
    else if (collider instanceof BoxBody2D)
        return this.overlaps((BoxBody2D) collider);
    return false;
}

Each of ArcBody2D etc. are subclasses of CollisionBody2D and have defined methods for collisions for each of the other types (ArcBody2D etc.).I want to replace the eyesore if statement (if instanceof)... with a generic cast down to the proper subclass type so that I do not have to continuously grow the if statement as I add more collider types.

Ideally I am trying to achieve something like:

return this.overlaps((collider.subclassType()) collider);

I have tried using generics, but the problem is that it requires you to predefine the class type, which isn't really helpful to me as I need a method which handles collision without needing to predefine the type of CollisionBody2D when called. For example:

BoxBody2D box = new BoxBody2D(parameters);
CollisionBody2D colliders [];
//populate array
for (CollisionBody2D c: colliders)
{
    if (box.overlaps(c))
        //do something
}

I have tried using generics but the problem is they still require you to define the type when the method is called. Is there any other way to achieve this aside from this long if statement?

Body:
I believe you can do something along the lines of
(exception handling omited)

public boolean overlaps(CollisionBody2D collider)
{
    Class c = collider.getClass();

    return this.overlaps( c.cast( collider) );
}


问:
Android ListView rows in ScrollView not fully displayed - clipped
I encountered a problem when embedding a ListView inside a ScrollView, or at least that's where I guess the problem comes from. The ListView element is a fairly simple one:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/general_background_list_middle"
    android:paddingTop="4dp"
    android:paddingBottom="4dp"
    android:paddingRight="0dp"
    android:paddingLeft="0dp">

    <ImageView
        android:id="@+id/chat_friends_avatar"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginLeft="7dp"
        android:layout_marginRight="8dp"
        android:paddingRight="0dp"
        android:paddingLeft="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/friends_icon_avatar_default"/>

    <TextView
        android:id="@+id/chat_message_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/chat_friends_avatar"
        android:layout_alignParentTop="true"
        android:layout_marginRight="35dp"
        android:maxLines="10"
        android:textSize="12dp"/>

    <TextView
        android:id="@+id/chat_friend_name"
        android:layout_width="140dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        style="@style/SubText"
        android:layout_toRightOf="@id/chat_friends_avatar"
        android:layout_below="@id/chat_message_text" />

    <TextView
        android:id="@+id/chat_message_time"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:layout_marginTop="3dp"
        style="@style/SubText"
        android:layout_alignParentRight="true"
        android:layout_below="@id/chat_message_text" />

</RelativeLayout>
</code>```

However, when I embed a list of such elements in a ScrollView, in between some other elements, the rows are not fully displayed, they are clipped (see image below) if the text is wrapped. The ListView is instantiated as follows in the ScrollView:

```<code><ListView
android:id="@+id/info_chat_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:cacheColorHint="@color/frame_background_color"
android:clickable="false"
android:divider="@null"
android:footerDividersEnabled="false"
android:focusable="false" >
</ListView>
</code>```

If the height of the ListView is set to "wrap_content" only the first element is shown. That's why I'm using a method to calculate the height of the rows of the list:

```<code>private int getCommentsListHeight() {
        if (mChatAdapter != null && mChatAdapter.getCount() != 0) {
            if (mChatList != null) {// && mCommentsListItemHeight == 0) {
                mCommentsListItemHeight = 0;
                for (int i = 0; i < mChatAdapter.getCount(); i++) {
                    // Get view item height
                    View viewItem = mChatAdapter
                            .getView(i, new View(OnAirActivity.this), mChatList);
                    viewItem.measure(0, 0);
                    Logger.d(LOGTAG, "View " + i + " measured height = " + viewItem.getMeasuredHeight());
                    mCommentsListItemHeight += viewItem.getMeasuredHeight();
                }
            }
            //return mChatAdapter.getCount() * mCommentsListItemHeight;
            return mCommentsListItemHeight;
        } else {
            return 0;
        }
    }
</code>```

Unfortunately, in case when the text inside the TextView is wrapped, even over several lines, the height of the row element returned by the getMeasuredHeight() method is constant. Also the getLineCount() called on the TextView inside the row element returns 1 even if the text is wrapped.

On the other hand, if this ListView is embedded in a LinearLayout, everything works fine and the full list is displayed with no clipping.

Do you have any suggestions as to what might be wrong here? I really don't like the idea of manually measuring the height of the list elements and it apparently doesn't work but why can't android nicely stretch the ListView inside the ScrollView to fit it all in there?

Clipped list:

答:
This works for me</p>

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

    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:text="@string/text_list_devices" />

    <ListView
        android:id="@+id/lv_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000"
        android:layout_above="@+id/signup_t"
        android:layout_below="@id/tv_status"
        />

    <Button

        android:id="@+id/signup_t"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"
        android:layout_alignParentBottom="true"
        android:text="Print All Records"
        android:typeface="sans"
        android:layout_marginLeft="45dp"
        android:layout_marginRight="45dp"
        android:textSize="24sp"
        android:background="@drawable/selector_for_button"
        android:textStyle="bold" />
</RelativeLayout>
</code>```

Body:
I encountered a problem when embedding a ListView inside a ScrollView, or at least that's where I guess the problem comes from. The ListView element is a fairly simple one:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/general_background_list_middle"
    android:paddingTop="4dp"
    android:paddingBottom="4dp"
    android:paddingRight="0dp"
    android:paddingLeft="0dp">

    <ImageView
        android:id="@+id/chat_friends_avatar"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:layout_marginLeft="7dp"
        android:layout_marginRight="8dp"
        android:paddingRight="0dp"
        android:paddingLeft="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/friends_icon_avatar_default"/>

    <TextView
        android:id="@+id/chat_message_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/chat_friends_avatar"
        android:layout_alignParentTop="true"
        android:layout_marginRight="35dp"
        android:maxLines="10"
        android:textSize="12dp"/>

    <TextView
        android:id="@+id/chat_friend_name"
        android:layout_width="140dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="3dp"
        style="@style/SubText"
        android:layout_toRightOf="@id/chat_friends_avatar"
        android:layout_below="@id/chat_message_text" />

    <TextView
        android:id="@+id/chat_message_time"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:layout_marginTop="3dp"
        style="@style/SubText"
        android:layout_alignParentRight="true"
        android:layout_below="@id/chat_message_text" />

</RelativeLayout>

However, when I embed a list of such elements in a ScrollView, in between some other elements, the rows are not fully displayed, they are clipped (see image below) if the text is wrapped. The ListView is instantiated as follows in the ScrollView:

<ListView
android:id="@+id/info_chat_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:cacheColorHint="@color/frame_background_color"
android:clickable="false"
android:divider="@null"
android:footerDividersEnabled="false"
android:focusable="false" >
</ListView>

If the height of the ListView is set to "wrap_content" only the first element is shown. That's why I'm using a method to calculate the height of the rows of the list:

private int getCommentsListHeight() {
        if (mChatAdapter != null && mChatAdapter.getCount() != 0) {
            if (mChatList != null) {// && mCommentsListItemHeight == 0) {
                mCommentsListItemHeight = 0;
                for (int i = 0; i < mChatAdapter.getCount(); i++) {
                    // Get view item height
                    View viewItem = mChatAdapter
                            .getView(i, new View(OnAirActivity.this), mChatList);
                    viewItem.measure(0, 0);
                    Logger.d(LOGTAG, "View " + i + " measured height = " + viewItem.getMeasuredHeight());
                    mCommentsListItemHeight += viewItem.getMeasuredHeight();
                }
            }
            //return mChatAdapter.getCount() * mCommentsListItemHeight;
            return mCommentsListItemHeight;
        } else {
            return 0;
        }
    }

Unfortunately, in case when the text inside the TextView is wrapped, even over several lines, the height of the row element returned by the getMeasuredHeight() method is constant. Also the getLineCount() called on the TextView inside the row element returns 1 even if the text is wrapped.

On the other hand, if this ListView is embedded in a LinearLayout, everything works fine and the full list is displayed with no clipping.

Do you have any suggestions as to what might be wrong here? I really don't like the idea of manually measuring the height of the list elements and it apparently doesn't work but why can't android nicely stretch the ListView inside the ScrollView to fit it all in there?

Clipped list:

Body:
This works for me

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

    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:text="@string/text_list_devices" />

    <ListView
        android:id="@+id/lv_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000"
        android:layout_above="@+id/signup_t"
        android:layout_below="@id/tv_status"
        />

    <Button

        android:id="@+id/signup_t"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"
        android:layout_alignParentBottom="true"
        android:text="Print All Records"
        android:typeface="sans"
        android:layout_marginLeft="45dp"
        android:layout_marginRight="45dp"
        android:textSize="24sp"
        android:background="@drawable/selector_for_button"
        android:textStyle="bold" />
</RelativeLayout>


问:
How to detect if browser cookies are enabled in ASP.Net MVC 5?
I've to detect in my ASP.Net MVC application if cookies are disabled in the client's browser. All my searches result in asp.net WebForms with Page_Load etc., instead of an ASP.Net MVC application.

How can I detect on the server side if browser cookies are enabled?

答:
Controller Code :

```<code>public ActionResult Index()
        {
            var browser = Request.Browser;
            string s = "Browser Capabilities\n"
                       + "Type = " + browser.Type + "\n"
                       + "Name = " + browser.Browser + "\n"
                       + "Version = " + browser.Version + "\n"
                       + "Major Version = " + browser.MajorVersion + "\n"
                       + "Minor Version = " + browser.MinorVersion + "\n"
                       + "Platform = " + browser.Platform + "\n"
                       + "Is Beta = " + browser.Beta + "\n"
                       + "Is Crawler = " + browser.Crawler + "\n"
                       + "Is AOL = " + browser.AOL + "\n"
                       + "Is Win16 = " + browser.Win16 + "\n"
                       + "Is Win32 = " + browser.Win32 + "\n"
                       + "Supports Frames = " + browser.Frames + "\n"
                       + "Supports Tables = " + browser.Tables + "\n"
                       + "Supports Cookies = " + browser.Cookies + "\n"
                       + "Supports VBScript = " + browser.VBScript + "\n"
                       + "Supports JavaScript = " +
                       browser.EcmaScriptVersion.ToString() + "\n"
                       + "Supports Java Applets = " + browser.JavaApplets + "\n"
                       + "Supports ActiveX Controls = " + browser.ActiveXControls
                       + "\n"
                       + "Supports JavaScript Version = " +
                       browser["JavaScriptVersion"] + "\n";

            ViewBag.Message = s;
            return View();
        }
</code>```

and you can use in view :

```<code><h3>@ViewBag.Message</h3>
</code>```

Body:
Controller Code :

public ActionResult Index()
        {
            var browser = Request.Browser;
            string s = "Browser Capabilities\n"
                       + "Type = " + browser.Type + "\n"
                       + "Name = " + browser.Browser + "\n"
                       + "Version = " + browser.Version + "\n"
                       + "Major Version = " + browser.MajorVersion + "\n"
                       + "Minor Version = " + browser.MinorVersion + "\n"
                       + "Platform = " + browser.Platform + "\n"
                       + "Is Beta = " + browser.Beta + "\n"
                       + "Is Crawler = " + browser.Crawler + "\n"
                       + "Is AOL = " + browser.AOL + "\n"
                       + "Is Win16 = " + browser.Win16 + "\n"
                       + "Is Win32 = " + browser.Win32 + "\n"
                       + "Supports Frames = " + browser.Frames + "\n"
                       + "Supports Tables = " + browser.Tables + "\n"
                       + "Supports Cookies = " + browser.Cookies + "\n"
                       + "Supports VBScript = " + browser.VBScript + "\n"
                       + "Supports JavaScript = " +
                       browser.EcmaScriptVersion.ToString() + "\n"
                       + "Supports Java Applets = " + browser.JavaApplets + "\n"
                       + "Supports ActiveX Controls = " + browser.ActiveXControls
                       + "\n"
                       + "Supports JavaScript Version = " +
                       browser["JavaScriptVersion"] + "\n";

            ViewBag.Message = s;
            return View();
        }

and you can use in view :

<h3>@ViewBag.Message</h3>


答:
You have to create an array. You have just declared a reference.

```<code>myBoolean = new boolean[100];
</code>```

Or some value N in place of 100.

Title: Initialize boolean Array [Java]

Body:
You have to create an array. You have just declared a reference.

myBoolean = new boolean[100];

Or some value N in place of 100.


问:
SQL - Get average count GROUP BY months
Let's say I have the following structure:

```<code>Ticket |date_created       |date_removed

ticket1|2015-05-14 15:08:65|2015-05-11 10:50:11
</code>```

I'm trying to find the average count of date_removed minus date_created, and then group by months.

Here's what I have so far:

```<code>select AVG(DATEDIFF(day, date_created, date_resolved)) AS 'avg_days' from
my_table
</code>```

gives me the avg number of days for the entire query.
How would I go about grouping by months as well?

I've tried the following:

```<code>select AVG(DATEDIFF(day, date_created, date_resolved)) AS 'avg_days',
MONTH(date_created) AS 'month' from my_table
</code>```

but got the error:

```<code>Incorrect parameter count in the call to native function 'DATEDIFF'
</code>```

答:
Simply add a GROUP BY clause and MySQL's DATEDIFF() (with latter date first) does not take unit parameter like day which you may be confusing different RDBMS methods like SQL Server.

```<code>select MONTH(date_created) AS 'month',
       AVG(DATEDIFF(date_resolved, date_created)) AS 'avg_days',
from my_table
group by MONTH(date_created);
</code>```

Title: SQL - Get average count GROUP BY months

Body:
Let's say I have the following structure:

Ticket |date_created       |date_removed

ticket1|2015-05-14 15:08:65|2015-05-11 10:50:11

I'm trying to find the average count of date_removed minus date_created, and then group by months.

Here's what I have so far:

select AVG(DATEDIFF(day, date_created, date_resolved)) AS 'avg_days' from
my_table

gives me the avg number of days for the entire query.
How would I go about grouping by months as well?

I've tried the following:

select AVG(DATEDIFF(day, date_created, date_resolved)) AS 'avg_days',
MONTH(date_created) AS 'month' from my_table

but got the error:

Incorrect parameter count in the call to native function 'DATEDIFF'

Body:
Simply add a GROUP BY clause and MySQL's DATEDIFF() (with latter date first) does not take unit parameter like day which you may be confusing different RDBMS methods like SQL Server.

select MONTH(date_created) AS 'month',
       AVG(DATEDIFF(date_resolved, date_created)) AS 'avg_days',
from my_table
group by MONTH(date_created);


问:
Wrap async await queries in try catch
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

```<code>let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});
</code>```

答:
You would use async/await with the code that calls getAllUsers rather than using it in getAllUsers itself:

```<code>const getAllUsers = () => {
  return models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
};

router.get(`${path}`, async (req, res) => {
    try {
        const users = await queries.users.getAllUsers();
        res.status(200).json(users);
    } catch (error) {
        res.status(500).send(error)
    }
});
</code>```

Title: Wrap async await queries in try catch

Body:
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});

Body:
You would use async/await with the code that calls getAllUsers rather than using it in getAllUsers itself:

const getAllUsers = () => {
  return models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
};

router.get(`${path}`, async (req, res) => {
    try {
        const users = await queries.users.getAllUsers();
        res.status(200).json(users);
    } catch (error) {
        res.status(500).send(error)
    }
});


答:
Try this out $('#mydiv').find('svg').length)

If svg exists then you will get length as some value, if not then value will be 0.

Hopw this will help you.

Title: How to check if a div has an svg in it using JavaScript?

Body:
I have a div like the following with a question mark in it...

?

In my code, when someone tries to submit a form, I do a check to see if that field has a question mark in it, like this:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('?') !== -1;

That works fine, but now, instead of a question mark in that div, I have an SVG of a question mark (rather than just a text question mark), like this.

  <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>

    <g>
      <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2 c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5 c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4 l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8 c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c1.3-1.4,2-2.9,2-4.8c0-0.9-0.2-1.8-0.5-2.6c-0.4-0.8-0.8-1.5-1.5-2.1c-0.6-0.6-1.3-1.1-2.1-1.5 c-0.8-0.4-1.7-0.5-2.6-0.5c-0.9,0-1.8,0.2-2.6,0.5c-0.8,0.4-1.5,0.8-2.1,1.4c-0.6,0.6-1.1,1.3-1.4,2.1 C18.5,15.3,18.3,16.2,18.3,17.2z M28.5,40.9c0,1-0.3,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1c-1,0-1.8-0.3-2.5-1c-0.7-0.7-1-1.5-1-2.5 c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1C28.2,39.1,28.5,40,28.5,40.9z'/>
      </g>
    </g>
  </svg>

I still want to run a check on that div, but now I have to check to see if it has an SVG in it, rather than just "?".  How can I use JS to check if a div has an svg element in it?

FYI, I tried the following since I thought it would still look for the text, but to no avail...

const fieldText = $('#mydiv').text();
return fieldText.indexOf('svg') !== -1;


问:
c# A better way to Copy/Merge multiple arrays into one array
Would anyone be able to advise if there's a better way to copy multiple arrays into a single array? The resulting array must have the elements in the same order such as arrayOne values first then arraySecond values next etc.

Following is a mockup of what I'm currently executing which working as expected. Looking for a smarter way of doing this.

```<code>// Initialise the first array.
string[] arrayOne = new string[5];
arrayOne[0] = "arrayOneValue[0]";
arrayOne[1] = "arrayOneValue[1]";
arrayOne[2] = "arrayOneValue[2]";
arrayOne[3] = "arrayOneValue[3]";
arrayOne[4] = "arrayOneValue[4]";

// Initialise the second array.
string[] arrayTwo = new string[6];
arrayTwo[0] = "arrayTwoValue[0]";
arrayTwo[1] = "arrayTwoValue[1]";
arrayTwo[2] = "arrayTwoValue[2]";
arrayTwo[3] = "arrayTwoValue[3]";
arrayTwo[4] = "arrayTwoValue[4]";
arrayTwo[5] = "arrayTwoValue[5]";

// Initialise the third array.
string[] arrayThree = new string[3];
arrayThree[0] = "arrayThreeValue[0]";
arrayThree[1] = "arrayThreeValue[1]";
arrayThree[2] = "arrayThreeValue[2]";

// string[] arrayN = new string[n]
//.
//.
//.

// Initialise the target array.
string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length];
// ArrayN - string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length + arrayN.Length];

// Copy/merge the three arrays into the target array.
Array.Copy(arrayOne, 0, finalArray, 0, arrayOne.Length);
Array.Copy(arrayTwo, 0, finalArray, arrayOne.Length, arrayTwo.Length);
Array.Copy(arrayThree, 0, finalArray, (arrayOne.Length + arrayTwo.Length), arrayThree.Length);
//.
//.
//.
//.
// ArrayN - Array.Copy(arrayN, 0, finalArray, (arrayOne.Length + arrayTwo.Length + arrayN), arrayN.Length) ?;
</code>```

As you can see for arrayN the code can get longer. I have a maximum of 5 arrays I'm trying to copy into one array, therefore, it's manageable. I'm using this technique as part of a WebAPI where a collection of oracle parameter objects are consolidated based on business rules to be passed to several Oracle stored procedures. Any advise here is appreciated. Thanks in advance.
Result

```<code>Console output
/*--- Destination array -
arrayOneValue[0]
arrayOneValue[1]
arrayOneValue[2]
arrayOneValue[3]
arrayOneValue[4]
arrayTwoValue[0]
arrayTwoValue[1]
arrayTwoValue[2]
arrayTwoValue[3]
arrayTwoValue[4]
arrayTwoValue[5]
arrayThreeValue[0]
arrayThreeValue[1]
arrayThreeValue[2]*/
</code>```

答:
You can just use LINQ .Concat so that you don't need manually take care of arrays lengths and offsets:

```<code>var finalArray = arrayOne.Concat(arrayTwo).Concat(arrayThree).ToArray();
</code>```

It may be little less performant than using Array.Copy, but this code is much more readable, maintainable and error-safe, which is more important.

Body:
Would anyone be able to advise if there's a better way to copy multiple arrays into a single array? The resulting array must have the elements in the same order such as arrayOne values first then arraySecond values next etc.

Following is a mockup of what I'm currently executing which working as expected. Looking for a smarter way of doing this.

// Initialise the first array.
string[] arrayOne = new string[5];
arrayOne[0] = "arrayOneValue[0]";
arrayOne[1] = "arrayOneValue[1]";
arrayOne[2] = "arrayOneValue[2]";
arrayOne[3] = "arrayOneValue[3]";
arrayOne[4] = "arrayOneValue[4]";

// Initialise the second array.
string[] arrayTwo = new string[6];
arrayTwo[0] = "arrayTwoValue[0]";
arrayTwo[1] = "arrayTwoValue[1]";
arrayTwo[2] = "arrayTwoValue[2]";
arrayTwo[3] = "arrayTwoValue[3]";
arrayTwo[4] = "arrayTwoValue[4]";
arrayTwo[5] = "arrayTwoValue[5]";

// Initialise the third array.
string[] arrayThree = new string[3];
arrayThree[0] = "arrayThreeValue[0]";
arrayThree[1] = "arrayThreeValue[1]";
arrayThree[2] = "arrayThreeValue[2]";

// string[] arrayN = new string[n]
//.
//.
//.

// Initialise the target array.
string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length];
// ArrayN - string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length + arrayN.Length];

// Copy/merge the three arrays into the target array.
Array.Copy(arrayOne, 0, finalArray, 0, arrayOne.Length);
Array.Copy(arrayTwo, 0, finalArray, arrayOne.Length, arrayTwo.Length);
Array.Copy(arrayThree, 0, finalArray, (arrayOne.Length + arrayTwo.Length), arrayThree.Length);
//.
//.
//.
//.
// ArrayN - Array.Copy(arrayN, 0, finalArray, (arrayOne.Length + arrayTwo.Length + arrayN), arrayN.Length) ?;

As you can see for arrayN the code can get longer. I have a maximum of 5 arrays I'm trying to copy into one array, therefore, it's manageable. I'm using this technique as part of a WebAPI where a collection of oracle parameter objects are consolidated based on business rules to be passed to several Oracle stored procedures. Any advise here is appreciated. Thanks in advance.
Result

Console output
/*--- Destination array -
arrayOneValue[0]
arrayOneValue[1]
arrayOneValue[2]
arrayOneValue[3]
arrayOneValue[4]
arrayTwoValue[0]
arrayTwoValue[1]
arrayTwoValue[2]
arrayTwoValue[3]
arrayTwoValue[4]
arrayTwoValue[5]
arrayThreeValue[0]
arrayThreeValue[1]
arrayThreeValue[2]*/

Body:
You can just use LINQ .Concat so that you don't need manually take care of arrays lengths and offsets:

var finalArray = arrayOne.Concat(arrayTwo).Concat(arrayThree).ToArray();

It may be little less performant than using Array.Copy, but this code is much more readable, maintainable and error-safe, which is more important.


问:
I'm trying to split this "for" loop to create 5 different DIV elements
thank you for passing by. I'm really a newbie and I'm trying to do (by taking some code, hopefully there's nothing wrong with that) 5 different players and I've used the following code: https://codepen.io/katzkode/pen/ZbxYYG

I'm trying to split the following loop in 5 different divs (5 different players, instead of #audio-players, there'd be a new div for each one):

```<code>function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

Here's the code to pull the files from:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];
</code>```

And I'm unsure how to proceed, I'm still learning. Thank you.

答:
Seems you just need to loop the array. Use forEach for ease of understanding

function createAudioPlayers() {
  files.forEach(function(f) {
    var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\">" + f + "</button>

";
    $("#audio-players").append(playerString);
  })
}

var files = ["interlude.mp3", // 0
  "chooseyourweapon.mp3", // 1
  "interlude.mp3", // 2
  "scriptures.mp3",
  "scriptures.mp3" // 3
];
createAudioPlayers()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="audio-players"></div></code>```

Body:
thank you for passing by. I'm really a newbie and I'm trying to do (by taking some code, hopefully there's nothing wrong with that) 5 different players and I've used the following code: https://codepen.io/katzkode/pen/ZbxYYG

I'm trying to split the following loop in 5 different divs (5 different players, instead of #audio-players, there'd be a new div for each one):

function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

Here's the code to pull the files from:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

And I'm unsure how to proceed, I'm still learning. Thank you.

Body:
Seems you just need to loop the array. Use forEach for ease of understanding

function createAudioPlayers() {
  files.forEach(function(f) {
    var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\">" + f + "</button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
    $("#audio-players").append(playerString);
  })
}

var files = ["interlude.mp3", // 0
  "chooseyourweapon.mp3", // 1
  "interlude.mp3", // 2
  "scriptures.mp3",
  "scriptures.mp3" // 3
];
createAudioPlayers()

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="audio-players"></div>


问:
Numpy - Count the rows in matrix for which column is the minimum?
So if I have a matrix like this:

```<code>[ 6 9 4 7]
[ 1 2 3 4]
[ 3 5 9 8]
[ 5 7 2 4]
</code>```

I want to know how many times the first column is the minimum. For example, here the answer would be 2, where the 2nd and 3rd row have column 1 as the minimum. I know we can find the minimum using matrix.min(axis=1) from this, and I think we can use numpy.sum to count the number of rows... but how would I actually know from which column the minimum came from? I there some simple way to accomplish this in numpy?

答:
Well if it helps anyone else, due to the argmin suggestion, came up with this approach that works for the first column:

```<code>np.count_nonzero(np.argmin(matrix,axis=1))
</code>```

Not sure about the performance of this method over large matrices or anything like that however.. Of course, this doesn't work for anything but checking minimums on the first column

Body:
So if I have a matrix like this:

[ 6 9 4 7]
[ 1 2 3 4]
[ 3 5 9 8]
[ 5 7 2 4]

I want to know how many times the first column is the minimum. For example, here the answer would be 2, where the 2nd and 3rd row have column 1 as the minimum. I know we can find the minimum using matrix.min(axis=1) from this, and I think we can use numpy.sum to count the number of rows... but how would I actually know from which column the minimum came from? I there some simple way to accomplish this in numpy?

Body:
Well if it helps anyone else, due to the argmin suggestion, came up with this approach that works for the first column:

np.count_nonzero(np.argmin(matrix,axis=1))

Not sure about the performance of this method over large matrices or anything like that however.. Of course, this doesn't work for anything but checking minimums on the first column


问:
How to use dimens.xml in Android?
When I design a layout, I centralize all dimensions in dimens.xml because of topics of maintainability. My question is if this is correct or not. What would it be the best good practice? There is very little information about this, nothing. I know it's good idea to centralize all strings of a layout on strings.xml, colors on colors.xml. But about dimensions?

For example:

```<code><TableLayout
    android:id="@+id/history_detail_rows_submitted"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/cebroker_history_detail_rows_border"
    android:collapseColumns="*">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/history_detail_rows_margin_vertical"
        android:background="@color/cebroker_history_detail_rows_background"
        android:gravity="center"
        android:paddingBottom="@dimen/history_detail_rows_padding_vertical"
        android:paddingLeft="@dimen/history_detail_rows_padding_horizontal"
        android:paddingRight="@dimen/history_detail_rows_padding_horizontal"
        android:paddingTop="@dimen/history_detail_rows_padding_vertical">

        <TextView
            android:layout_width="match_parent"
            android:drawableLeft="@mipmap/ic_history_detail_submitted_by"
            android:drawablePadding="@dimen/history_detail_rows_textviews_padding_drawable"
            android:gravity="left|center"
            android:paddingRight="@dimen/history_detail_rows_textviews_padding"
            android:text="@string/history_detail_textview_submitted_by"
            android:textColor="@color/cebroker_history_detail_rows_textviews"
            android:textSize="@dimen/history_detail_rows_textviews_text_size" />
</code>```

答:
How to use dimens.xml

Create a new dimens.xml file by right clicking the values folder and choosing New > Values resource file. Write dimens for the name. (You could also call it dimen or dimensions. The name doesn't really matter, only the dimen resource type that it will include.)

Add a dimen name and value.

```<code> <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <dimen name="my_value">16dp</dimen>
 </resources>
</code>```

Values can be in dp, px, or sp.

Use the value in xml

```<code> <TextView
     android:padding="@dimen/my_value"
     ... />
</code>```

or in code

```<code> float sizeInPixels = getResources().getDimension(R.dimen.my_value);
</code>```

When to use dimens.xml

Thanks to this answer for more ideas.

Reusing values - If you need to use the same dimension multiple places throughout your app (for example, Activity layout padding or a TextView textSize), then using a single dimen value will make it much easier to adjust later. This is the same idea as using styles and themes.

Supporting Multiple Screens - A padding of 8dp might look fine on a phone but terrible on a 10" tablet. You can create multiple dimens.xml to be used with different screens. That way you could do something like set 8dp for the phone and 64dp for the tablet. To create another dimens.xml file, right click your res folder and choose New > Value resource file. (see this answer for details)

Convenient dp to px code conversion - In code you usually need to work with pixel values. However you still have to think about the device density and the conversion is annoying to do programmatically. If you have a constant dp value, you can get it in pixels easy like this for float:

```<code> float sizeInPixels = getResources().getDimension(R.dimen.my_value);
</code>```

or this for int :

```<code> int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_value);
</code>```

I give many more details of how to do these things in my fuller answer.

When not to use dimens.xml

Don't put your values in dimens.xml if it is going to make them more difficult to maintain. Generally that will be whenever it doesn't fall into the categories I listed above. Using dimens.xml makes the code harder to read because you have to flip back and forth between two files to see what the actual values are. It's not worth it (in my opinion) for individual Views.

Strings are different. All strings should go in a resource file like strings.xml because almost all strings need to be translated when internationalizing your app. Most dimension values, on the other hand, do not need to change for a different locality. Android Studio seems to support this reasoning. Defining a string directly in the layout xml will give a warning but defining a dp value won't.

Title: How to use dimens.xml in Android?

Body:
When I design a layout, I centralize all dimensions in dimens.xml because of topics of maintainability. My question is if this is correct or not. What would it be the best good practice? There is very little information about this, nothing. I know it's good idea to centralize all strings of a layout on strings.xml, colors on colors.xml. But about dimensions?

For example:

<TableLayout
    android:id="@+id/history_detail_rows_submitted"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/cebroker_history_detail_rows_border"
    android:collapseColumns="*">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/history_detail_rows_margin_vertical"
        android:background="@color/cebroker_history_detail_rows_background"
        android:gravity="center"
        android:paddingBottom="@dimen/history_detail_rows_padding_vertical"
        android:paddingLeft="@dimen/history_detail_rows_padding_horizontal"
        android:paddingRight="@dimen/history_detail_rows_padding_horizontal"
        android:paddingTop="@dimen/history_detail_rows_padding_vertical">

        <TextView
            android:layout_width="match_parent"
            android:drawableLeft="@mipmap/ic_history_detail_submitted_by"
            android:drawablePadding="@dimen/history_detail_rows_textviews_padding_drawable"
            android:gravity="left|center"
            android:paddingRight="@dimen/history_detail_rows_textviews_padding"
            android:text="@string/history_detail_textview_submitted_by"
            android:textColor="@color/cebroker_history_detail_rows_textviews"
            android:textSize="@dimen/history_detail_rows_textviews_text_size" />

Body:
How to use dimens.xml

Create a new dimens.xml file by right clicking the values folder and choosing New > Values resource file. Write dimens for the name. (You could also call it dimen or dimensions. The name doesn't really matter, only the dimen resource type that it will include.)

Add a dimen name and value.

 <?xml version="1.0" encoding="utf-8"?>
 <resources>
     <dimen name="my_value">16dp</dimen>
 </resources>

Values can be in dp, px, or sp.

Use the value in xml

 <TextView
     android:padding="@dimen/my_value"
     ... />

or in code

 float sizeInPixels = getResources().getDimension(R.dimen.my_value);

When to use dimens.xml

Thanks to this answer for more ideas.

Reusing values - If you need to use the same dimension multiple places throughout your app (for example, Activity layout padding or a TextView textSize), then using a single dimen value will make it much easier to adjust later. This is the same idea as using styles and themes.

Supporting Multiple Screens - A padding of 8dp might look fine on a phone but terrible on a 10" tablet. You can create multiple dimens.xml to be used with different screens. That way you could do something like set 8dp for the phone and 64dp for the tablet. To create another dimens.xml file, right click your res folder and choose New > Value resource file. (see this answer for details)

Convenient dp to px code conversion - In code you usually need to work with pixel values. However you still have to think about the device density and the conversion is annoying to do programmatically. If you have a constant dp value, you can get it in pixels easy like this for float:

 float sizeInPixels = getResources().getDimension(R.dimen.my_value);

or this for int :

 int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_value);

I give many more details of how to do these things in my fuller answer.

When not to use dimens.xml

Don't put your values in dimens.xml if it is going to make them more difficult to maintain. Generally that will be whenever it doesn't fall into the categories I listed above. Using dimens.xml makes the code harder to read because you have to flip back and forth between two files to see what the actual values are. It's not worth it (in my opinion) for individual Views.

Strings are different. All strings should go in a resource file like strings.xml because almost all strings need to be translated when internationalizing your app. Most dimension values, on the other hand, do not need to change for a different locality. Android Studio seems to support this reasoning. Defining a string directly in the layout xml will give a warning but defining a dp value won't.

ContentLicense: CC BY-SA 4.0


问:
Lastpass changing username
I have a form that username gets pre-populated from the backend. When the page loads, the username is shown in the username field. When lastpass loads, it changes the username to the username that is saved on the lastpass. It looks like a bug that lastpass overwrites the username when it has a value. Is there a way to prevent this?

In the above video, pre defined username is baz@qux.com. After lastpass is loaded, it changes to foo@bar.com.

PS. I'm the developer. I am looking for a way to prevent this from happening for my users.

答:
Use

```<code>data-lpignore="true"
</code>```

On your html element.

According to lastpass documentation:

To prevent LastPass icons on your website or application from appearing on non-desired fields, add 'data-lpignore'=true attribute to your form fields, this will prevent LastPass icons from being generated in this particular locations.

Source: https://lastpass.com/support.php?cmd=showfaq&id=10512

Title: Lastpass changing username

Body:
Use

data-lpignore="true"

On your html element.

According to lastpass documentation:

To prevent LastPass icons on your website or application from appearing on non-desired fields, add 'data-lpignore'=true attribute to your form fields, this will prevent LastPass icons from being generated in this particular locations.

Source: https://lastpass.com/support.php?cmd=showfaq&id=10512


问:
Spark Worker could not find CassandraPartition Class
I am working on spark standalone cluster with a master and 3 workers.
My driver is also on the same network, so basically all the workers and master can communicate with the driver and vice-versa.

I am trying to do the job from the driver by getting the sparksession (in Java program). Maven dependencies added for the program are spark-core_2.11(v2.2), spark-sql_2.11(v2.2), spark-streaming_2.11(v2.2),spark-mllib_2.11(v2.2), spark-cassandra-connector_2.11(v2.0.5), spark-cassandra-connector-java_2.11(v1.6.0-M1).

I am getting the following error in the slave.

```<code>java.lang.ClassNotFoundException: com.datastax.spark.connector.rdd.partitioner.CassandraPartition
    java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    java.lang.Class.forName0(Native Method)
    java.lang.Class.forName(Class.java:348)
    org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1826)
    java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
    java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
    java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
    java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
    java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:309)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    java.lang.Thread.run(Thread.java:748)
</code>```

Could someone help me in figuring out this issue...

Also, the launch command in slave looks like below:

```<code>17/11/15 03:21:07 INFO ExecutorRunner: Launch command: "/docker-java-home/jre/bin/java"
     "-cp" "//conf/:/jars/*" "-Xmx1024M"
     "-Dspark.cassandra.connection.port=9042"
     "-Dspark.driver.port=7078"
     "org.apache.spark.executor.CoarseGrainedExecutorBackend"
     "--driver-url"
     "spark://CoarseGrainedScheduler@xx:xx:xx:xx:7078"
     "--executor-id" "10" "--hostname"
     "slave01" "--cores" "4"
     "--app-id" "app-20171115032101-0019" "--worker-url" "spark://Worker@slave01:12125"
</code>```

Thanks!!

答: I solved this problem by adding the datastax spark cassandra connector dependency jars to the runtime classpath in spark workers. </p>

Body:
I am working on spark standalone cluster with a master and 3 workers.
My driver is also on the same network, so basically all the workers and master can communicate with the driver and vice-versa.

I am trying to do the job from the driver by getting the sparksession (in Java program). Maven dependencies added for the program are spark-core_2.11(v2.2), spark-sql_2.11(v2.2), spark-streaming_2.11(v2.2),spark-mllib_2.11(v2.2), spark-cassandra-connector_2.11(v2.0.5), spark-cassandra-connector-java_2.11(v1.6.0-M1).

I am getting the following error in the slave.

java.lang.ClassNotFoundException: com.datastax.spark.connector.rdd.partitioner.CassandraPartition
    java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    java.lang.Class.forName0(Native Method)
    java.lang.Class.forName(Class.java:348)
    org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1826)
    java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
    java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
    java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
    java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
    java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
    java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
    java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:309)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    java.lang.Thread.run(Thread.java:748)

Could someone help me in figuring out this issue...

Also, the launch command in slave looks like below:

17/11/15 03:21:07 INFO ExecutorRunner: Launch command: "/docker-java-home/jre/bin/java"
     "-cp" "//conf/:/jars/*" "-Xmx1024M"
     "-Dspark.cassandra.connection.port=9042"
     "-Dspark.driver.port=7078"
     "org.apache.spark.executor.CoarseGrainedExecutorBackend"
     "--driver-url"
     "spark://CoarseGrainedScheduler@xx:xx:xx:xx:7078"
     "--executor-id" "10" "--hostname"
     "slave01" "--cores" "4"
     "--app-id" "app-20171115032101-0019" "--worker-url" "spark://Worker@slave01:12125"

Thanks!!


问:
WPGLOBUS plugin show both languages on my slider

text show in english and in french even if i change the text in both
  language in the custom menu

I've checked on WPGlobus doc and it says :

```<code>// Wrong. Prints 'Hello' regardless of the user's language.
echo 'Hello';
// Correct. Translators can supply the translation of 'Hello'.
echo __( 'Hello', 'my-text-domain' );
</code>```

but it doesnt work

答:
Find the place in the code where the text is printed on the screen.
It should say something like echo $something;.

Surround $something with a filter: echo apply_filters('the_title', $something);

If it helps (it should), tell the slider's author to include that change in their next release.

Body:
text show in english and in french even if i change the text in both
  language in the custom menu

I've checked on WPGlobus doc and it says :

// Wrong. Prints 'Hello' regardless of the user's language.
echo 'Hello';
// Correct. Translators can supply the translation of 'Hello'.
echo __( 'Hello', 'my-text-domain' );

but it doesnt work


问:
Groovy script in soapui is not getting executed from testrunner
I have the below mentioned groovy script in soapui where it

```<code>def date=new Date()
use(groovy.time.TimeCategory){ date = date.plus(10.minutes) }
def dateString = date.format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone('UST'))
return dateString
</code>```

From the request body i am calling this script as shown below,

```<code>{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${StartTime#result}"
}
</code>```

But it runs fine when i run it from console, but when i use TestRunner script is not getting executed.
Kindly let me know how to make a script run from testrunner which is same as running from cmd line.

答:
Never used in the way you mentioned, not sure of the issue. However, you could do something like below overcome the issue.

1.Make below change in the groovy script.

From:

```<code>return dateString
</code>```

To:

```<code>context.testCase.setPropertyValue('START_DATE_TIME', dateString)
</code>```

2.In the Rest request test step, change request

From:

```<code>{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${StartTime#result}"
}
</code>```

To:

```<code>{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${#TestCase#START_DATE_TIME}"
}
</code>```

Body:
I have the below mentioned groovy script in soapui where it

def date=new Date()
use(groovy.time.TimeCategory){ date = date.plus(10.minutes) }
def dateString = date.format("yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone('UST'))
return dateString

From the request body i am calling this script as shown below,

{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${StartTime#result}"
}

But it runs fine when i run it from console, but when i use TestRunner script is not getting executed.
Kindly let me know how to make a script run from testrunner which is same as running from cmd line.

Body:
Never used in the way you mentioned, not sure of the issue. However, you could do something like below overcome the issue.

1.Make below change in the groovy script.

From:

return dateString

To:

context.testCase.setPropertyValue('START_DATE_TIME', dateString)

2.In the Rest request test step, change request

From:

{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${StartTime#result}"
}

To:

{
  "name": "ABCD",
  "tempname": "XYZ",
  "starttime": "${#TestCase#START_DATE_TIME}"
}


Body:
Find svg tag inside div.

if($("#mydiv").find("svg").length) {
   alert("I found SVG");
} else {
    alert("SVG is not found");
}

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

<div id="mydiv">
   <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px'
  viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>
  <style type='text/css'>
     .q-mark{fill:#777777;}
  </style>
  <g>
     <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2
           c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5
           c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4
           l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8
           c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c1.3-1.4,2-2.9,2-4.8c0-0.9-0.2-1.8-0.5-2.6c-0.4-0.8-0.8-1.5-1.5-2.1c-0.6-0.6-1.3-1.1-2.1-1.5
           c-0.8-0.4-1.7-0.5-2.6-0.5c-0.9,0-1.8,0.2-2.6,0.5c-0.8,0.4-1.5,0.8-2.1,1.4c-0.6,0.6-1.1,1.3-1.4,2.1
           C18.5,15.3,18.3,16.2,18.3,17.2z M28.5,40.9c0,1-0.3,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1c-1,0-1.8-0.3-2.5-1c-0.7-0.7-1-1.5-1-2.5
           c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1C28.2,39.1,28.5,40,28.5,40.9z'/>
     </g>
  </g>
   </svg>
</div>


问:
How to append elements dynamically with styles in angular5
I'm trying to append elements dynamically when I click a button.
Actually when I click a button, elements append well.
But the problem is that function and style is not worked.
My code is below.

P.S. I'm using angular5

HTML

```<code><table style="text-align: center; width: 100%">
    <tbody #tContent>
        <!-- I want to append element in here -->
    </tbody>
</table>
    <button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>
</code>```

TS

```<code>    addTbody() {
    ???
}
</code>```

答:
Here it is, In the Angular way:

Component side

```<code>rowData = [];

addTbody() {
    rowData.push({
        name : 'something',
        age : '15',
        ...
    });
}
</code>```

Template side

```<code><table style="text-align: center; width: 100%">
    <tbody>
        <tr *ngFor='let row of rowData'>
            <td> {{ row.name }} </td>
            <td> {{ row.age }} </td>
        </tr>
    </tbody>
</table>

<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>
</code>```

Try to avoid jQuery as much as possible,while learning Angular

Body:
I'm trying to append elements dynamically when I click a button.
Actually when I click a button, elements append well.
But the problem is that function and style is not worked.
My code is below.

P.S. I'm using angular5

HTML

    <button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>

TS

    addTbody() {
    ???
}

Body:
Here it is, In the Angular way:

Component side

rowData = [];

addTbody() {
    rowData.push({
        name : 'something',
        age : '15',
        ...
    });
}

Template side

<table style="text-align: center; width: 100%">
    <tbody>
        <tr *ngFor='let row of rowData'>
            <td> {{ row.name }} </td>
            <td> {{ row.age }} </td>
        </tr>
    </tbody>
</table>

<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>

Try to avoid jQuery as much as possible,while learning Angular


问:
Partial Classes, LINQ, Interfaces and VB.NET
Okay, I have ran in to a problem with VB.NET. So all those defenders of VB.NET please can you help me out? Here is my issue: I am using LINQ to Entities, it also works with LINQ to SQL, I build my edmx file I then create a Partial Publc Class of the same name as one of the entities All fine up to now, so here comes the problem.

I need the Partial class to implement an Interface Implements Interfaces.IAsset But VB.NET want to place "Implements Interfaces.IAsset.ID" at the end of the property, which of course is in the generated code section of the Partial class, which I can not do as the edmx file is auto generated and will change in the future.

Here is the line of code that needs sorting:

Public Property ID1() As Integer Implements Interfaces.IAsset.ID

In C# it is fine and works wonders. So why can't VB.NET implement an interface that is in the code generated class?

答:
There is no way round this. It's a flaw in how VB forces you to handle the implementation of interfaces.

You could create a separate library for your LINQ to Entities that was in C#. I'm not sure if you could just put partial classes in the separate project and keep the basics in a VB one. I've never tried that.

OwnerDisplayName: Garry Shutler


问:
How to change SAS sgplot refline label orientation
I am plotting in SAS using SGPLOT. I added a few reflines on the x-axis to mark certain dates however, the labels of these reflines become vertical as shown  here. With only three reflines, the labels were horizontal as I hoped. However, as I added more reflines, the labels turned vertical.

Is there a way to change the orientation of the label? Or is it just because there is not enough space...

Here is my code for the refline:

```<code>refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial")
</code>```

答:
SAS is automatically rotating them in an attempt to "fit" them (or to indicate they're overlapping visually), more than likely.  Using Reeza's example, this is trivial to reproduce.

```<code>proc sgplot data=sashelp.stocks(where=(stock='IBM'));
series x=date y=open;
refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
refline '02Jul2002'd / axis=x label = "[2]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
run;
</code>```

With just one, it is horizontal, but the second one causes a rotation.

I don't see a way to fix this other than having fewer reference lines so that the labels don't try to overlap.  Neither SGPLOT nor GTL seems to give an option (usually named FITPOLICY) for reference line plots.  You could use a different kind of plot I suppose which might give you more options, or use annotation rather than reference lines (it's possible to duplicate reference lines entirely using Annotation, the refline plot itself is just a convenience to avoid having to use the Annotate facility).

You may want to consider asking this question on http://communities.sas.com and seeing if one of the developers (Sanjay, Dan H, etc.) has a workaround or can suggest something specific other than annotation.  If you do I suggest you include an example like the above so the question is clear.

Body:
I am plotting in SAS using SGPLOT. I added a few reflines on the x-axis to mark certain dates however, the labels of these reflines become vertical as shown  here. With only three reflines, the labels were horizontal as I hoped. However, as I added more reflines, the labels turned vertical.

Is there a way to change the orientation of the label? Or is it just because there is not enough space...

Here is my code for the refline:

refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial")

Body:
SAS is automatically rotating them in an attempt to "fit" them (or to indicate they're overlapping visually), more than likely.  Using Reeza's example, this is trivial to reproduce.

proc sgplot data=sashelp.stocks(where=(stock='IBM'));
series x=date y=open;
refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
refline '02Jul2002'd / axis=x label = "[2]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
run;

With just one, it is horizontal, but the second one causes a rotation.

I don't see a way to fix this other than having fewer reference lines so that the labels don't try to overlap.  Neither SGPLOT nor GTL seems to give an option (usually named FITPOLICY) for reference line plots.  You could use a different kind of plot I suppose which might give you more options, or use annotation rather than reference lines (it's possible to duplicate reference lines entirely using Annotation, the refline plot itself is just a convenience to avoid having to use the Annotate facility).

You may want to consider asking this question on http://communities.sas.com and seeing if one of the developers (Sanjay, Dan H, etc.) has a workaround or can suggest something specific other than annotation.  If you do I suggest you include an example like the above so the question is clear.


问:
Use Reflection to get methods excluding local functions in C# 7.0?
Is there a way to use reflection to get private static methods in a class, without getting any local functions defined within those methods?

For instance, I have a class like so:

```<code>public class Foo {
    private static void FooMethod(){
        void LocalFoo(){
           // do local stuff
        }
        // do foo stuff
    }
}
</code>```

If I use reflection to grab the private static methods like so:

```<code>var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
    .Select(m=>m.Name).ToList();
</code>```

Then I end up with something like:

```<code>FooMethod
<FooMethod>g__LocalFoo5_0
</code>```

With the gnarly compiler-generated name of the local function included.

So far, the best I have been able to come up with is to add a Where clause that would filter out the local functions, like:

```<code>    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("<")
        .Select(m=>m.Name).ToList();
</code>```

or:

```<code>    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("__")
        .Select(m=>m.Name).ToList();
</code>```

答:
What about:

```<code>var methods = typeof(Foo).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
    .Where(x => !x.IsAssembly)
    .Select(x => x.Name)
    .ToList();
</code>```

Result:

```<code>"FooMethod"
</code>```

IsAssembly property summary:

Gets a value indicating whether the potential visibility of this method or constructor
  is described by System.Reflection.MethodAttributes.Assembly; that is, the method
  or constructor is visible at most to other types in the same assembly, and is
  not visible to derived types outside the assembly.

Body:
Is there a way to use reflection to get private static methods in a class, without getting any local functions defined within those methods?

For instance, I have a class like so:

public class Foo {
    private static void FooMethod(){
        void LocalFoo(){
           // do local stuff
        }
        // do foo stuff
    }
}

If I use reflection to grab the private static methods like so:

var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
    .Select(m=>m.Name).ToList();

Then I end up with something like:

FooMethod
<FooMethod>g__LocalFoo5_0

With the gnarly compiler-generated name of the local function included.

So far, the best I have been able to come up with is to add a Where clause that would filter out the local functions, like:

    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("<")
        .Select(m=>m.Name).ToList();

or:

    var methods = typeof(Foo).GetMethods(BindingFlags.Static|BindingFlags.NonPublic)
        .Where(m=>!m.Name.Contains("__")
        .Select(m=>m.Name).ToList();

Body:
What about:

var methods = typeof(Foo).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
    .Where(x => !x.IsAssembly)
    .Select(x => x.Name)
    .ToList();

Result:

"FooMethod"

IsAssembly property summary:

Gets a value indicating whether the potential visibility of this method or constructor
  is described by System.Reflection.MethodAttributes.Assembly; that is, the method
  or constructor is visible at most to other types in the same assembly, and is
  not visible to derived types outside the assembly.


问:
Android push notification using MQTT instead of using FCM
I have an Android application developing in Java and using Firebase Database. This application will send the notification to the users when uploaded something to the database. Therefore, I want to ask whether can the application send push notification using MQTT instead of using Firebase Cloud Messaging(FCM)?</p>

答:
Therefore, I want to ask whether can the application send push notification using MQTT instead of using Firebase Cloud Messaging(FCM)?

You can use whatever you want. There's no requirement to stick Google service for this.


问:
What does .shape[] do in "for i in range(Y.shape[0])"?
I'm trying to break down a program line by line. Y is a matrix of data but I can't find any concrete data on what .shape[0] does exactly.

```<code>for i in range(Y.shape[0]):
    if Y[i] == -1:
</code>```

This program uses numpy, scipy, matplotlib.pyplot, and cvxopt.

答:
In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data
train.shape[0]
```

<p>Number of columns is given by </p>

<pre class="lang-py prettyprint-override"><code>train.shape[1]
</code>```

Body:
I'm trying to break down a program line by line. Y is a matrix of data but I can't find any concrete data on what .shape[0] does exactly.

for i in range(Y.shape[0]):
    if Y[i] == -1:

This program uses numpy, scipy, matplotlib.pyplot, and cvxopt.

Body:
In Python shape() is use in pandas to give number of row/column:

Number of rows is given by:

train = pd.read_csv('fine_name') //load the data
train.shape[0]

Number of columns is given by

train.shape[1]


问:
Image array. Uncaught TypeError: Cannot set property 'src' of null
First time messing with arrays. Trying to cycle through an image array, getting "Uncaught TypeError: Cannot set property 'src' of null" when clicking the next button. I thought it would be something simple like an id not matching up, but I can't spot any issues like that.

var target = document.getElementById('target');

var counter = 0;

var imageArray = [
 "megatron.png",
 "starscream.jpg",
 "soundwave.jpg",
 "shockwave.jpg",
 "devastator.jpg",
 "astrotrain.jpg",
 "blitzwing.jpg",
 "thrust.jpg",
 "rumble.png",
 "ravage.jpg",
 "laserbeak.jpg",
 "reflector.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></!DOCTYPE html>
<html>
<head>
 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">
 <script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
 <div id="socket" class="center">
  <img src="megatron.png" id="target">
 </div>
 <div id="switchplate" class="center">
   <button onclick="next()" id="next">Next</button>
 </div>
</div>
</body>
</html></code>```

答:
Here is the working sample of your code.Please check

var counter = 0;

var imageArray = [
 "https://doodles.google.ca/d4g/images/splashes/featured.png", "https://vignette.wikia.nocookie.net/logopedia/images/a/aa/Google_Assistant.png/revision/latest?cb=20170815132456",
 "http://st1.bgr.in/wp-content/uploads/2017/07/google-search.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></!DOCTYPE html>
<html>
<head>
 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">
<script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
 <div id="socket" class="center">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLxmBuSqBLEVe6FZkt8CK7GxewFiDHOihhgod4ncC8H0hPVV6w" style="width:100px;height:100px;" id="target" >
 </div>
 <div id="switchplate" class="center">
   <button onclick="next()" id="next">Next</button>
 </div>
</div>

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

Body:
First time messing with arrays. Trying to cycle through an image array, getting "Uncaught TypeError: Cannot set property 'src' of null" when clicking the next button. I thought it would be something simple like an id not matching up, but I can't spot any issues like that.

var target = document.getElementById('target');

var counter = 0;

var imageArray = [
 "megatron.png",
 "starscream.jpg",
 "soundwave.jpg",
 "shockwave.jpg",
 "devastator.jpg",
 "astrotrain.jpg",
 "blitzwing.jpg",
 "thrust.jpg",
 "rumble.png",
 "ravage.jpg",
 "laserbeak.jpg",
 "reflector.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}

</!DOCTYPE html>

 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">

Image Array

   <button onclick="next()" id="next">Next</button>

Body:
Here is the working sample of your code.Please check

var counter = 0;

var imageArray = [
 "https://doodles.google.ca/d4g/images/splashes/featured.png", "https://vignette.wikia.nocookie.net/logopedia/images/a/aa/Google_Assistant.png/revision/latest?cb=20170815132456",
 "http://st1.bgr.in/wp-content/uploads/2017/07/google-search.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}

</!DOCTYPE html>
<html>
<head>
 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">
<script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
 <div id="socket" class="center">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLxmBuSqBLEVe6FZkt8CK7GxewFiDHOihhgod4ncC8H0hPVV6w" style="width:100px;height:100px;" id="target" >
 </div>
 <div id="switchplate" class="center">
   <button onclick="next()" id="next">Next</button>
 </div>
</div>

</body>
</html>


答:
jQuery is overkill here. You can use vanilla javascript and getElementsByTagName to return an array of matching elements inside specific elements. Then you can test against the length of the returned array (0 serving as false in the condition).

For example Two tests, one with svg in a div, and one without:

var t1 = document.getElementById('test1');
var t2 = document.getElementById('test2');

// Used in a simple conditional statement
if (t1.getElementsByTagName('svg').length) {
  console.log('test1 has svg');
}
if (t2.getElementsByTagName('svg').length) {
  console.log('test2 has svg');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='test1'></div>
<div id='test2'><svg></svg></div></code>```

Body:
I have a div like the following with a question mark in it...

?

In my code, when someone tries to submit a form, I do a check to see if that field has a question mark in it, like this:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('?') !== -1;

That works fine, but now, instead of a question mark in that div, I have an SVG of a question mark (rather than just a text question mark), like this.

  <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>

    <g>
      <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2 c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5 c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4 l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8 c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c1.3-1.4,2-2.9,2-4.8c0-0.9-0.2-1.8-0.5-2.6c-0.4-0.8-0.8-1.5-1.5-2.1c-0.6-0.6-1.3-1.1-2.1-1.5 c-0.8-0.4-1.7-0.5-2.6-0.5c-0.9,0-1.8,0.2-2.6,0.5c-0.8,0.4-1.5,0.8-2.1,1.4c-0.6,0.6-1.1,1.3-1.4,2.1 C18.5,15.3,18.3,16.2,18.3,17.2z M28.5,40.9c0,1-0.3,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1c-1,0-1.8-0.3-2.5-1c-0.7-0.7-1-1.5-1-2.5 c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1C28.2,39.1,28.5,40,28.5,40.9z'/>
      </g>
    </g>
  </svg>

I still want to run a check on that div, but now I have to check to see if it has an SVG in it, rather than just "?".  How can I use JS to check if a div has an svg element in it?

FYI, I tried the following since I thought it would still look for the text, but to no avail...

const fieldText = $('#mydiv').text();
return fieldText.indexOf('svg') !== -1;

Body:
jQuery is overkill here. You can use vanilla javascript and getElementsByTagName to return an array of matching elements inside specific elements. Then you can test against the length of the returned array (0 serving as false in the condition).

For example Two tests, one with svg in a div, and one without:

var t1 = document.getElementById('test1');
var t2 = document.getElementById('test2');

// Used in a simple conditional statement
if (t1.getElementsByTagName('svg').length) {
  console.log('test1 has svg');
}
if (t2.getElementsByTagName('svg').length) {
  console.log('test2 has svg');
}

<div id='test1'></div>
<div id='test2'><svg></svg></div>


问:
What's the easiest way to implement collision detection in an XNA Game w/ C#?
I'm basically working on a Pong clone, and I wanted to add collision. The way I wanted it to work, is that the paddles would each be divided into 4 sections (not visually), and the ball will react differently depending on which section it hits.

As far as collision goes, I only know rectangle collision, and that's basically the entire paddle as a whole. I do not know how to make it so the paddle has 4 possible points of collision with different reactions.

答:
I'd divide the paddle into rects of different width, e.g.:

```<code>ABBCCCDDDDDDDDDDDDCCCBBA
</code>```

where each letter represents a continuous rect (DDDDDDDDD is one wide rect). Since you know how to intersect rects, you can, say, set for D rect the reaction will be perfect reflection (180-alpha), where as for A,B,C it will be (180 - alpha*factor), where factor depends on the rect, e.g. for A it's 2, for B 1.8, for C 1.5. Well, technically for D the factor is 1 :)

Body:
I'd divide the paddle into rects of different width, e.g.:

ABBCCCDDDDDDDDDDDDCCCBBA

where each letter represents a continuous rect (DDDDDDDDD is one wide rect). Since you know how to intersect rects, you can, say, set for D rect the reaction will be perfect reflection (180-alpha), where as for A,B,C it will be (180 - alpha*factor), where factor depends on the rect, e.g. for A it's 2, for B 1.8, for C 1.5. Well, technically for D the factor is 1 :)