问:
Android App crashing during start up, image resources related
I have an android App which crash on Samsung S4, S5 and Note3 devices.
The app has a LinearLayout in front, and renders 7 rows of a "category" option.

The common error is:

```<code>java.lang.OutOfMemoryError:
           at dalvik.system.VMRuntime.newNonMovableArray (Native Method)
           at android.graphics.BitmapFactory.nativeDecodeAsset (Native Method)
           at android.graphics.BitmapFactory.decodeStream (BitmapFactory.java:856)

      at android.graphics.BitmapFactory.decodeResourceStream (BitmapFactory.java:675)

      at android.graphics.drawable.Drawable.createFromResourceStream (Drawable.java:2228)

      at android.content.res.Resources.loadDrawableForCookie (Resources.java:4211)

      at android.content.res.Resources.loadDrawable (Resources.java:4085)

      at android.content.res.Resources.getDrawable (Resources.java:2005)

      at android.content.res.Resources.getDrawable (Resources.java:1987)

      at android.content.Context.getDrawable (Context.java:464)

      at android.support.v4.c.b.a (Unknown Source)

      at android.support.v4.c.a.a (Unknown Source)

      at android.support.v7.widget.m.a (Unknown Source)

      at android.support.v7.widget.m.a (Unknown Source)

      at android.support.v7.b.a.b.b (Unknown Source)

      at android.support.v7.view.menu.j.getIcon (Unknown Source)

      at android.support.design.internal.NavigationMenuItemView.a (Unknown Source)

      at android.support.design.internal.i$b.a (Unknown Source)

      at android.support.design.internal.i$b.a (Unknown Source)
      at android.support.v7.widget.RecyclerView$a.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$a.b (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.c (Unknown Source)
           at android.support.v7.widget.LinearLayoutManager$c.a (Unknown Source)
           at android.support.v7.widget.LinearLayoutManager.a (Unknown Source)
      at android.support.v7.widget.LinearLayoutManager.a (Unknown Source)

      at android.support.v7.widget.LinearLayoutManager.c (Unknown Source)

      at android.support.v7.widget.RecyclerView.N (Unknown Source)

      at android.support.v7.widget.RecyclerView.p (Unknown Source)

      at android.support.v7.widget.RecyclerView.onLayout (Unknown Source)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.support.v4.widget.DrawerLayout.onLayout (Unknown Source)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1742)

      at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1585)

      at android.widget.LinearLayout.onLayout (LinearLayout.java:1494)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)
     ...
</code>```

I'm using a ListView in the MainActivity, where each row is a single image asset. Like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:layout_margin="0dp"
    android:padding="0dp">

    <LinearLayout
        android:id="@+id/categoryViewContainer"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/category_logo_transport"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@drawable/gradient_bg"
            android:gravity="bottom"
            android:orientation="vertical"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            tools:ignore="RtlHardcoded,RtlSymmetry">

            <TextView
                android:id="@+id/categoryTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:shadowColor="@color/Black"
                android:shadowDx="-5"
                android:shadowDy="-1"
                android:shadowRadius="10"
                android:text="@string/categorytitle"
                android:textColor="@color/White"
                android:textSize="28sp" />

            <TextView
                android:id="@+id/categoryDesc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="2"
                android:text="@string/categorydesc"
                android:textColor="@color/windowBackground"
                android:textSize="11sp"
                tools:ignore="SmallSp" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

I suppose that there could be a problem with the amount of memory used by so many images, but I've compressed each image to 35kB.

答:
Try setting the image in an ImageView, not in a LinearLayout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:layout_margin="0dp"
    android:padding="0dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/category_logo_transport"/>

    <LinearLayout
        android:id="@+id/categoryViewContainer"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@drawable/gradient_bg"
            android:gravity="bottom"
            android:orientation="vertical"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            tools:ignore="RtlHardcoded,RtlSymmetry">

            <TextView
                android:id="@+id/categoryTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:shadowColor="@color/Black"
                android:shadowDx="-5"
                android:shadowDy="-1"
                android:shadowRadius="10"
                android:text="@string/categorytitle"
                android:textColor="@color/White"
                android:textSize="28sp" />

            <TextView
                android:id="@+id/categoryDesc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="2"
                android:text="@string/categorydesc"
                android:textColor="@color/windowBackground"
                android:textSize="11sp"
                tools:ignore="SmallSp" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

Body:
I have an android App which crash on Samsung S4, S5 and Note3 devices.
The app has a LinearLayout in front, and renders 7 rows of a "category" option.

The common error is:

java.lang.OutOfMemoryError:
           at dalvik.system.VMRuntime.newNonMovableArray (Native Method)
           at android.graphics.BitmapFactory.nativeDecodeAsset (Native Method)
           at android.graphics.BitmapFactory.decodeStream (BitmapFactory.java:856)

      at android.graphics.BitmapFactory.decodeResourceStream (BitmapFactory.java:675)

      at android.graphics.drawable.Drawable.createFromResourceStream (Drawable.java:2228)

      at android.content.res.Resources.loadDrawableForCookie (Resources.java:4211)

      at android.content.res.Resources.loadDrawable (Resources.java:4085)

      at android.content.res.Resources.getDrawable (Resources.java:2005)

      at android.content.res.Resources.getDrawable (Resources.java:1987)

      at android.content.Context.getDrawable (Context.java:464)

      at android.support.v4.c.b.a (Unknown Source)

      at android.support.v4.c.a.a (Unknown Source)

      at android.support.v7.widget.m.a (Unknown Source)

      at android.support.v7.widget.m.a (Unknown Source)

      at android.support.v7.b.a.b.b (Unknown Source)

      at android.support.v7.view.menu.j.getIcon (Unknown Source)

      at android.support.design.internal.NavigationMenuItemView.a (Unknown Source)

      at android.support.design.internal.i$b.a (Unknown Source)

      at android.support.design.internal.i$b.a (Unknown Source)
      at android.support.v7.widget.RecyclerView$a.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$a.b (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.a (Unknown Source)
           at android.support.v7.widget.RecyclerView$o.c (Unknown Source)
           at android.support.v7.widget.LinearLayoutManager$c.a (Unknown Source)
           at android.support.v7.widget.LinearLayoutManager.a (Unknown Source)
      at android.support.v7.widget.LinearLayoutManager.a (Unknown Source)

      at android.support.v7.widget.LinearLayoutManager.c (Unknown Source)

      at android.support.v7.widget.RecyclerView.N (Unknown Source)

      at android.support.v7.widget.RecyclerView.p (Unknown Source)

      at android.support.v7.widget.RecyclerView.onLayout (Unknown Source)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.support.v4.widget.DrawerLayout.onLayout (Unknown Source)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1742)

      at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1585)

      at android.widget.LinearLayout.onLayout (LinearLayout.java:1494)

      at android.view.View.layout (View.java:17938)

      at android.view.ViewGroup.layout (ViewGroup.java:5814)

      at android.widget.FrameLayout.layoutChildren (FrameLayout.java:344)

      at android.widget.FrameLayout.onLayout (FrameLayout.java:281)

      at android.view.View.layout (View.java:17938)
     ...

I'm using a ListView in the MainActivity, where each row is a single image asset. Like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:layout_margin="0dp"
    android:padding="0dp">

    <LinearLayout
        android:id="@+id/categoryViewContainer"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/category_logo_transport"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@drawable/gradient_bg"
            android:gravity="bottom"
            android:orientation="vertical"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            tools:ignore="RtlHardcoded,RtlSymmetry">

            <TextView
                android:id="@+id/categoryTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:shadowColor="@color/Black"
                android:shadowDx="-5"
                android:shadowDy="-1"
                android:shadowRadius="10"
                android:text="@string/categorytitle"
                android:textColor="@color/White"
                android:textSize="28sp" />

            <TextView
                android:id="@+id/categoryDesc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="2"
                android:text="@string/categorydesc"
                android:textColor="@color/windowBackground"
                android:textSize="11sp"
                tools:ignore="SmallSp" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

I suppose that there could be a problem with the amount of memory used by so many images, but I've compressed each image to 35kB.

Body:
Try setting the image in an ImageView, not in a LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:layout_margin="0dp"
    android:padding="0dp">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:src="@drawable/category_logo_transport"/>

    <LinearLayout
        android:id="@+id/categoryViewContainer"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical"
        tools:ignore="UselessParent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="@drawable/gradient_bg"
            android:gravity="bottom"
            android:orientation="vertical"
            android:paddingBottom="10dp"
            android:paddingLeft="10dp"
            tools:ignore="RtlHardcoded,RtlSymmetry">

            <TextView
                android:id="@+id/categoryTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:shadowColor="@color/Black"
                android:shadowDx="-5"
                android:shadowDy="-1"
                android:shadowRadius="10"
                android:text="@string/categorytitle"
                android:textColor="@color/White"
                android:textSize="28sp" />

            <TextView
                android:id="@+id/categoryDesc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:maxLines="2"
                android:text="@string/categorydesc"
                android:textColor="@color/windowBackground"
                android:textSize="11sp"
                tools:ignore="SmallSp" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


来源: stackexchange

问:
C# difference between == and Equals()
I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals() returns true.

Here is the code:

```<code>if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))
{
    // Execute code
}

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
    // Execute code
}
</code>```

Any reason as to why this is happening?

答:
Because the static version of the .Equal method was not mentioned so far, I would like to add this here to summarize and to compare the 3 variations.

```<code>MyString.Equals("Somestring"))          //Method 1
MyString == "Somestring"                //Method 2
String.Equals("Somestring", MyString);  //Method 3 (static String.Equals method) - better
</code>```

where MyString is a variable that comes from somewhere else in the code.

Background info and to summerize:

In Java using == to compare strings should not be used. I mention this in case you need to use both languages and also
to let you know that using == can also be replaced with something better in C#.

In C# there's no practical difference for comparing strings using Method 1 or Method 2 as long as both are of type string. However, if one is null, one is of another type (like an integer), or one represents an object that has a different reference, then, as the initial question shows, you may experience that comparing the content for equality may not return what you expect.

Suggested solution:

Because using == is not exactly the same as using .Equals when comparing things, you can use the static String.Equals method instead. This way, if the two sides are not the same type you will still compare the content and  if one is null, you will avoid the exception.

```<code>   bool areEqual = String.Equals("Somestring", MyString);
</code>```

It is a little more to write, but in my opinion, safer to use.

Here is some info copied from Microsoft:

```<code>public static bool Equals (string a, string b);
</code>```

Parameters

a    String

The first string to compare, or null.

b    String

The second string to compare, or null.

Returns  Boolean

true if the value of a is the same as the value of b; otherwise, false. If both a and b are null, the method returns true.

ContentLicense: CC BY-SA 3.0

Title: C# difference between == and Equals()

Body:
I have a condition in a silverlight application that compares 2 strings, for some reason when I use == it returns false while .Equals() returns true.

Here is the code:

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content.Equals("Energy Attack"))
{
    // Execute code
}

if (((ListBoxItem)lstBaseMenu.SelectedItem).Content == "Energy Attack")
{
    // Execute code
}

Any reason as to why this is happening?

Body:
Because the static version of the .Equal method was not mentioned so far, I would like to add this here to summarize and to compare the 3 variations.

MyString.Equals("Somestring"))          //Method 1
MyString == "Somestring"                //Method 2
String.Equals("Somestring", MyString);  //Method 3 (static String.Equals method) - better

where MyString is a variable that comes from somewhere else in the code.

Background info and to summerize:

In Java using == to compare strings should not be used. I mention this in case you need to use both languages and also
to let you know that using == can also be replaced with something better in C#.

In C# there's no practical difference for comparing strings using Method 1 or Method 2 as long as both are of type string. However, if one is null, one is of another type (like an integer), or one represents an object that has a different reference, then, as the initial question shows, you may experience that comparing the content for equality may not return what you expect.

Suggested solution:

Because using == is not exactly the same as using .Equals when comparing things, you can use the static String.Equals method instead. This way, if the two sides are not the same type you will still compare the content and  if one is null, you will avoid the exception.

   bool areEqual = String.Equals("Somestring", MyString);

It is a little more to write, but in my opinion, safer to use.

Here is some info copied from Microsoft:

public static bool Equals (string a, string b);

Parameters

a    String

The first string to compare, or null.

b    String

The second string to compare, or null.

Returns  Boolean

true if the value of a is the same as the value of b; otherwise, false. If both a and b are null, the method returns true.


问:
How can you create a non-empty CharField in Django?
I have a simple model which looks like this:

```<code>class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)
</code>```

I would expect this to throw an integrity error, but it does not:

```<code>group = Group() # name is an empty string here
group.save()
</code>```

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

答:
another option that doesn't require you to manually call clean is to use this:

```<code>name = models.CharField(max_length=100, blank=False, default=None)
</code>```

blank will prevent an empty string to be provided in the admin or using a form or serializer (most cases). However as pointed out in the comments, this unfortunately does not prevent things like model.name = ""  (manually setting blank string)

default=None will set name to None when using something like group = Group(), thus raising an exception when calling save

Body:
I have a simple model which looks like this:

class Group(models.Model):
    name = models.CharField(max_length = 100, blank=False)

I would expect this to throw an integrity error, but it does not:

group = Group() # name is an empty string here
group.save()

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

Body:
another option that doesn't require you to manually call clean is to use this:

name = models.CharField(max_length=100, blank=False, default=None)

blank will prevent an empty string to be provided in the admin or using a form or serializer (most cases). However as pointed out in the comments, this unfortunately does not prevent things like model.name = ""  (manually setting blank string)

default=None will set name to None when using something like group = Group(), thus raising an exception when calling save

ContentLicense: CC BY-SA 4.0


问:
When is StringIO used, as opposed to joining a list of strings?
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

```<code>from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
</code>```

Results:

```<code>16.7872819901
18.7160351276
</code>```

答:
If you measure for speed, you should use cStringIO.

From the docs:

The module cStringIO provides an
  interface similar to that of the
  StringIO module. Heavy use of
  StringIO.StringIO objects can be made
  more efficient by using the function
  StringIO() from this module instead.

But the point of StringIO is to be a file-like object, for when something expects such and you don't want to use actual files.

Edit: I noticed you use from io import StringIO, so you are probably on Python >= 3 or at least 2.6. The separate StringIO and cStringIO are gone in Py3. Not sure what implementation they used to provide the io.StringIO. There is io.BytesIO too.

Body:
Using StringIO as string buffer is slower than using list as buffer.

When is StringIO used?

from io import StringIO

def meth1(string):
    a = []
    for i in range(100):
        a.append(string)
    return ''.join(a)

def meth2(string):
    a = StringIO()
    for i in range(100):
        a.write(string)
    return a.getvalue()

if __name__ == '__main__':
    from timeit import Timer
    string = "This is test string"
    print(Timer("meth1(string)", "from __main__ import meth1, string").timeit())
    print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())

Results:

16.7872819901
18.7160351276

ContentLicense: CC BY-SA 2.5


问:
What happens to WKWebView when scrolled out of bounds
I'm using a paged scroll view displaying different web views as pages. The scroll view has set clipsToBounds = false to allow the display of previous and following pages in the scroll view.

When scrolling through the pages, there is one exact moment, where the WKWebViews content becomes completely invisible. This happens exactly at the moment, where the web view leaves the bounds of the scroll view (see below). On some websites, the visible content out of the bounds is different to the actual content.

These problems only occur when using WKWebView instead of UIWebView (Everything works as intended with UIWebView).

Has someone experienced similar issues with the WKWebView and has a solution for them?

EDIT:
There is a now a sample project on Github, where you can experience the bug and play around with it:
WKWebView test project

答:
To figure it out i think you need to use UICollectionView.
The cell should exist with WKWebView while it will be on screen.

1) You need to place it like Here

And next problem will be to make content pageble.
2) To do it right you need to add UIScrollView over your collection like Here

3) After, make your UIScrollView pageble and write in viewdidload:
collectionView.addGestureRecognizer(scrollView.panGestureRecognizer)

4) After you receive models for showing in UICOllectionView - update your contentSize of UIScrollView like

```<code>scrollView.contentSize = CGSize(width: (models.count*(cellWidth+cellIndent) + sectionIndent * 2), height: cellHeight)
</code>```

5) Implement UIScrollViewDelegate

```<code>extension YourVC: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView {
            collectionView.contentOffset = scrollView.contentOffset
        } else if scrollView == self.collectionView {
            self.scrollView.contentOffset = scrollView.contentOffset
        }
    }
}
</code>```

Thats it. Happy coding =)

Body:
To figure it out i think you need to use UICollectionView.
The cell should exist with WKWebView while it will be on screen.

1) You need to place it like Here

And next problem will be to make content pageble.
2) To do it right you need to add UIScrollView over your collection like Here

3) After, make your UIScrollView pageble and write in viewdidload:
collectionView.addGestureRecognizer(scrollView.panGestureRecognizer)

4) After you receive models for showing in UICOllectionView - update your contentSize of UIScrollView like

scrollView.contentSize = CGSize(width: (models.count*(cellWidth+cellIndent) + sectionIndent * 2), height: cellHeight)

5) Implement UIScrollViewDelegate

extension YourVC: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView {
            collectionView.contentOffset = scrollView.contentOffset
        } else if scrollView == self.collectionView {
            self.scrollView.contentOffset = scrollView.contentOffset
        }
    }
}

Thats it. Happy coding =)


问:
Django fixture with all possible combinations?
I am trying to test a statistics function, which counts what type of objects I have in my database. For this I would like to create at least one instance of each possible combination of model fields. Random test data requires a lot of test objects to make sure all possible combinations are met.

Here is a shortened example from one of my models:

```<code>class Member(models.Model)
    is_active = models.BooleanField()
    name = models.CharField()
    balance = models.IntegerField()
    division = models.ForeignKey(Division, on_delete=models.CASCADE)

Class Division(models.Model)
    name = models.CharField()
</code>```

This is how I'm doing it right now using django_dynamic_fixture:

```<code>from django.test import TestCase
from django_dynamic_fixture import G
from members.models import Member

class StatisticsTestCase(TestCase):
    def setUp(self):
        for is_active in [True, False]:
            for balance in [-100, 0, 100]:
                for division in Division.objects.all()
                    G(Member, is_active=is_active, balance=balance, division=division)
</code>```

But this looks pretty bad and is hard to read. Is there a simpler way with better to read code to create all possible combinations of properties of an object?

I'm open to different test data generators as long as they work nicely with Python 3 and Django.

答:
import itertools

combinations = list(itertools.product(*[[True, False], [-100, 0, 100]]))
for division in Division.objects.all():
    for is_active, balance in combinations:
        G(Member, is_active=is_active, balance=balance, division=division)
```

<hr>

<p>Update:
</p>

```import itertools

combinations = list(itertools.product([True, False], [-100, 0, 100], Division.objects.all()))
for is_active, balance, division in combinations:
    G(Member, is_active=is_active, balance=balance, division=division)
```

Body:
I am trying to test a statistics function, which counts what type of objects I have in my database. For this I would like to create at least one instance of each possible combination of model fields. Random test data requires a lot of test objects to make sure all possible combinations are met.

Here is a shortened example from one of my models:

class Member(models.Model)
    is_active = models.BooleanField()
    name = models.CharField()
    balance = models.IntegerField()
    division = models.ForeignKey(Division, on_delete=models.CASCADE)

Class Division(models.Model)
    name = models.CharField()

This is how I'm doing it right now using django_dynamic_fixture:

from django.test import TestCase
from django_dynamic_fixture import G
from members.models import Member

class StatisticsTestCase(TestCase):
    def setUp(self):
        for is_active in [True, False]:
            for balance in [-100, 0, 100]:
                for division in Division.objects.all()
                    G(Member, is_active=is_active, balance=balance, division=division)

But this looks pretty bad and is hard to read. Is there a simpler way with better to read code to create all possible combinations of properties of an object?

I'm open to different test data generators as long as they work nicely with Python 3 and Django.

Body:
import itertools

combinations = list(itertools.product(*[[True, False], [-100, 0, 100]]))
for division in Division.objects.all():
    for is_active, balance in combinations:
        G(Member, is_active=is_active, balance=balance, division=division)

Update:

import itertools

combinations = list(itertools.product([True, False], [-100, 0, 100], Division.objects.all()))
for is_active, balance, division in combinations:
    G(Member, is_active=is_active, balance=balance, division=division)


问:
Count not adding for each item, adding as a total C# console application
trying to get a count of each item in the array, however its adding a total number.

```<code>  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }
</code>```

E.g. Input: 1,10

Expected output:

```<code>hello: 3
world: 5
helloworld: 1
integer: 11
</code>```

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

答:
You'll need to use if statements inside your foreach loop i.e.

```<code>foreach (var item in arraylist)
{
    if (item.Equals("Hello") )
    {
        counts["Hello"]++;
    }
    else if (item.Equals("World"))
    {
        counts["World"]++;
    }
    else if (item.Equals("HelloWorld"))
    {
        counts["HelloWorld"]++;
    }
    else if (item.Equals("integer"))
    {
        counts["integer"]++;
    }
}
</code>```

Also, just a nitpick, you don't need

```<code>item.Key.ToString()
</code>```

since the key is a string to begin with

```<code>item.Key
</code>```

should suffice.

Body:
trying to get a count of each item in the array, however its adding a total number.

  Dictionary<string, int> counts = new Dictionary<string, int>() {
          { "HelloWorld", 0},
          { "Hello", 0},
          { "World", 0},
          { "integer", 0},
        };

        foreach (var item in arraylist)
        {
            counts["HelloWorld"] += 1;
            counts["Hello"] += 1;
            counts["World"] += 1;
            counts["integer"] += 1;

        }

        Console.WriteLine("");

        foreach (KeyValuePair<string, int> item in counts)
        {
            Console.WriteLine(item.Key.ToString() + ":" + item.Value.ToString());
        }

        Console.ReadLine();
        }

E.g. Input: 1,10

Expected output:

hello: 3
world: 5
helloworld: 1
integer: 11

Run below dotnet fiddle to find issue:

https://dotnetfiddle.net/eKHb5x

Body:
You'll need to use if statements inside your foreach loop i.e.

foreach (var item in arraylist)
{
    if (item.Equals("Hello") )
    {
        counts["Hello"]++;
    }
    else if (item.Equals("World"))
    {
        counts["World"]++;
    }
    else if (item.Equals("HelloWorld"))
    {
        counts["HelloWorld"]++;
    }
    else if (item.Equals("integer"))
    {
        counts["integer"]++;
    }
}

Also, just a nitpick, you don't need

item.Key.ToString()

since the key is a string to begin with

item.Key

should suffice.


问:
Bootstrap Carousel image stack
I'm trying to learn how to use a bootstrap carousel. My problem is that my two images stack on each other. I've been looking thru the code 100 times but can't figure out what's wrong.

```<code> <div id="filmSnurraID" class="carousel slide" data-ride="carousel">

        <ol class="carousel-indicators">
            <li data-target="#filmSnurraID" data-slide-to="0" class="active"></li>
            <li data-target="#filmSnurraID" data-slide-to="1"></li>
        </ol>

        <div class="carousel-inner" role="listbox">
            <div class="item active">
                <img src="./frukt2.jpg" alt="Ett plan">
                <div class="carousel-caption"><h3>Ett plan</h3></div>
            </div>

            <div class="item">
                <img src="./frukt1.jpg" alt="Ett annat plan">
            </div>
        </div>

        <a class="left carousel-control" href="#filmSnurraID" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
            <span class="sr-only">Previous</span>
        </a>

        <a class="right carousel-control" href="#filmSnurraID" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
</code>```

答:
What is the problem here?

I presume, you have not correctly imported Bootstrap CSS in your code.
As you see this ERROR CODEPEN, where I have removed Bootstrap CDN.

Hence please follow the below steps.

All you need is,stack your css/script files in correct order

CSS Imports

Bootstrap CSS CDN/File import

JS Imports

Jquery CDN

Bootstrap JS CDN (As this depends on Jquery, hence Jquery needs to be loaded first)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Ett plan

    Previous

    Next

```

Title: Bootstrap Carousel image stack

Body:
I'm trying to learn how to use a bootstrap carousel. My problem is that my two images stack on each other. I've been looking thru the code 100 times but can't figure out what's wrong.

Ett plan

            Previous

            Next

Body:
What is the problem here?

I presume, you have not correctly imported Bootstrap CSS in your code.
As you see this ERROR CODEPEN, where I have removed Bootstrap CDN.

Hence please follow the below steps.

All you need is,stack your css/script files in correct order

CSS Imports

Bootstrap CSS CDN/File import

JS Imports

Jquery CDN

Bootstrap JS CDN (As this depends on Jquery, hence Jquery needs to be loaded first)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="filmSnurraID" class="carousel slide" data-ride="carousel">

  <ol class="carousel-indicators">
    <li data-target="#filmSnurraID" data-slide-to="0" class="active"></li>
    <li data-target="#filmSnurraID" data-slide-to="1"></li>
  </ol>

  <div class="carousel-inner">
    <div class="item active">
      <img src="http://keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" alt="Ett plan">
      <div class="carousel-caption">
        <h3>Ett plan</h3>
      </div>
    </div>

    <div class="item">
      <img src="https://www.aussiespecialist.com/content/asp/en_sg/sales-resources/image-and-video-galleries/jcr:content/mainParsys/hero/image.adapt.1663.medium.jpg" alt="Ett annat plan">
    </div>
  </div>

  <a class="left carousel-control" href="#filmSnurraID" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
    <span class="sr-only">Previous</span>
  </a>

  <a class="right carousel-control" href="#filmSnurraID" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
    <span class="sr-only">Next</span>
  </a>
</div>


问:
How to put JSON array in request body for Retrofit?
The server API takes a JSON array in the request body. Like this:

```<code>[
  {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
  }
]
</code>```

I know how to put a JSON object as the body, but how can I put a JSON array in a retrofit request?

I already have a POJO:

```<code>public class Sample {
    @SerializedName("key1")
    @Expose
    private String key1;
    @SerializedName("key2")
    @Expose
    private String key2;
    @SerializedName("key3")
    @Expose
    private String key3;
}
</code>```

Here's my API class:

```<code>  @PATCH("//some url")
    Observable<ResponseBody> patchRequest(
            // ... other params
            @Body Sample sampleBody;
    );
</code>```

When I make a request, the body looks like this:

```<code>  {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
  }
</code>```

Except I need it to be inside an array as show in the first JSON.

答:
Use list of that objects</p>

```<code>@POST("url")
Call<Object> doStuff(@Body List<Map<String, String>> body)
</code>```

Body:
The server API takes a JSON array in the request body. Like this:

[
  {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
  }
]

I know how to put a JSON object as the body, but how can I put a JSON array in a retrofit request?

I already have a POJO:

public class Sample {
    @SerializedName("key1")
    @Expose
    private String key1;
    @SerializedName("key2")
    @Expose
    private String key2;
    @SerializedName("key3")
    @Expose
    private String key3;
}

Here's my API class:

  @PATCH("//some url")
    Observable<ResponseBody> patchRequest(
            // ... other params
            @Body Sample sampleBody;
    );

When I make a request, the body looks like this:

  {
    "key1" : "value1",
    "key2" : "value2",
    "key3" : "value3"
  }

Except I need it to be inside an array as show in the first JSON.

Body:
Use list of that objects

@POST("url")
Call<Object> doStuff(@Body List<Map<String, String>> body)


问:
jQuery to add Browser-Name into css-class
I'm using jQuery to detect the Users Browser-Agent and than add the browser-name as a css-class to the body. This works like magic with webkit and mozilla … but with msie it fails — but don't know why. For msie i also have to add not only the «msie», but also one class with the version-number of the used msie (like «msie7» or «msie8»).

Everything works, only the msie-section does not!

my (full) jQuery-Code:

```<code>    <script type="text/javascript">
<!--
(function($){
    $(function(){

        var $copy = $('div.SPA_printcontact').clone();
        var $body = $('body');

        $copy.insertAfter('#printdate');

        if($.browser.msie) {
            $body.addClass('msie')
            var userAgent = userAgent.substring(0,userAgent.indexOf('.'));
            var version = userAgent;
            $body.addClass('msie' + version)
        }
        if($.browser.webkit) {
            $body.addClass('webkit')
        }
        if($.browser.mozilla) {
            $body.addClass('mozilla')
        }

    });
}(jQuery));
-->
</script>
</code>```

答: There is no global object userAgent. It's a member of navigator, so use navigator.userAgent instead or the version provide by jQuery like suggested by Mohib Sheth


问:
Get coefficients of symbolic polynomial in Matlab
I have a Matlab function that returns a polynomial of the form:

```<code>poly = ax^2 + bx*y + cy^2
</code>```

where a, b, and c are constants, and x and y are symbolic (class sym).

I want to get the coefficients of the polynomial in the form [a b c], but I'm running into the following problem. If the function returns poly = y^2, then coeffs(poly) = 1. I don't want this – I want it to return [0 0 1].

How can I create a function that will give me the coefficients of a symbolic polynomial in the form that I want?

答:
There is also an alternative to this problem. For a given degree, this function returns a polynomial of that degree and its coefficients altogether.

```<code> function [polynomial, coefficeint] = makePoly(degree)
 syms x y
 previous  = 0 ;
 for i=0:degree
     current = expand((x+y)^i);
     previous= current +  previous  ;
 end
  [~,poly] = coeffs(previous);
 for j= 1:length(poly)
     coefficeint(j) = sym(strcat('a', int2str(j)) );
 end
 polynomial = fliplr(coefficeint)* poly.' ;
 end
</code>```

Hope this helps.

Body:
I have a Matlab function that returns a polynomial of the form:

poly = ax^2 + bx*y + cy^2

where a, b, and c are constants, and x and y are symbolic (class sym).

I want to get the coefficients of the polynomial in the form [a b c], but I'm running into the following problem. If the function returns poly = y^2, then coeffs(poly) = 1. I don't want this – I want it to return [0 0 1].

How can I create a function that will give me the coefficients of a symbolic polynomial in the form that I want?

Body:
There is also an alternative to this problem. For a given degree, this function returns a polynomial of that degree and its coefficients altogether.

 function [polynomial, coefficeint] = makePoly(degree)
 syms x y
 previous  = 0 ;
 for i=0:degree
     current = expand((x+y)^i);
     previous= current +  previous  ;
 end
  [~,poly] = coeffs(previous);
 for j= 1:length(poly)
     coefficeint(j) = sym(strcat('a', int2str(j)) );
 end
 polynomial = fliplr(coefficeint)* poly.' ;
 end

Hope this helps.


问:
adding a class to a calendar day in jQuery UI (MultipleDates)
I'm using Multiple Dates picker for jQuery UI date picker. Everything was going fine until now. Turns out the developer who made it hasn't touched it in years and pre-highlighting dates no longer works. So here's my plan. I'll place my dates that i need highlighted into an array, then using jQuery to add the necessary class to the calendars. That's where I'm stuck. How do I target this particular anchor when the it looks like this:

```<code><td class=" ui-datepicker-week-end  ui-datepicker-current-day" data-handler="selectDay" data-event="click" data-month="10" data-year="2017">
<a class="ui-state-default" href="#">18</a> <!-- needs class: ui-state-active-->
</td>
</code>```

So how do I target based on data-month, data-year and then the number that's in the anchor? All help is greatly appreciated!!

答:
To get the value inside the anchor tag you can use jQuery selectors to narrow down the search using the month and year.

Then loop through all the days in that month and year and use the find() method on the anchor to get the day. compare the calendar date to the date in your array and if they match, highlight it

Here is an example, but I am not sure about the performance or how it will scale.

$(document).ready(function() {
  var myDates = ["10/18/2017", "10/20/2017"];
  myDates.forEach(function(dateString) {
    var date = new Date(dateString);
    var currMonth = date.getMonth() + 1;
    var currYear = date.getFullYear();
    var currDay = date.getDate();

    var $monthYear = $(`td[data-month='${currMonth}'][data-year='${currYear}']`);
    $monthYear.each(function(i, elem) {
      var calendarDay = $(elem).find("a").text();
      var currDate = `${currMonth}/${calendarDay}/${currYear}`;
      if (dateString === currDate) {
        $(elem).addClass("highlight");
      }
    });
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight {
  background-color: yellow;
}</code>```

      18

      19

      20

```

Body:
I'm using Multiple Dates picker for jQuery UI date picker. Everything was going fine until now. Turns out the developer who made it hasn't touched it in years and pre-highlighting dates no longer works. So here's my plan. I'll place my dates that i need highlighted into an array, then using jQuery to add the necessary class to the calendars. That's where I'm stuck. How do I target this particular anchor when the it looks like this:

18

So how do I target based on data-month, data-year and then the number that's in the anchor? All help is greatly appreciated!!

Body:
To get the value inside the anchor tag you can use jQuery selectors to narrow down the search using the month and year.

Then loop through all the days in that month and year and use the find() method on the anchor to get the day. compare the calendar date to the date in your array and if they match, highlight it

Here is an example, but I am not sure about the performance or how it will scale.

$(document).ready(function() {
  var myDates = ["10/18/2017", "10/20/2017"];
  myDates.forEach(function(dateString) {
    var date = new Date(dateString);
    var currMonth = date.getMonth() + 1;
    var currYear = date.getFullYear();
    var currDay = date.getDate();

    var $monthYear = $(`td[data-month='${currMonth}'][data-year='${currYear}']`);
    $monthYear.each(function(i, elem) {
      var calendarDay = $(elem).find("a").text();
      var currDate = `${currMonth}/${calendarDay}/${currYear}`;
      if (dateString === currDate) {
        $(elem).addClass("highlight");
      }
    });
  })
})

.highlight {
  background-color: yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class=" ui-datepicker-week-end  ui-datepicker-current-day" data-handler="selectDay" data-event="click" data-month="10" data-year="2017">
      <a class="ui-state-default" href="#">18</a>
      <!-- needs class: ui-state-active-->
    </td>

    <td class=" ui-datepicker-week-end  ui-datepicker-current-day" data-handler="selectDay" data-event="click" data-month="10" data-year="2017">
      <a class="ui-state-default" href="#">19</a>
      <!-- needs class: ui-state-active-->
    </td>

    <td class=" ui-datepicker-week-end  ui-datepicker-current-day" data-handler="selectDay" data-event="click" data-month="10" data-year="2017">
      <a class="ui-state-default" href="#">20</a>
      <!-- needs class: ui-state-active-->
    </td>
  </tr>
</table>


答:
I would use a window function to get the number of ussues at the minimum date, then compare that to the baseline number of issues</p>

```<code>select
    case when baseline.NoOfIssues = rev.NoOfIssues then 'equal'
         when baseline.NoOfIssues > rev.NoOfIssues then 'reduced'
         when baseline.NoOfIssues < rev.NoOfIssues then 'increased'
    end as status,
    count(*) as count
from baseline
inner join(
    select
        formid,
        case when date = min(date) over(partition by formid) then NoOfIssues else null end as first_rev_issues
    from revisits
) rev
on baseline.formid = rev.formid
group by
    case when baseline.NoOfIssues = rev.NoOfIssues then 'equal'
         when baseline.NoOfIssues > rev.NoOfIssues then 'reduced'
         when baseline.NoOfIssues < rev.NoOfIssues then 'increased'
    end
</code>```

Title: SQL group by count across two tables

Body:
I have got two tables called baseline and revisits

baseline

formid-------NoOfIssues

1--------------3

2--------------4

3--------------5

revisits

id------formid-------NoOfIssues-----------date--------------fid

1---------2--------------4-------------5/06/2016------------1

2---------3--------------3-------------15/06/2016-----------1

3---------1--------------4-------------20/07/2016-----------1

4---------1--------------3-------------25/07/2016-----------1

5---------2--------------5-------------28/07/2016-----------1

6---------1--------------5-------------01/06/2016-----------1

7---------3--------------8-------------21/02/2016-----------1

8---------3--------------2-------------21/02/2016-----------2

These tables are joined by 'formid'.
I need to compare number of issues in baseline vs revisits(only first) and get a count as reduced, increased or equal

Based upon the above table i am expecting the following, for example across all three baseline entries no equals were found comparing NoOfissues in first revisit against same formid, but 1 equal and 2 increased were found

Addition: if same date and same formid is found than take the lower fid, so in the last two rows of revisits table both formid and date are equal but need to consider the lower formid which is 1

status----------Count

reduced----------0

equal------------1

increased--------2

Body:
I would use a window function to get the number of ussues at the minimum date, then compare that to the baseline number of issues

select
    case when baseline.NoOfIssues = rev.NoOfIssues then 'equal'
         when baseline.NoOfIssues > rev.NoOfIssues then 'reduced'
         when baseline.NoOfIssues < rev.NoOfIssues then 'increased'
    end as status,
    count(*) as count
from baseline
inner join(
    select
        formid,
        case when date = min(date) over(partition by formid) then NoOfIssues else null end as first_rev_issues
    from revisits
) rev
on baseline.formid = rev.formid
group by
    case when baseline.NoOfIssues = rev.NoOfIssues then 'equal'
         when baseline.NoOfIssues > rev.NoOfIssues then 'reduced'
         when baseline.NoOfIssues < rev.NoOfIssues then 'increased'
    end


问:
Mix Cloud Functions w/ Firebase
I have some pub / sub setup on Google Cloud and I have some Cloud Functions running on Firebase.

I'd like to set a trigger on Firebase, so when a user account is created, I publish a message to a topic on Google Cloud.

Is this possible? Am I missing something obvious?

I can trigger a cloud function on account creation and I'm happy at this point showing a console log.

I was considering in my Firebase trigger add something like @google-cloud/pubsub so I can literally setup the message in the body of my firebase trigger, but that feels a little wrong.

Quite clunky and not the way it should be done?

In short, I guess what I'm trying to do is firebase publish to topic on trigger?

答:
I don't think there's anything wrong with what you're suggesting as a solution.  You can use an authentication trigger to find out when a new user account is created, then use the node Cloud Pubsub SDK to turn around and publish a message to your topic.  There's really no more straightforward way to accomplish this that I can think of.

It's pretty common to mix Cloud APIs into your Cloud Functions, regardless if they're based on Cloud or Firebase events.

Title: Mix Cloud Functions w/ Firebase


问:
python appends to all dictionaries
I am using dictoinaries inside of dictionaries. Looping through a pandas dataframe, the value of the action row always matches one of the keys in the dictionary, and based on that some other values from that row are appended to a list in that dictionary. For some reason, however, the values are appended to all lists in the other dictionaries

```<code>    general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = general_form

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)
</code>```

This will make all of the percentages identical in all dictionaries inside sheetstats. Why?

答:
```<code>sheetstats[action] = general_form
</code>```

Is basically putting the same dictionary in every key slot, you can think of this as each key pointing back to general_form

What you can do is make a copy of general_form:

```<code>for action in action_types:
    sheetstats[action] = dict(general_form)
</code>```

The proper way to copy data structure is to use the module copy and it's deepcopy function which will copy deep structures (such as classes):

```<code>import copy
for action in action_types:
    sheetstats[action] = copy.deepcopy(general_form)
</code>```

Title: python appends to all dictionaries

Body:
I am using dictoinaries inside of dictionaries. Looping through a pandas dataframe, the value of the action row always matches one of the keys in the dictionary, and based on that some other values from that row are appended to a list in that dictionary. For some reason, however, the values are appended to all lists in the other dictionaries

    general_form = {
        "Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
    }
    #get all possible action types
    action_types = self.df['Action Type'].tolist()
    action_types = list(set(action_types))

    #give every action type its own dictionary within the main dictionary
    sheetstats = {}
    for action in action_types:
        sheetstats[action] = general_form

    #push the percentage in the list inside the dictionary specified in
    #action
    for index, row in self.df.iterrows():
        percentage = row['Percentage']
        daypercentage = row['DayPercentage']
        action = row['Action Type']
        sheetstats[action]['Percentages'].append(percentage)
        sheetstats[action]["DayPercentages"].append(daypercentage)

This will make all of the percentages identical in all dictionaries inside sheetstats. Why?

Body:
sheetstats[action] = general_form

Is basically putting the same dictionary in every key slot, you can think of this as each key pointing back to general_form

What you can do is make a copy of general_form:

for action in action_types:
    sheetstats[action] = dict(general_form)

The proper way to copy data structure is to use the module copy and it's deepcopy function which will copy deep structures (such as classes):

import copy
for action in action_types:
    sheetstats[action] = copy.deepcopy(general_form)


问:
How would I code "q to quit"? (Python 3.6)
I've been coding a program with a partner for a class assignment and we've been stuck on adding a "q to quit" in it. The assignment is to make a "guess the number" game. Here's our code:

```<code>import random

def get_distance(secret,guess):
    difference = abs(secret - guess)
    return difference
def point_machine(guess1,guess2):
    points_1 = 0
    points_2 = 0
    if guess1 < guess2:
        print ("Player 1 wins")
        points_1 += 1
    elif guess2 < guess1:
        print ("Player 2 wins")
        points_2 += 1
    elif guess1 == guess2:
        print ("It's a tie!")
        points_1 += 1
        points_2 += 1
    return points_1, points_2

x = 0
print ("Welcome to Guess-the-Number!")
print ("Press 'q' to quit at any time.")
name1 = input("What is player one's name?: ")
name2 = input("What is player two's name?: ")
rounds = (input("How many rounds?: "))
points_1 = 0
points_2 = 0
for i in range(int(rounds)):
    x += 1
    secret = random.randint(0,100)
    print ("Round",x)
    print ("~~~~~~~")
    guess1 = int(input(name1+", take a guess: "))
    guess1 = get_distance(secret,guess1)
    guess2 = int(input(name2+", take a guess: "))
    guess2 = get_distance(secret,guess2)
    new1,new2=point_machine(guess1,guess2)
    points_1 += new1
    points_2 += new2
    print ("The number was:",secret)
    print ("Score:",points_1,"to",points_2)

if points_1 > points_2:
    print (name1,"wins the game!")
elif points_2 > points_1:
    print (name2,"wins the game!")
elif points_1 == points_2:
    print ("It's a tie!")
    print (points_1,"to",points_2)
</code>```

The requirement is that when "q" is inputted at any time during the game, it returns you to the "main menu".

Thanks in advance

答:
You will need to test at every input() command. So instead of:

```<code>guess1 = int(input(name1+", take a guess: "))
guess1 = get_distance(secret,guess1)
guess2 = int(input(name2+", take a guess: "))
guess2 = get_distance(secret,guess2)
</code>```

Try this:

```<code>userInput = input(name1+", take a guess: ")
if userInput == "q":
    exit()

guess1 = int(userInput)
guess1 = get_distance(secret,guess1)

userInput = input(name2+", take a guess: ")
if userInput == "q":
    exit()

guess2 = int(userInput)
guess2 = get_distance(secret,guess2)
</code>```

This way, at any time, the user can type "q" and hit enter to quit the game.

Or, alternatively, you can define your own function to use instead of the input() function:

```<code>def userInput(prefix):
    a = input(prefix)
    if a=="q":
        exit()
    else:
        return a
</code>```

And then:

```<code>guess1 = int(userInput(name1+", take a guess: "))
guess1 = get_distance(secret,guess1)
guess2 = int(userInput(name2+", take a guess: "))
guess2 = get_distance(secret,guess2)
</code>```

Body:
I've been coding a program with a partner for a class assignment and we've been stuck on adding a "q to quit" in it. The assignment is to make a "guess the number" game. Here's our code:

import random

def get_distance(secret,guess):
    difference = abs(secret - guess)
    return difference
def point_machine(guess1,guess2):
    points_1 = 0
    points_2 = 0
    if guess1 < guess2:
        print ("Player 1 wins")
        points_1 += 1
    elif guess2 < guess1:
        print ("Player 2 wins")
        points_2 += 1
    elif guess1 == guess2:
        print ("It's a tie!")
        points_1 += 1
        points_2 += 1
    return points_1, points_2

x = 0
print ("Welcome to Guess-the-Number!")
print ("Press 'q' to quit at any time.")
name1 = input("What is player one's name?: ")
name2 = input("What is player two's name?: ")
rounds = (input("How many rounds?: "))
points_1 = 0
points_2 = 0
for i in range(int(rounds)):
    x += 1
    secret = random.randint(0,100)
    print ("Round",x)
    print ("~~~~~~~")
    guess1 = int(input(name1+", take a guess: "))
    guess1 = get_distance(secret,guess1)
    guess2 = int(input(name2+", take a guess: "))
    guess2 = get_distance(secret,guess2)
    new1,new2=point_machine(guess1,guess2)
    points_1 += new1
    points_2 += new2
    print ("The number was:",secret)
    print ("Score:",points_1,"to",points_2)

if points_1 > points_2:
    print (name1,"wins the game!")
elif points_2 > points_1:
    print (name2,"wins the game!")
elif points_1 == points_2:
    print ("It's a tie!")
    print (points_1,"to",points_2)

The requirement is that when "q" is inputted at any time during the game, it returns you to the "main menu".

Thanks in advance

Body:
You will need to test at every input() command. So instead of:

guess1 = int(input(name1+", take a guess: "))
guess1 = get_distance(secret,guess1)
guess2 = int(input(name2+", take a guess: "))
guess2 = get_distance(secret,guess2)

Try this:

userInput = input(name1+", take a guess: ")
if userInput == "q":
    exit()

guess1 = int(userInput)
guess1 = get_distance(secret,guess1)

userInput = input(name2+", take a guess: ")
if userInput == "q":
    exit()

guess2 = int(userInput)
guess2 = get_distance(secret,guess2)

This way, at any time, the user can type "q" and hit enter to quit the game.

Or, alternatively, you can define your own function to use instead of the input() function:

def userInput(prefix):
    a = input(prefix)
    if a=="q":
        exit()
    else:
        return a

And then:

guess1 = int(userInput(name1+", take a guess: "))
guess1 = get_distance(secret,guess1)
guess2 = int(userInput(name2+", take a guess: "))
guess2 = get_distance(secret,guess2)


答:
You could use pythoncom, pyHook

```<code>import pythoncom, pyHook
import random

def get_distance(secret,guess):
    difference = abs(secret - guess)
    return difference

def point_machine(guess1,guess2):
    points_1 = 0
    points_2 = 0
    if guess1 < guess2:
        print ("Player 1 wins")
        points_1 += 1
    elif guess2 < guess1:
        print ("Player 2 wins")
        points_2 += 1
    elif guess1 == guess2:
        print ("It's a tie!")
        points_1 += 1
        points_2 += 1
    return points_1, points_2

def start_game():
    x = 0
    print ("Welcome to Guess-the-Number!")
    print ("Press 'q' to quit at any time.")
    name1 = input("What is player one's name?: ")
    name2 = input("What is player two's name?: ")
    rounds = (input("How many rounds?: "))
    points_1 = 0
    points_2 = 0
    for i in range(int(rounds)):
        x += 1
        secret = random.randint(0,100)
        print ("Round",x)
        print ("~~~~~~~")
        guess1 = int(input(name1+", take a guess: "))
        guess1 = get_distance(secret,guess1)
        guess2 = int(input(name2+", take a guess: "))
        guess2 = get_distance(secret,guess2)
        new1,new2=point_machine(guess1,guess2)
        points_1 += new1
        points_2 += new2
        print ("The number was:",secret)
        print ("Score:",points_1,"to",points_2)

    if points_1 > points_2:
        print (name1,"wins the game!")
    elif points_2 > points_1:
        print (name2,"wins the game!")
    elif points_1 == points_2:
        print ("It's a tie!")
        print (points_1,"to",points_2)

def OnKeyboardEvent(event):

    if event.Key in ['q', 'Q']:
        start_game()

    # return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all input events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

start_game()
</code>```

Title: How would I code "q to quit"? (Python 3.6)

Body:
You could use pythoncom, pyHook

import pythoncom, pyHook
import random

def get_distance(secret,guess):
    difference = abs(secret - guess)
    return difference

def point_machine(guess1,guess2):
    points_1 = 0
    points_2 = 0
    if guess1 < guess2:
        print ("Player 1 wins")
        points_1 += 1
    elif guess2 < guess1:
        print ("Player 2 wins")
        points_2 += 1
    elif guess1 == guess2:
        print ("It's a tie!")
        points_1 += 1
        points_2 += 1
    return points_1, points_2

def start_game():
    x = 0
    print ("Welcome to Guess-the-Number!")
    print ("Press 'q' to quit at any time.")
    name1 = input("What is player one's name?: ")
    name2 = input("What is player two's name?: ")
    rounds = (input("How many rounds?: "))
    points_1 = 0
    points_2 = 0
    for i in range(int(rounds)):
        x += 1
        secret = random.randint(0,100)
        print ("Round",x)
        print ("~~~~~~~")
        guess1 = int(input(name1+", take a guess: "))
        guess1 = get_distance(secret,guess1)
        guess2 = int(input(name2+", take a guess: "))
        guess2 = get_distance(secret,guess2)
        new1,new2=point_machine(guess1,guess2)
        points_1 += new1
        points_2 += new2
        print ("The number was:",secret)
        print ("Score:",points_1,"to",points_2)

    if points_1 > points_2:
        print (name1,"wins the game!")
    elif points_2 > points_1:
        print (name2,"wins the game!")
    elif points_1 == points_2:
        print ("It's a tie!")
        print (points_1,"to",points_2)

def OnKeyboardEvent(event):

    if event.Key in ['q', 'Q']:
        start_game()

    # return True to pass the event to other handlers
    return True

# create a hook manager
hm = pyHook.HookManager()
# watch for all input events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

start_game()


问:
Plot a Linear Regression in ggplot2
I have this dataframe:

```<code>> head(data)
    sx   yd  sl
1   male 35  36350
2   male 22  35350
3   male 23  28200
4 female 27  26775
5   male 30  33696
6   male 21  28516
</code>```

Where "sx" is sex, "yd" is years since acquired degree and "sl" is salary. Using ggplot or plot, I can plot the scatter easily.

```<code>palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)

library(ggplot2)
ggplot(data, aes(x=yd,y=sl)) +
    geom_point(shape=21, aes(col=sx, bg=sx)) +
    xlab("Years Since Earned Highest Degree") +
    ylab("Salary (dollars)") +
    ggtitle("Salary Increases with Experience") +
    scale_color_discrete(guide=FALSE) +
    labs(fill="sex")
</code>```

However, I have also made a linear model based on the data:

```<code>mod<-lm(sl~sx*poly(yd,2),data)
</code>```

And I am unable to figure out how to plot the data to the graphs. Specifically, I want two lines corresponding to male and female data superimposed on the scatterplot AND to be color-coded. I would assume that R has some way to do this so that I don't have to actually write out the model. Either base plot or ggplot answers are good. Thanks.

Edit:

Running this the above ggplot with geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)):

```<code>ggplot(data, aes(x=yd,y=sl)) + geom_point(shape=21, aes(col=sx, bg=sx)) + geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)) + xlab("Years Since Earned Highest Degree") + ylab("Salary (dollars)") + ggtitle("Salary Increases with Experience") + scale_color_discrete(guide=FALSE)+ labs(fill="sex")
</code>```

Returns this error:

```<code>Error in model.frame.default(formula = formula, data = data, weights = weight,  :
  variable lengths differ (found for '(weights)')
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
</code>```

答:
I was unable to find a ggplot way to do it, so here is the base plot way to do it:

```<code>palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)
lines(seq(0,25,0.1), predict.lm(quad, data.frame(yd = seq(0,25,0.1), sx = "female", stringsAsFactors = TRUE)),col="pink", lwd = 5)
lines(seq(0,25,0.1), predict.lm(quad, data.frame(yd = seq(0,25,0.1), sx = "male", stringsAsFactors = TRUE)),col="blue", lwd = 5)
</code>```

The two calls to lines are the solution. If anyone has the ggplot way to do it, I'd appreciate it a lot, as ggplot looks so much better.

OwnerDisplayName: Jeff

Title: Plot a Linear Regression in ggplot2

Body:
I have this dataframe:

> head(data)
    sx   yd  sl
1   male 35  36350
2   male 22  35350
3   male 23  28200
4 female 27  26775
5   male 30  33696
6   male 21  28516

Where "sx" is sex, "yd" is years since acquired degree and "sl" is salary. Using ggplot or plot, I can plot the scatter easily.

palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)

library(ggplot2)
ggplot(data, aes(x=yd,y=sl)) +
    geom_point(shape=21, aes(col=sx, bg=sx)) +
    xlab("Years Since Earned Highest Degree") +
    ylab("Salary (dollars)") +
    ggtitle("Salary Increases with Experience") +
    scale_color_discrete(guide=FALSE) +
    labs(fill="sex")

However, I have also made a linear model based on the data:

mod<-lm(sl~sx*poly(yd,2),data)

And I am unable to figure out how to plot the data to the graphs. Specifically, I want two lines corresponding to male and female data superimposed on the scatterplot AND to be color-coded. I would assume that R has some way to do this so that I don't have to actually write out the model. Either base plot or ggplot answers are good. Thanks.

Edit:

Running this the above ggplot with geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)):

ggplot(data, aes(x=yd,y=sl)) + geom_point(shape=21, aes(col=sx, bg=sx)) + geom_smooth(aes(col=sx), se = FALSE, method = "lm", formula = sl ~ sx * poly(yd, 2)) + xlab("Years Since Earned Highest Degree") + ylab("Salary (dollars)") + ggtitle("Salary Increases with Experience") + scale_color_discrete(guide=FALSE)+ labs(fill="sex")

Returns this error:

Error in model.frame.default(formula = formula, data = data, weights = weight,  :
  variable lengths differ (found for '(weights)')
Error in if (nrow(layer_data) == 0) return() : argument is of length zero

Body:
I was unable to find a ggplot way to do it, so here is the base plot way to do it:

palette(c("pink", "blue"))
plot(data$yr, data$sl, col = factor(data$sx), xlab = "Years Since Earned Highest Degree", ylab = "Salary (dollars)", main = "Salary Increases with Experience", pch = 19)
legend("topleft", legend = unique(data$sx), col = c("blue", "pink"), pch=19)
lines(seq(0,25,0.1), predict.lm(quad, data.frame(yd = seq(0,25,0.1), sx = "female", stringsAsFactors = TRUE)),col="pink", lwd = 5)
lines(seq(0,25,0.1), predict.lm(quad, data.frame(yd = seq(0,25,0.1), sx = "male", stringsAsFactors = TRUE)),col="blue", lwd = 5)

The two calls to lines are the solution. If anyone has the ggplot way to do it, I'd appreciate it a lot, as ggplot looks so much better.


问:
The most efficient way to determine the presence of repeated values in a 2D array, arranged like a table (with some starting ideas)
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

```<code> 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0
</code>```

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

答:
Start brute force with the first cell (index), check against all neighboring cells. Go to the next cell, check against neighboring cells, then the next, and so on. </p>

<p>When you get that working, you'll probably get some ideas for improving it. Eventually you will understand the process and can advance to better algorithms. </p>

Body:
I am switching the tags for this question as I don't believe it is a C# .NET specific question, and more so a mathematical/algorithms one. Say I have an 2D array of ints, like below:

 0 | 1 | 2
---+---+---
 0 | 1 | 0
---+---+---
 1 | 0 | 0

These could be stored in a different data structure if this would allow a faster solution to the problem. The problem being how to detect (and find the locations of) equal integer values stored adjacently (allowing for diagonals) (and not accounting for "wrapping around" adjacency, for example a corner piece should only need to be compared with 3 other values... that is unless there is a better solution to storing the data).

My first (and I am sure naive) approach would be a 2D array (implemented as a jagged array or just indexed like this) in which I store the integer values. I have no need for any sort property besides just whether or not values are equal (i.e. no need for >, <, etc). I could then do an N^8 (not sure if this is the correct time analysis for this situation but it was my best try)traversal of all N locations in the array, and 8 checks maximum (if not on the edge) per iteration. I think there may be a better way to do this, however. Especially as this approach is very time consuming.

One idea I had is to modify the data structure so that every item has a flag (included in each structure in the array [so not just an array of ints]) of whether it is the same as any adjacent value. This would slow down my insertion and building processes, but may (??) speed up the process of finding pairs in the table. Thanks for any help.

Body:
Start brute force with the first cell (index), check against all neighboring cells. Go to the next cell, check against neighboring cells, then the next, and so on.

When you get that working, you'll probably get some ideas for improving it. Eventually you will understand the process and can advance to better algorithms.


问:
How to only field names(not field values) of a particular document using node.js
I'm a beginner in both MongoDB and node.js. Actually, I'm trying to get the names of a particular document but I wonder how to do that.
Let me elaborate in detail :
if "a" is a collection which contains document named "student" and "student" contains fields like

```<code>{
    "_id: "student",
    "name": "alex",
    "roll": "3",
    "age":"13"
}
</code>```

then how to get the field names in this ["name","roll","age"] format
By trying this:

```<code>db.collection("user").find({ "_id": "student" }).toArray(function(err, result) {
    console.log(result)
})
</code>```

is giving all the fields with their values.

答:
This will work:</p>

```<code>db.collection("user",function(err,user){
   var array = [];
   user.findOne(function(err,doc){
     for (key in doc) array.push(key);
   });
   console.log(array);
});
</code>```

Body:
I'm a beginner in both MongoDB and node.js. Actually, I'm trying to get the names of a particular document but I wonder how to do that.
Let me elaborate in detail :
if "a" is a collection which contains document named "student" and "student" contains fields like

{
    "_id: "student",
    "name": "alex",
    "roll": "3",
    "age":"13"
}

then how to get the field names in this ["name","roll","age"] format
By trying this:

db.collection("user").find({ "_id": "student" }).toArray(function(err, result) {
    console.log(result)
})

is giving all the fields with their values.

Body:
This will work:

db.collection("user",function(err,user){
   var array = [];
   user.findOne(function(err,doc){
     for (key in doc) array.push(key);
   });
   console.log(array);
});


问:
From file to ldif script, attributes separated by comma
I have a file like this:

h3fah055,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah058,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah065,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah066,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah082,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal029,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal030,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG

I would like to generate an ldif from this file, so for each rows I need to generate:

```<code> dn: cn=h3fah055,ou=hosts,dc=example,dc=com
 objectClass: host
 objectClass: ipHost
 objectClass: top
 ipHostNumber: 1.1.1.1
 cn: h3fah055
 Allowednetgroup: NG_SYS_UX
 Allowednetgroup: NG_SYS_FO
 Allowednetgroup: NG_SYS_STG
 Allowednetgroup: NG_APP_DWH
</code>```

How can I read each rows in this file and save, if existing, each netgroup in a variable in order to print in a file my desired output?

I tryed with

```<code>while read p; do
  echo $p |  awk -F , '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com"}'
done <hosts_list.txt
</code>```

But I'm not sure how to add as many Allowednetgroup as defined in the file.

答:
this is the template you can follow

```<code>awk -F, '{print "cn:",$1;
          for(i=2;i<=NF;i++) print "Allowednetgroup:",$i}'
</code>```

which will handle

```<code>cn: h3fah055
Allowednetgroup: NG_SYS_UX
Allowednetgroup: NG_SYS_FO
Allowednetgroup: NG_SYS_STG
Allowednetgroup: NG_APP_DWH
</code>```

you can add the top yourself.

Body:
I have a file like this:

h3fah055,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah058,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah065,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah066,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah082,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal029,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal030,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG

I would like to generate an ldif from this file, so for each rows I need to generate:

 dn: cn=h3fah055,ou=hosts,dc=example,dc=com
 objectClass: host
 objectClass: ipHost
 objectClass: top
 ipHostNumber: 1.1.1.1
 cn: h3fah055
 Allowednetgroup: NG_SYS_UX
 Allowednetgroup: NG_SYS_FO
 Allowednetgroup: NG_SYS_STG
 Allowednetgroup: NG_APP_DWH

How can I read each rows in this file and save, if existing, each netgroup in a variable in order to print in a file my desired output?

I tryed with

while read p; do
  echo $p |  awk -F , '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com"}'
done <hosts_list.txt

But I'm not sure how to add as many Allowednetgroup as defined in the file.

Body:
this is the template you can follow

awk -F, '{print "cn:",$1;
          for(i=2;i<=NF;i++) print "Allowednetgroup:",$i}'

which will handle

cn: h3fah055
Allowednetgroup: NG_SYS_UX
Allowednetgroup: NG_SYS_FO
Allowednetgroup: NG_SYS_STG
Allowednetgroup: NG_APP_DWH

you can add the top yourself.


问:
Refreshing page makes jQuery button click trigger twice
I have a star button that a user can click to star something on my site. When clicked it submits an ajax request and my rails controller handles the rest. The ajax works fine and I'm using some coffeescript and jQuery to change the star icon when it is clicked. It works fine, but if I refresh the page the click triggers twice. I have tried .preventDefault() but it does nothing. What works in stopping it from triggering twice is .stopImmediatePropagation(). This, however, changes my button from having a method of POST to GET and I get a routing error saying that there is no such route as GET/...

Here's my button:

```<code><%= link_to star_question_path(@question), method: :post, remote: true do %>
  <i class="fa fa-star fa-2x fa-yellow" id="star-question-icon"></i>
<% end %>
</code>```

Coffeescript and jQuery:

```<code>$('#star-question-icon').on 'click', (e) ->
  if $(this).hasClass "fa-star"
    $(this).removeClass('fa-star')
    $(this).addClass('fa-star-o')
  else if $(this).hasClass "fa-star-o"
    $(this).removeClass('fa-star-o')
    $(this).addClass('fa-star')
  return
</code>```

This works but changes the method to GET if the page is refreshed:

```<code>$('#star-question-icon').on 'click', (e) ->
  e.stopImmediatePropagation()
  if $(this).hasClass "fa-star"
    $(this).removeClass('fa-star')
    $(this).addClass('fa-star-o')
  else if $(this).hasClass "fa-star-o"
    $(this).removeClass('fa-star-o')
    $(this).addClass('fa-star')
  return
</code>```

My corresponding route:

```<code>post 'question/:id/star', to: 'questions#star', as: 'star_question'
</code>```

答:
Next code is blocking  a doubleclick.</p>

```<code>   $document.on('click','#star-question-icon',function(ev){
        if(ev.detail>1){
          // this code execute after twice click or more
          return false;
        }
      });
</code>```

Body:
I have a star button that a user can click to star something on my site. When clicked it submits an ajax request and my rails controller handles the rest. The ajax works fine and I'm using some coffeescript and jQuery to change the star icon when it is clicked. It works fine, but if I refresh the page the click triggers twice. I have tried .preventDefault() but it does nothing. What works in stopping it from triggering twice is .stopImmediatePropagation(). This, however, changes my button from having a method of POST to GET and I get a routing error saying that there is no such route as GET/...

Here's my button:

<%= link_to star_question_path(@question), method: :post, remote: true do %>

<% end %>

Coffeescript and jQuery:

$('#star-question-icon').on 'click', (e) ->
  if $(this).hasClass "fa-star"
    $(this).removeClass('fa-star')
    $(this).addClass('fa-star-o')
  else if $(this).hasClass "fa-star-o"
    $(this).removeClass('fa-star-o')
    $(this).addClass('fa-star')
  return

This works but changes the method to GET if the page is refreshed:

$('#star-question-icon').on 'click', (e) ->
  e.stopImmediatePropagation()
  if $(this).hasClass "fa-star"
    $(this).removeClass('fa-star')
    $(this).addClass('fa-star-o')
  else if $(this).hasClass "fa-star-o"
    $(this).removeClass('fa-star-o')
    $(this).addClass('fa-star')
  return

My corresponding route:

post 'question/:id/star', to: 'questions#star', as: 'star_question'

Body:
Next code is blocking  a doubleclick.

   $document.on('click','#star-question-icon',function(ev){
        if(ev.detail>1){
          // this code execute after twice click or more
          return false;
        }
      });


问:
SQL Server : cross apply makes columns to be nullable
I'm making a view but I'm a bit confused on why my fields are getting converted to nullable. I'm using SQL Server 2016.

```<code>CREATE OR ALTER VIEW [dbo].[vwEmployeePTORequest]
AS
    SELECT
        Employees.EmployeeID, Employees.DivisionID,
        PTORequests.PTORequestId, PTORequests.IsPaidOut,
        PTORequests.PayoutPayEntryEarningId,
        --Why do I have to use ISNULL here?
        ISNULL(SummaryDetails.TotalHours, 0) AS TotalHours,
        SummaryDetails.RequestStartDate, SummaryDetails.RequestEndDate,
        SummaryDetails.DivisionPTOAccrualId
    FROM
        dbo.Employees
    INNER JOIN
        dbo.GlobalIds ON Employees.GlobalId = GlobalIds.Id
    INNER JOIN
        dbo.Activities ON Activities.OriginatorGlobalId = GlobalIds.Id
    INNER JOIN
        dbo.PTORequests ON Activities.ActivityId = PTORequests.ActivityId
    CROSS APPLY
        dbo.GetEmployeePTORequestDetailSummary(PTORequests.PTORequestId) AS SummaryDetails;
</code>```

And this is the function being called in CROSS APPLY:

```<code>CREATE OR ALTER FUNCTION [dbo].[GetEmployeePTORequestDetailSummary]
    (@PTORequestId INT)
RETURNS TABLE
AS
    RETURN
        (SELECT TOP 1
             SUM(Hours) AS TotalHours,
             MIN(RequestDate) AS RequestStartDate,
             MAX(RequestDate) AS RequestEndDate,
             DivisionPTOAccrualId AS DivisionPTOAccrualId
         FROM
             dbo.PTORequestDetails
         WHERE
             PTORequestId = @PTORequestId
         GROUP BY
             PTORequestId, DivisionPTOAccrualId);
</code>```

And this is the relevant portion of the table definition:

```<code>CREATE TABLE [dbo].[PTORequestDetails]
(
    [PTORequestDetailId] [int] IDENTITY(1,1) NOT NULL,
    [RequestDate] [date] NOT NULL,
    [StartTime] [datetime] NULL,
    [Hours] [decimal](19, 2) NOT NULL,
)
</code>```

I'm a bit confused on why this is happening. As you can see my columns are not NULLABLE, the aggregate function return non-nullable types, and I'm using CROSS APPLY which works per-row similar to inner join.  Since it's a one to one it shouldn't create a nullable.

Can anyone explain why my columns are coming in as nullable, and how can I fix this in the function so that all other procedures using it do not have to specify the ISNULL() conditional for each selected column?

答:
It’s not the cross apply. It is the aggregate functions. SUM, MIN, MAX are all assumed to be nullable because if you use them on an empty table with no GROUP BY they will return NULL.

Moreover SUM can return NULL instead of error on integer overflow if you use some deprecated session options.

So you would need to wrap the aggregates in an ISNULL to have the columns treated as not nullable.

Body:
I'm making a view but I'm a bit confused on why my fields are getting converted to nullable. I'm using SQL Server 2016.

CREATE OR ALTER VIEW [dbo].[vwEmployeePTORequest]
AS
    SELECT
        Employees.EmployeeID, Employees.DivisionID,
        PTORequests.PTORequestId, PTORequests.IsPaidOut,
        PTORequests.PayoutPayEntryEarningId,
        --Why do I have to use ISNULL here?
        ISNULL(SummaryDetails.TotalHours, 0) AS TotalHours,
        SummaryDetails.RequestStartDate, SummaryDetails.RequestEndDate,
        SummaryDetails.DivisionPTOAccrualId
    FROM
        dbo.Employees
    INNER JOIN
        dbo.GlobalIds ON Employees.GlobalId = GlobalIds.Id
    INNER JOIN
        dbo.Activities ON Activities.OriginatorGlobalId = GlobalIds.Id
    INNER JOIN
        dbo.PTORequests ON Activities.ActivityId = PTORequests.ActivityId
    CROSS APPLY
        dbo.GetEmployeePTORequestDetailSummary(PTORequests.PTORequestId) AS SummaryDetails;

And this is the function being called in CROSS APPLY:

CREATE OR ALTER FUNCTION [dbo].[GetEmployeePTORequestDetailSummary]
    (@PTORequestId INT)
RETURNS TABLE
AS
    RETURN
        (SELECT TOP 1
             SUM(Hours) AS TotalHours,
             MIN(RequestDate) AS RequestStartDate,
             MAX(RequestDate) AS RequestEndDate,
             DivisionPTOAccrualId AS DivisionPTOAccrualId
         FROM
             dbo.PTORequestDetails
         WHERE
             PTORequestId = @PTORequestId
         GROUP BY
             PTORequestId, DivisionPTOAccrualId);

And this is the relevant portion of the table definition:

CREATE TABLE [dbo].[PTORequestDetails]
(
    [PTORequestDetailId] [int] IDENTITY(1,1) NOT NULL,
    [RequestDate] [date] NOT NULL,
    [StartTime] [datetime] NULL,
    [Hours] [decimal](19, 2) NOT NULL,
)

I'm a bit confused on why this is happening. As you can see my columns are not NULLABLE, the aggregate function return non-nullable types, and I'm using CROSS APPLY which works per-row similar to inner join.  Since it's a one to one it shouldn't create a nullable.

Can anyone explain why my columns are coming in as nullable, and how can I fix this in the function so that all other procedures using it do not have to specify the ISNULL() conditional for each selected column?


问:
Button with an icon CSS
I created a simple login (via Gmail) button with green color.
Look at this, please

```<code> <!DOCTYPE html>
<html>
<head>
<style>
.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
.button:icon {
    background: url(gmail-icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}
</style>
</head>
<body>

<button class="button"><span class="icon"></span>Button</button>

</body>
</code>```

But I can't see my icon on the button.
Please tell me why?

答:
you have forget the quots ""
and change :icon to .icon

Try this one:

```<code>.button .icon {
    background: url("gmail-icon.png") no-repeat;
    float: left;
    width: 20px;
    height: 20px;
    margin-right: 10px;
}
</code>```

Title: Button with an icon CSS

Body:
I created a simple login (via Gmail) button with green color.
Look at this, please

 <!DOCTYPE html>

<button class="button">Button</button>

But I can't see my icon on the button.
Please tell me why?

Body:
you have forget the quots ""
and change :icon to .icon

Try this one:

.button .icon {
    background: url("gmail-icon.png") no-repeat;
    float: left;
    width: 20px;
    height: 20px;
    margin-right: 10px;
}


问:
Copy files in folders with different names
I need to copy files from the folder called shape, but this folder is inside another folder that has different names.

For example I have 1000 folders all with different names, but within each of them I have a folder called shape, and I want to make a script in python that automatically copies all the files of that shape folder that is inside that folder that changes name and paste it into another directory that will always be the same.

txs in advance.

答:
EDIT: A much simpler way, inspired by a comment from @fernand0, is to run:

```<code>import subprocess

root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"

cmd = "mv */shape/* {}".format(destination)
p = subprocess.call(cmd.split(),cwd=root_dir,shell=True)
</code>```

I have not been able to test this, but it should do what you need it to.

```<code>import os
import shutil

# Set up directory you want to copy from and to
root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"

# Get the list of all directories in root_dir
for root, dirs, files in os.walk(root_dir, topdown=True):
   dir_list = dirs
   break

# Iterate over this list and see if 'shape/' exists
for dir in dir_list:

   sub_dir = os.listdir(dir) # List of all contents in dir

   # Iterate over contents and see if 'shape/' is present
   for d in sub_dir:

       # If so, copy all files and directories from it
       if d.lower() == 'shape':
          shape_dir = os.path.join(root_dir,dir,d)
          for f in os.list(shape_dir):
              shutil.copyfile(os.path.join(shape_dir,f),os.path.join(destination, f))
</code>```

Body:
EDIT: A much simpler way, inspired by a comment from @fernand0, is to run:

import subprocess

root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"

cmd = "mv */shape/* {}".format(destination)
p = subprocess.call(cmd.split(),cwd=root_dir,shell=True)

I have not been able to test this, but it should do what you need it to.

import os
import shutil

# Set up directory you want to copy from and to
root_dir = "/Users/krekto/lots_of_folders/"
destination = "/Users/krekto/my_destination/"

# Get the list of all directories in root_dir
for root, dirs, files in os.walk(root_dir, topdown=True):
   dir_list = dirs
   break

# Iterate over this list and see if 'shape/' exists
for dir in dir_list:

   sub_dir = os.listdir(dir) # List of all contents in dir

   # Iterate over contents and see if 'shape/' is present
   for d in sub_dir:

       # If so, copy all files and directories from it
       if d.lower() == 'shape':
          shape_dir = os.path.join(root_dir,dir,d)
          for f in os.list(shape_dir):
              shutil.copyfile(os.path.join(shape_dir,f),os.path.join(destination, f))