问:
android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>
I am receiving many errors of kind displayed in the subj. These errors seems to be occasional and I cannot reproduce them. From stack I can learn that such error may occurs for my different layout resources. The line of XML is also varying.

Can anybody explain why this error occurs? And what I can do to fix this problem?

Stack

```<code>=============================================================

com.fsp.android.f generated the following exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsp.android.f/com.life360.android.ui.tour.TourActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

--------- Stack trace ---------
1. android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)
2. android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2674)
3. android.app.ActivityThread.access$2200(ActivityThread.java:131)
4. android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975)
5. android.os.Handler.dispatchMessage(Handler.java:99)
6. android.os.Looper.loop(Looper.java:123)
7. android.app.ActivityThread.main(ActivityThread.java:4702)
8. java.lang.reflect.Method.invokeNative(Native Method)
9. java.lang.reflect.Method.invoke(Method.java:521)
10. com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11. com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12. dalvik.system.NativeStart.main(Native Method)
-------------------------------

----------- Cause -----------
android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

1. android.view.LayoutInflater.createView(LayoutInflater.java:513)
2. com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
3. android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
4. android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
5. android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
6. android.view.LayoutInflater.inflate(LayoutInflater.java:382)
7. android.view.LayoutInflater.inflate(LayoutInflater.java:320)
8. android.view.LayoutInflater.inflate(LayoutInflater.java:276)
9. com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:208)
10. android.app.Activity.setContentView(Activity.java:1629)
11. com.solvek.sample.ui.BaseActivity.onCreate(BaseActivity.java:23)
12. com.solvek.sample.ui.tour.TourActivity.onCreate(TourActivity.java:161)
13. android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
14. android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2587)
15. android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2674)
16. android.app.ActivityThread.access$2200(ActivityThread.java:131)
17. android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975)
18. android.os.Handler.dispatchMessage(Handler.java:99)
19. android.os.Looper.loop(Looper.java:123)
20. android.app.ActivityThread.main(ActivityThread.java:4702)
21. java.lang.reflect.Method.invokeNative(Native Method)
22. java.lang.reflect.Method.invoke(Method.java:521)
23. com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
24. com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
25. dalvik.system.NativeStart.main(Native Method)
-----------------------------

-------- Environment --------
Time =2010-12-20 08:27:35 AM
Device =tmobile/htc_espresso/espresso/espresso:2.1-update1/ERE27/216830:user/release-keys
Make =HTC
Model =T-Mobile myTouch 3G Slide
Product =htc_espresso
App =com.fsp.android.f, version 2.0.9 (build 1232)
</code>```

Here is a result of XML, however such error occurs in other xmls

```<code><?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <ViewFlipper android:layout_gravity="fill" android:id="@+id/flipper" android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_1"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_2"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_3"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_4"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_5"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_6"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_7"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_8"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_9"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_10"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_11"/>
    </ViewFlipper>

    <LinearLayout android:id="@+id/exit_bar" android:layout_gravity="top" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue_bar" android:visibility="invisible">
        <Button android:background="@drawable/orange_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:textStyle="bold" android:textColor="#000000" android:shadowColor="#ffffff" android:shadowRadius="1.6" android:shadowDx="1.5" android:shadowDy="1.3" android:id="@+id/exit_tour_btn" android:text="Exit" android:layout_marginLeft="20dip"/>
        <TextView android:layout_height="wrap_content" android:textColor="#ffffff" android:layout_gravity="center" android:layout_width="110dip" android:layout_marginLeft="20dip" android:textSize="16dip" android:textStyle="bold" android:text="Life360 Tour"/>

    </LinearLayout>

    <Button style="@style/BlueBtn" android:text="Continue" android:layout_marginTop="40dip" android:id="@+id/continue_btn" android:visibility="gone" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" />

    <FrameLayout android:id="@+id/bottom_bar" android:layout_gravity="bottom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue_bar" android:visibility="invisible">
        <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/left" android:layout_gravity="left|center" android:background="@drawable/tour_left" android:layout_marginLeft="10dip"/>
        <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/right" android:layout_gravity="right|center" android:background="@drawable/tour_right" android:layout_marginRight="10dip"/>
    </FrameLayout>
</merge>
</code>```

答:
In my case,this error happen when  I use the Floating action button and set android:backgroundTint="#000". Then just don't set backgroundTint and problem solved.
Hope it's helpful for you.

Body:
I am receiving many errors of kind displayed in the subj. These errors seems to be occasional and I cannot reproduce them. From stack I can learn that such error may occurs for my different layout resources. The line of XML is also varying.

Can anybody explain why this error occurs? And what I can do to fix this problem?

Stack

=============================================================

com.fsp.android.f generated the following exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fsp.android.f/com.life360.android.ui.tour.TourActivity}: android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

--------- Stack trace ---------
1. android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2649)
2. android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2674)
3. android.app.ActivityThread.access$2200(ActivityThread.java:131)
4. android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975)
5. android.os.Handler.dispatchMessage(Handler.java:99)
6. android.os.Looper.loop(Looper.java:123)
7. android.app.ActivityThread.main(ActivityThread.java:4702)
8. java.lang.reflect.Method.invokeNative(Native Method)
9. java.lang.reflect.Method.invoke(Method.java:521)
10. com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11. com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
12. dalvik.system.NativeStart.main(Native Method)
-------------------------------

----------- Cause -----------
android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

1. android.view.LayoutInflater.createView(LayoutInflater.java:513)
2. com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
3. android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
4. android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
5. android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
6. android.view.LayoutInflater.inflate(LayoutInflater.java:382)
7. android.view.LayoutInflater.inflate(LayoutInflater.java:320)
8. android.view.LayoutInflater.inflate(LayoutInflater.java:276)
9. com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:208)
10. android.app.Activity.setContentView(Activity.java:1629)
11. com.solvek.sample.ui.BaseActivity.onCreate(BaseActivity.java:23)
12. com.solvek.sample.ui.tour.TourActivity.onCreate(TourActivity.java:161)
13. android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
14. android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2587)
15. android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2674)
16. android.app.ActivityThread.access$2200(ActivityThread.java:131)
17. android.app.ActivityThread$H.handleMessage(ActivityThread.java:1975)
18. android.os.Handler.dispatchMessage(Handler.java:99)
19. android.os.Looper.loop(Looper.java:123)
20. android.app.ActivityThread.main(ActivityThread.java:4702)
21. java.lang.reflect.Method.invokeNative(Native Method)
22. java.lang.reflect.Method.invoke(Method.java:521)
23. com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
24. com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
25. dalvik.system.NativeStart.main(Native Method)
-----------------------------

-------- Environment --------
Time =2010-12-20 08:27:35 AM
Device =tmobile/htc_espresso/espresso/espresso:2.1-update1/ERE27/216830:user/release-keys
Make =HTC
Model =T-Mobile myTouch 3G Slide
Product =htc_espresso
App =com.fsp.android.f, version 2.0.9 (build 1232)

Here is a result of XML, however such error occurs in other xmls

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <ViewFlipper android:layout_gravity="fill" android:id="@+id/flipper" android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_1"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_2"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_3"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_4"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_5"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_6"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_7"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_8"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_9"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_10"/>
        <ImageView android:scaleType="fitXY" android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@drawable/tour_11"/>
    </ViewFlipper>

    <LinearLayout android:id="@+id/exit_bar" android:layout_gravity="top" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue_bar" android:visibility="invisible">
        <Button android:background="@drawable/orange_btn" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" android:textStyle="bold" android:textColor="#000000" android:shadowColor="#ffffff" android:shadowRadius="1.6" android:shadowDx="1.5" android:shadowDy="1.3" android:id="@+id/exit_tour_btn" android:text="Exit" android:layout_marginLeft="20dip"/>
        <TextView android:layout_height="wrap_content" android:textColor="#ffffff" android:layout_gravity="center" android:layout_width="110dip" android:layout_marginLeft="20dip" android:textSize="16dip" android:textStyle="bold" android:text="Life360 Tour"/>

    </LinearLayout>

    <Button style="@style/BlueBtn" android:text="Continue" android:layout_marginTop="40dip" android:id="@+id/continue_btn" android:visibility="gone" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_gravity="center" />

    <FrameLayout android:id="@+id/bottom_bar" android:layout_gravity="bottom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/blue_bar" android:visibility="invisible">
        <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/left" android:layout_gravity="left|center" android:background="@drawable/tour_left" android:layout_marginLeft="10dip"/>
        <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/right" android:layout_gravity="right|center" android:background="@drawable/tour_right" android:layout_marginRight="10dip"/>
    </FrameLayout>
</merge>


来源: stackexchange

问:
Dynamic menu for inventory
I want to make a dynamic menu in which it detects whether you have one or more durability in your inventory. If you do have one or more, it prints out into the menu. Otherwise, it won't.

Here's the code:

```<code>#include <iostream>
#include <vector>
using namespace std;
class A {
protected:
    int durability = 3;
public:
    virtual void attack() { };
    virtual int usage() { return 1; };
    virtual string weaponName() { return "Sword x"; };
};
class B : public A
{

public:
    void attack() { durability--; cout << "B Attack" << endl; cout << durability; };
    string weaponName() { return "Sword B"; };

};
class C : public A
{
public:
    int usage() { return durability; };
    void attack() { durability--; cout << "C Attack" << endl;cout << durability; };
    string weaponName() { return "Sword C"; };
};
class D : public A
{

public:
    void attack() { durability--;  cout << "D Attack" << endl;cout << durability; };
    string weaponName() { return "Sword D"; };
};
int main(void)
{
B * b = new B;
C * c = new C;
D * d = new D;
    int k = 10;
    vector <A*> tableOfAs;
    tableOfAs.push_back(b);
    tableOfAs.push_back(c);
    tableOfAs.push_back(d);
    while (--k>0)
    {
        int i = 0;
        vector <A*> options;
        for (i = 0; i < tableOfAs.size(); i++)
        {
            if (tableOfAs[i]->usage() > 0){
                options.push_back(tableOfAs[i]);
        } else { delete tableOfAs[i]; }
        }
        if (options.size() == 0)
            break;
        cout << "Attack Options:" << endl;
            for (i = 0; i < options.size(); i++)
            cout << i << ". " << options[i]->weaponName().c_str() << endl;
        int choise;
        cin >> choise;
        if (choise<0 || choise > options.size()-1)
            cout << "Wrong option" << endl;
        else
            options[choise]->attack();
    }
    return 1;
}
</code>```

My problem here is that the durability gets zeroed and gets deleted and then after placing another choice, the console crashes.

答:
Looking back at this old post. I revised the code from boring32. I made it a lot easier to read for those new to programming.

```<code>#include <iostream>
#include <string>
#include <vector>
using namespace std;
class baseClass {
public:
    virtual void attack() {};
    virtual int usage() { return 1; }
    virtual string weaponName() { return "Sword x"; }
};
class Sword : public baseClass
{
private:
    int durability;
    string name;
public:
    /*Sets the name and the durability of the sword*/
    Sword(string nameToSet, int dur) :name(nameToSet),durability(dur) {}
    int usage() { return durability; }
    /*Decreases durability by one and tells the name of the sword used in the attack*/
    void attack() {
        durability--;
        cout << name <<" Sword Attack" << endl;
    }
    /*returns weapon name*/
    string weaponName() { return name +" Sword"; }
};
int main()
{
    Sword sworda("One", 1), swordb("Two", 2), swordc("Three", 3);
    int loop = 10;
    int choice;
    /*Add swords into a holding container first*/
    vector <baseClass*> holdingContainer;
    holdingContainer.push_back(&sworda);
    holdingContainer.push_back(&swordb);
    holdingContainer.push_back(&swordc);

    while (--loop>0)
    {
        /*Decide whether swords in the holding container has a durability of one or more
          before adding them into the menu*/
        vector <baseClass*> swordWithDurabilityContainer;
        for (int i = 0; i < holdingContainer.size(); i++)
        {
            if (holdingContainer[i]->usage() > 0) {
                swordWithDurabilityContainer.push_back(holdingContainer[i]);
            }
        }

        /*Check if there's any items in the swordWithDurabilityContainer otherwise break out of the loop*/
        if (swordWithDurabilityContainer.size() == 0) { break; }

        /*Print the items*/
        cout << "Attack Options:" << endl;
        for (int i = 0; i < swordWithDurabilityContainer.size(); i++) {
            cout << i << ". " << swordWithDurabilityContainer[i]->weaponName().c_str() << endl;
        }
        /*Ask for user input*/
        cin >> choice;

        /*Check if the input is valid*/
        if (choice<0 || choice > swordWithDurabilityContainer.size() - 1) {
            cout << "Wrong option" << endl;
        }
        else {
            swordWithDurabilityContainer[choice]->attack();
        }
    }
    /*Notify the user that the loop has ended*/
    cout << "No more items in the list(swordWithDurabilityContainer variable)";
}
</code>```

Back then when I was reading boring32's answer, I couldn't read it because there are barely any comments and variables named as "a", "b" and Classes named "A", "B" and classes which have no correlation with the code. I came back to fix it. Although I'm not sure why some people make it a habit to leave a semi-working code in forums/threads.

No offense to those who also do this.

ContentLicense: CC BY-SA 3.0

Title: Dynamic menu for inventory

Body:
I want to make a dynamic menu in which it detects whether you have one or more durability in your inventory. If you do have one or more, it prints out into the menu. Otherwise, it won't.

Here's the code:

#include <iostream>
#include <vector>
using namespace std;
class A {
protected:
    int durability = 3;
public:
    virtual void attack() { };
    virtual int usage() { return 1; };
    virtual string weaponName() { return "Sword x"; };
};
class B : public A
{

public:
    void attack() { durability--; cout << "B Attack" << endl; cout << durability; };
    string weaponName() { return "Sword B"; };

};
class C : public A
{
public:
    int usage() { return durability; };
    void attack() { durability--; cout << "C Attack" << endl;cout << durability; };
    string weaponName() { return "Sword C"; };
};
class D : public A
{

public:
    void attack() { durability--;  cout << "D Attack" << endl;cout << durability; };
    string weaponName() { return "Sword D"; };
};
int main(void)
{
B * b = new B;
C * c = new C;
D * d = new D;
    int k = 10;
    vector  tableOfAs;
    tableOfAs.push_back(b);
    tableOfAs.push_back(c);
    tableOfAs.push_back(d);
    while (--k>0)
    {
        int i = 0;
        vector  options;
        for (i = 0; i < tableOfAs.size(); i++)
        {
            if (tableOfAs[i]->usage() > 0){
                options.push_back(tableOfAs[i]);
        } else { delete tableOfAs[i]; }
        }
        if (options.size() == 0)
            break;
        cout << "Attack Options:" << endl;
            for (i = 0; i < options.size(); i++)
            cout << i << ". " << options[i]->weaponName().c_str() << endl;
        int choise;
        cin >> choise;
        if (choise<0 || choise > options.size()-1)
            cout << "Wrong option" << endl;
        else
            options[choise]->attack();
    }
    return 1;
}

My problem here is that the durability gets zeroed and gets deleted and then after placing another choice, the console crashes.

Body:
Looking back at this old post. I revised the code from boring32. I made it a lot easier to read for those new to programming.

#include <iostream>
#include <string>
#include <vector>
using namespace std;
class baseClass {
public:
    virtual void attack() {};
    virtual int usage() { return 1; }
    virtual string weaponName() { return "Sword x"; }
};
class Sword : public baseClass
{
private:
    int durability;
    string name;
public:
    /*Sets the name and the durability of the sword*/
    Sword(string nameToSet, int dur) :name(nameToSet),durability(dur) {}
    int usage() { return durability; }
    /*Decreases durability by one and tells the name of the sword used in the attack*/
    void attack() {
        durability--;
        cout << name <<" Sword Attack" << endl;
    }
    /*returns weapon name*/
    string weaponName() { return name +" Sword"; }
};
int main()
{
    Sword sworda("One", 1), swordb("Two", 2), swordc("Three", 3);
    int loop = 10;
    int choice;
    /*Add swords into a holding container first*/
    vector <baseClass*> holdingContainer;
    holdingContainer.push_back(&sworda);
    holdingContainer.push_back(&swordb);
    holdingContainer.push_back(&swordc);

    while (--loop>0)
    {
        /*Decide whether swords in the holding container has a durability of one or more
          before adding them into the menu*/
        vector <baseClass*> swordWithDurabilityContainer;
        for (int i = 0; i < holdingContainer.size(); i++)
        {
            if (holdingContainer[i]->usage() > 0) {
                swordWithDurabilityContainer.push_back(holdingContainer[i]);
            }
        }

        /*Check if there's any items in the swordWithDurabilityContainer otherwise break out of the loop*/
        if (swordWithDurabilityContainer.size() == 0) { break; }

        /*Print the items*/
        cout << "Attack Options:" << endl;
        for (int i = 0; i < swordWithDurabilityContainer.size(); i++) {
            cout << i << ". " << swordWithDurabilityContainer[i]->weaponName().c_str() << endl;
        }
        /*Ask for user input*/
        cin >> choice;

        /*Check if the input is valid*/
        if (choice<0 || choice > swordWithDurabilityContainer.size() - 1) {
            cout << "Wrong option" << endl;
        }
        else {
            swordWithDurabilityContainer[choice]->attack();
        }
    }
    /*Notify the user that the loop has ended*/
    cout << "No more items in the list(swordWithDurabilityContainer variable)";
}

Back then when I was reading boring32's answer, I couldn't read it because there are barely any comments and variables named as "a", "b" and Classes named "A", "B" and classes which have no correlation with the code. I came back to fix it. Although I'm not sure why some people make it a habit to leave a semi-working code in forums/threads.

No offense to those who also do this.


问:
Displaying values in modal from ng-repeat
I have list of stories with images , content and title in ng-repeat.
When I click on particular story , I need a bootstrap model to open and values to be displayed . I am doing it by calling a function showStories(); But I couldnt do it . I am getting empty value since its globally declared as

```<code>            $scope.selectedStoryPreview =  "";
            $scope.selectedStoryContent = "";
            $scope.selectedStoryTitle  = "";
</code>```

Html :

```<code><div class="image" ng-repeat="item in filteredStories track by $index">
    <img ng-src="{{item.images}}" style="cursor: pointer;" ng-click="showStories(item)" data-toggle="modal" data-target="#storyPreview">
    <button><span>{{item.title}}</span>
    </button>
</div>
</code>```

JS:

```<code>$scope.showStories = function(item) {

            $scope.selectedStoryPreview =  item.images;
            $scope.selectedStoryContent = item.content;
            $scope.selectedStoryTitle  = item.title;

        }
</code>```

Modal :

```<code><div class="modal fade" id="storyPreview" role="dialog"  data-keyboard="false" data-backdrop="static" style="padding-top: 8em;">

        <div class="modal-dialog">
  <div class="modal-content" style="text-align: center;">
    <div class="modal-header imagemodalhead">
        <h4>{{selectedStoryTitle}}</h4>
        <a class="edit" ng-click="openmanageprofile()"><img src="css/images/edit.png">
        </a>
    </div>
    <div class="modal-body" style="background: #eee;">

        <div class="row">

            <img class="file-imageStory" ng-src="{{selectedStoryPreview}}" />

        </div>
        <br>
        <div class="row">
            <div class=" col-sm-12 storyPrv">
                <span class="styletheStory">{{selectedStoryContent}}</span>
            </div>
        </div>

        <div class="modal-footer imagefooter">
            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;">close</button>
        </div>

    </div>
</code>```

答:
$scope.model is undefined. Set it as $scope.model = {} This way
you can dynamically add properties to it at compile time.

Moreover, you could use data-toggle="modal"
data-target="#viewdetails" as the action event to point to correct
modal.

Also, no need to pass individual properties as arguments in the
method showStories(item), you could send out complete object and
obtain its properties.

DEMO:

Click on the image to open modal.

function MyCtrl($scope) {

  $scope.filteredStories = [{
    id: 1,
    images: 'sample1.png',
    title: "sample1",
    content: "content here..."
  }, {
    id: 2,
    images: 'sample2.png',
    title: "sample2",
    content: "content here..."
  }, {
    id: 3,
    images: 'sample3.png',
    title: "sample3",
    content: "content here..."
  }, {
    id: 4,
    images: 'sample4.png',
    title: "sample4",
    content: "content here..."
  }]

  $scope.showStories = function(item) {
    $scope.selectedStoryPreview = item.images;
    $scope.selectedStoryContent = item.content;
    $scope.selectedStoryTitle = item.title;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body ng-app ng-controller="MyCtrl">
  <div class="image" ng-repeat="item in filteredStories track by $index">
    <img ng-src="{{item.images}}" style="cursor: pointer;" ng-click="showStories(item)" data-toggle="modal" data-target="#storypreview">
    <button><span>{{item.title}}</span>
    </button>
  </div>
  <div class="modal fade" id="storypreview" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content" style="text-align: center;">
        <div class="modal-header imagemodalhead">
          <h4>{{selectedStoryTitle}}</h4>
          <img src="css/images/edit.png">

        </div>
        <div class="modal-body" style="background: #eee;">
          <div class="row">
            <img class="file-imageStory" ng-src="{{selectedStoryPreview}}" />
          </div>
          <br>
          <div class="row">
            <div class=" col-sm-12 storyPrv">
              <span class="styletheStory">{{selectedStoryContent}}</span>
            </div>
          </div>
          <div class="modal-footer imagefooter">
            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;" data-dismiss="modal">close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</body></code>```

Body:
I have list of stories with images , content and title in ng-repeat.
When I click on particular story , I need a bootstrap model to open and values to be displayed . I am doing it by calling a function showStories(); But I couldnt do it . I am getting empty value since its globally declared as

            $scope.selectedStoryPreview =  "";
            $scope.selectedStoryContent = "";
            $scope.selectedStoryTitle  = "";

Html :

    <button>{{item.title}}
    </button>

JS:

$scope.showStories = function(item) {

            $scope.selectedStoryPreview =  item.images;
            $scope.selectedStoryContent = item.content;
            $scope.selectedStoryTitle  = item.title;

        }

Modal :

{{selectedStoryTitle}}

                {{selectedStoryContent}}

            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;">close</button>

Body:
$scope.model is undefined. Set it as $scope.model = {} This way
you can dynamically add properties to it at compile time.

Moreover, you could use data-toggle="modal"
data-target="#viewdetails" as the action event to point to correct
modal.

Also, no need to pass individual properties as arguments in the
method showStories(item), you could send out complete object and
obtain its properties.

DEMO:

Click on the image to open modal.

function MyCtrl($scope) {

  $scope.filteredStories = [{
    id: 1,
    images: 'sample1.png',
    title: "sample1",
    content: "content here..."
  }, {
    id: 2,
    images: 'sample2.png',
    title: "sample2",
    content: "content here..."
  }, {
    id: 3,
    images: 'sample3.png',
    title: "sample3",
    content: "content here..."
  }, {
    id: 4,
    images: 'sample4.png',
    title: "sample4",
    content: "content here..."
  }]

  $scope.showStories = function(item) {
    $scope.selectedStoryPreview = item.images;
    $scope.selectedStoryContent = item.content;
    $scope.selectedStoryTitle = item.title;
  }
}

<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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<body ng-app ng-controller="MyCtrl">
  <div class="image" ng-repeat="item in filteredStories track by $index">
    <img ng-src="{{item.images}}" style="cursor: pointer;" ng-click="showStories(item)" data-toggle="modal" data-target="#storypreview">
    <button><span>{{item.title}}</span>
    </button>
  </div>
  <div class="modal fade" id="storypreview" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content" style="text-align: center;">
        <div class="modal-header imagemodalhead">
          <h4>{{selectedStoryTitle}}</h4>
          <a class="edit" ng-click="openmanageprofile()"><img src="css/images/edit.png">
          </a>
        </div>
        <div class="modal-body" style="background: #eee;">
          <div class="row">
            <img class="file-imageStory" ng-src="{{selectedStoryPreview}}" />
          </div>
          <br>
          <div class="row">
            <div class=" col-sm-12 storyPrv">
              <span class="styletheStory">{{selectedStoryContent}}</span>
            </div>
          </div>
          <div class="modal-footer imagefooter">
            <button type="button" class="button share" ng-click="closePreview()" style="background-color: #7B7D7D; color: black;" data-dismiss="modal">close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>


问:
Making images responsive
I'm creating an image slider and when the screen gets to 600 or below I want the images to be 100% of the screen width. I have tried to use width: 100% and max: width: 600px thinking this would make them responsive. But now I realise that that just makes them 600px wide not 100% of the screen with a max width. How can I achieve this?

$(document).ready(function(){
  var image_width = $(".img_cont").width();
  var image_count = $(".carousel li").length;
  var carousel_width = image_width * image_count + image_width;
  var padding = $(".active img").height() /4;

  $(".carousel").css("width", carousel_width);
  $(".img_cont").css("paddingTop", padding);
  $(".active").css("paddingTop", 0);

  $(window).resize(function(){
    if($(window).width() <= 600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", 0);
        $(".active").css("paddingTop", 0);
      }else if($(window).width() < 1600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }else {
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }
      });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
  padding: 0;
  margin: 0;
}

body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.cont{
  position: relative;
  font-size: 0;/*removes white space*/
  margin: 60px auto;
  padding: 0;
/*   overflow: hidden; */
}

.carousel{
  padding: 0;
  list-style-type: none;
  height: auto;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: hidden;
}

.carousel li{
  float: left;
  background-color: pink;
}

#next{
  position: absolute;
  top: 45%;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  font-size: 0;
  z-index: 1;
}

#prev{
  position: absolute;
  top: 45%;
  left: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  z-index: 1;
}

.img_cont img{
  width: 100%;
  max-width: 600px;
  height: auto;
  max-height:600px;
}

.active img{
  width: 100%;
  max-width: 1200px;
  height: auto;
  padding: 0;
}

@media screen and (max-width: 1600px){
  .img_cont img{
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 1000px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1200px){
  .img_cont img{
    width: 100%;
    max-width: 400px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 800px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1000px){
  .img_cont img{
    width: 100%;
    max-width: 300px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}</code>```

```

答:
I managed solve it myself. I changed the 600px media query to this

```<code>@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100vw;
    /* max-width: 600px; */
    height: auto;
    padding: 0;
    max-width: none;
  }

  .active img{
    width: 100vw;
    /* max-width: 600px; */
    height: auto;
    padding: 0;
    max-width: none;
  }
}
</code>```

But I don't understand why when I change 100vw to 100% the image just displays at its original width and not 100% of the screen width. Can anyone explain this?

Title: Making images responsive

Body:
I'm creating an image slider and when the screen gets to 600 or below I want the images to be 100% of the screen width. I have tried to use width: 100% and max: width: 600px thinking this would make them responsive. But now I realise that that just makes them 600px wide not 100% of the screen with a max width. How can I achieve this?

$(document).ready(function(){
  var image_width = $(".img_cont").width();
  var image_count = $(".carousel li").length;
  var carousel_width = image_width * image_count + image_width;
  var padding = $(".active img").height() /4;

  $(".carousel").css("width", carousel_width);
  $(".img_cont").css("paddingTop", padding);
  $(".active").css("paddingTop", 0);

  $(window).resize(function(){
    if($(window).width() <= 600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", 0);
        $(".active").css("paddingTop", 0);
      }else if($(window).width() < 1600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }else {
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }
      });
  });

*{
  padding: 0;
  margin: 0;
}

body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.cont{
  position: relative;
  font-size: 0;/*removes white space*/
  margin: 60px auto;
  padding: 0;
/*   overflow: hidden; */
}

.carousel{
  padding: 0;
  list-style-type: none;
  height: auto;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: hidden;
}

.carousel li{
  float: left;
  background-color: pink;
}

#next{
  position: absolute;
  top: 45%;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  font-size: 0;
  z-index: 1;
}

#prev{
  position: absolute;
  top: 45%;
  left: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  z-index: 1;
}

.img_cont img{
  width: 100%;
  max-width: 600px;
  height: auto;
  max-height:600px;
}

.active img{
  width: 100%;
  max-width: 1200px;
  height: auto;
  padding: 0;
}

@media screen and (max-width: 1600px){
  .img_cont img{
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 1000px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1200px){
  .img_cont img{
    width: 100%;
    max-width: 400px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 800px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1000px){
  .img_cont img{
    width: 100%;
    max-width: 300px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

Body:
I managed solve it myself. I changed the 600px media query to this

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100vw;
    /* max-width: 600px; */
    height: auto;
    padding: 0;
    max-width: none;
  }

  .active img{
    width: 100vw;
    /* max-width: 600px; */
    height: auto;
    padding: 0;
    max-width: none;
  }
}

But I don't understand why when I change 100vw to 100% the image just displays at its original width and not 100% of the screen width. Can anyone explain this?


问:
How to programmatically create and shift list
At the moment I have this in my code

```<code>up = [1, 0, 0, 0]
down = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]
</code>```

I want to add another variable I need to know do

```<code>up = [1, 0, 0, 0, 0]
down = [0, 1, 0, 0, 0]
left = [0, 0, 1, 0, 0]
right = [0, 0, 0, 1, 0]
a = [0, 0, 0, 0, 1]
</code>```

And I'm not sure how many variables I need or I might end up needing a lot.

Is it possible to create a list of the variables I need, and then have a loop going through each one and doing this?

I'm not really sure how to go about figuring this out.

答:
What you are doing is called "one-hot encoding", and you could easily do that.
First, build a dict of your "variables", but instead of writing each one as [0,0,0,1] just write their indexes. Or better yet, use an indexed list to store their names:

```<code>mylist = ['up','down','left','right']
</code>```

Then, define a function that takes that list / dict and the "variable" number (which is really the key in that dict, or the item in the list) and outputs the correct "one-hot" encoding:

```<code>def onehot(mylist, key):
    index = mylist.index(key)
    zeros = [0 for i in mylist]
    zeros[index] = 1
    return zeros
</code>```

Now if your list is as it is written above, running onehot(mylist, 'up') will output [1,0,0,0]. If you decide to extend that list at any time, you could just run mylist.append('newname') and once again, run our little helper - onehot(mylist, 'newname') will output [0,0,0,0,1]

An alternative implementation is to do all the work in a single list comprehension.  Finding the index can be costly (it is O(n)) as the list has to be searched element by element.  Reducing this to one pass reduces the complexity a little:

```<code>def onehot(mylist, key):
    return [int(i == key) for i in mylist]
</code>```

Body:
At the moment I have this in my code

up = [1, 0, 0, 0]
down = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]

I want to add another variable I need to know do

up = [1, 0, 0, 0, 0]
down = [0, 1, 0, 0, 0]
left = [0, 0, 1, 0, 0]
right = [0, 0, 0, 1, 0]
a = [0, 0, 0, 0, 1]

And I'm not sure how many variables I need or I might end up needing a lot.

Is it possible to create a list of the variables I need, and then have a loop going through each one and doing this?

I'm not really sure how to go about figuring this out.

Body:
What you are doing is called "one-hot encoding", and you could easily do that.
First, build a dict of your "variables", but instead of writing each one as [0,0,0,1] just write their indexes. Or better yet, use an indexed list to store their names:

mylist = ['up','down','left','right']

Then, define a function that takes that list / dict and the "variable" number (which is really the key in that dict, or the item in the list) and outputs the correct "one-hot" encoding:

def onehot(mylist, key):
    index = mylist.index(key)
    zeros = [0 for i in mylist]
    zeros[index] = 1
    return zeros

Now if your list is as it is written above, running onehot(mylist, 'up') will output [1,0,0,0]. If you decide to extend that list at any time, you could just run mylist.append('newname') and once again, run our little helper - onehot(mylist, 'newname') will output [0,0,0,0,1]

An alternative implementation is to do all the work in a single list comprehension.  Finding the index can be costly (it is O(n)) as the list has to be searched element by element.  Reducing this to one pass reduces the complexity a little:

def onehot(mylist, key):
    return [int(i == key) for i in mylist]


问:
How to split `NSmutableArray` array array to chunks swift 3?
```<code>NSMutableArray *sample;
</code>```

I have an NSmutableArray, and I want to split it into chunks. I have tried checking the internet didn't find the solution for it. I got the link to split integer array.

答:
You can use the subarray method.

```<code>let array  = NSArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

let left  = array.subarray(with: NSMakeRange(0, 5))
let right = array.subarray(with: NSMakeRange(5, 5))
</code>```

Body:
NSMutableArray *sample;

I have an NSmutableArray, and I want to split it into chunks. I have tried checking the internet didn't find the solution for it. I got the link to split integer array.

Body:
You can use the subarray method.

let array  = NSArray(array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

let left  = array.subarray(with: NSMakeRange(0, 5))
let right = array.subarray(with: NSMakeRange(5, 5))


问:
C++ Boost Mutex Lock
Recently I am playing around Boost mutex and I am not sure if I can do the following:

```<code>boost::recursive_mutex ListLock;

int main(){
  ListLock.lock();
  function1();
  ListLock.unlock();
}

void function1(){
  ListLock.lock();
  //some operations
  ListLock.unlock();
}
</code>```

Is it okay to lock the ListLock twice?

答:
It depends on the lock. Recursive locks allow ... recursive locks. So, no problem in your example.

Non-recursive locks (such as std::mutex or boost::mutex) would deadlock (technically, I think the behaviour is unspecified, but most POSIX thread implementations either deadlock or raise an exception based on EDEADLK).

See http://en.cppreference.com/w/cpp/thread/recursive_mutex for recursive_mutex

Title: C++ Boost Mutex Lock

Body:
Recently I am playing around Boost mutex and I am not sure if I can do the following:

boost::recursive_mutex ListLock;

int main(){
  ListLock.lock();
  function1();
  ListLock.unlock();
}

void function1(){
  ListLock.lock();
  //some operations
  ListLock.unlock();
}

Is it okay to lock the ListLock twice?


问:
Best way to dynamically get column names from oracle tables
We are using an extractor application that will export data from the database to csv files. Based on some condition variable it extracts data from different tables, and for some conditions we have to use UNION ALL as the data has to be extracted from more than one table. So to satisfy the UNION ALL condition we are using nulls to match the number of columns.

Right now all the queries in the system are pre-built based on the condition variable. The problem is whenever there is change in the table projection (i.e new column added, existing column modified, column dropped) we have to manually change the code in the application.

Can you please give some suggestions how to extract the column names dynamically so that any changes in the table structure do not require change in the code?

My concern is the condition that decides which table to query. The variable condition is
like

if the condition is A, then load from TableX

if the condition is B  then load from TableA and TableY.

We must know from which table we need to get data.  Once we know the table it is  straightforward to query the column names from the data dictionary.  But there is one more condition, which is that some columns need to be excluded, and these columns are different for each table.

I am trying to solve the problem only for dynamically generating the list columns. But my manager told me to make solution on the conceptual level rather than just fixing. This is a very big system with providers and consumers constantly loading and consuming data. So he wanted solution that can be general.

So what is the best way for storing condition, tablename, excluded columns?  One way is storing in database.   Are there any other ways? If yes what is the best?  As I have to give at least a couple of ideas before finalizing.

Thanks,

答:
Ok, MNC, try this for size (paste it into a new console app):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Test.Api;
using Test.Api.Classes;
using Test.Api.Interfaces;
using Test.Api.Models;

namespace Test.Api.Interfaces
{
    public interface ITable
    {
        int Id { get; set; }
        string Name { get; set; }
    }
}

namespace Test.Api.Models
{
    public class MemberTable : ITable
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class TableWithRelations
    {
        public MemberTable Member { get; set; }
        // list to contain partnered tables
        public IList<ITable> Partner { get; set; }

        public TableWithRelations()
        {
            Member = new MemberTable();
            Partner = new List<ITable>();
        }
    }
}

namespace Test.Api.Classes
{
    public class MyClass
    {
        private readonly IList<TableWithRelations> _tables;

        public MyClass()
        {
            // tableA stuff
            var tableA = new TableWithRelations { Member = { Id = 1, Name = "A" } };
            var relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 2,
                   Name = "B"
                }
             };
            tableA.Partner = relatedclasses;

            // tableB stuff
            var tableB = new TableWithRelations { Member = { Id = 2, Name = "B" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 3,
                   Name = "C"
                }
             };
            tableB.Partner = relatedclasses;

            // tableC stuff
            var tableC = new TableWithRelations { Member = { Id = 3, Name = "C" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 2,
                   Name = "D"
                }
             };
            tableC.Partner = relatedclasses;

            // tableD stuff
            var tableD = new TableWithRelations { Member = { Id = 3, Name = "D" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 1,
                   Name = "A"
                },
                new MemberTable
                {
                   Id = 2,
                   Name = "B"
                },
             };
            tableD.Partner = relatedclasses;

            // add tables to the base tables collection
            _tables = new List<TableWithRelations> { tableA, tableB, tableC, tableD };
        }

        public IList<ITable> Compare(int tableId, string tableName)
        {
            return _tables.Where(table => table.Member.Id == tableId
                            && table.Member.Name == tableName)
                        .SelectMany(table => table.Partner).ToList();
        }
    }
}

namespace Test.Api
{
    public class TestClass
    {
        private readonly MyClass _myclass;
        private readonly IList<ITable> _relatedMembers;

        public IList<ITable> RelatedMembers
        {
            get { return _relatedMembers; }
        }

        public TestClass(int id, string name)
        {
            this._myclass = new MyClass();
            // the Compare method would take your two paramters and return
            // a mathcing set of related tables that formed the related tables
            _relatedMembers = _myclass.Compare(id, name);
            // now do something wityh the resulting list
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // change these values to suit, along with rules in MyClass
        var id = 3;
        var name = "D";
        var testClass = new TestClass(id, name);

        Console.Write(string.Format("For Table{0} on Id{1}\r\n", name, id));
        Console.Write("----------------------\r\n");
        foreach (var relatedTable in testClass.RelatedMembers)
        {
            Console.Write(string.Format("Related Table{0} on Id{1}\r\n",
                      relatedTable.Name, relatedTable.Id));
        }
        Console.Read();
    }
}
</code>```

I'll get back in a bit to see if it fits or not.

ContentLicense: CC BY-SA 2.5

Body:
Ok, MNC, try this for size (paste it into a new console app):

using System;
using System.Collections.Generic;
using System.Linq;
using Test.Api;
using Test.Api.Classes;
using Test.Api.Interfaces;
using Test.Api.Models;

namespace Test.Api.Interfaces
{
    public interface ITable
    {
        int Id { get; set; }
        string Name { get; set; }
    }
}

namespace Test.Api.Models
{
    public class MemberTable : ITable
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class TableWithRelations
    {
        public MemberTable Member { get; set; }
        // list to contain partnered tables
        public IList<ITable> Partner { get; set; }

        public TableWithRelations()
        {
            Member = new MemberTable();
            Partner = new List<ITable>();
        }
    }
}

namespace Test.Api.Classes
{
    public class MyClass
    {
        private readonly IList<TableWithRelations> _tables;

        public MyClass()
        {
            // tableA stuff
            var tableA = new TableWithRelations { Member = { Id = 1, Name = "A" } };
            var relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 2,
                   Name = "B"
                }
             };
            tableA.Partner = relatedclasses;

            // tableB stuff
            var tableB = new TableWithRelations { Member = { Id = 2, Name = "B" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 3,
                   Name = "C"
                }
             };
            tableB.Partner = relatedclasses;

            // tableC stuff
            var tableC = new TableWithRelations { Member = { Id = 3, Name = "C" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 2,
                   Name = "D"
                }
             };
            tableC.Partner = relatedclasses;

            // tableD stuff
            var tableD = new TableWithRelations { Member = { Id = 3, Name = "D" } };
            relatedclasses = new List<ITable>
             {
                new MemberTable
                {
                   Id = 1,
                   Name = "A"
                },
                new MemberTable
                {
                   Id = 2,
                   Name = "B"
                },
             };
            tableD.Partner = relatedclasses;

            // add tables to the base tables collection
            _tables = new List<TableWithRelations> { tableA, tableB, tableC, tableD };
        }

        public IList<ITable> Compare(int tableId, string tableName)
        {
            return _tables.Where(table => table.Member.Id == tableId
                            && table.Member.Name == tableName)
                        .SelectMany(table => table.Partner).ToList();
        }
    }
}

namespace Test.Api
{
    public class TestClass
    {
        private readonly MyClass _myclass;
        private readonly IList<ITable> _relatedMembers;

        public IList<ITable> RelatedMembers
        {
            get { return _relatedMembers; }
        }

        public TestClass(int id, string name)
        {
            this._myclass = new MyClass();
            // the Compare method would take your two paramters and return
            // a mathcing set of related tables that formed the related tables
            _relatedMembers = _myclass.Compare(id, name);
            // now do something wityh the resulting list
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // change these values to suit, along with rules in MyClass
        var id = 3;
        var name = "D";
        var testClass = new TestClass(id, name);

        Console.Write(string.Format("For Table{0} on Id{1}\r\n", name, id));
        Console.Write("----------------------\r\n");
        foreach (var relatedTable in testClass.RelatedMembers)
        {
            Console.Write(string.Format("Related Table{0} on Id{1}\r\n",
                      relatedTable.Name, relatedTable.Id));
        }
        Console.Read();
    }
}

I'll get back in a bit to see if it fits or not.


问:
Center align the absolute div without using left:0, right:0, width:100%
How to center a absolute div without using left, right and width:100%? And the width should be auto

```<code>div{
    position: absolute;
    width: 100%;
    margin: 0 auto;
    display: table;
}
</code>```

答:
.container {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #EEE;
}
.answer {
  position: absolute;
  width: auto;
  padding: 10px;
  background-color: #CCC;

  transform: translate(-50%, -50%);
  margin: 50% 0 0 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="answer">absolute</div>
</div></code>```

Body:
How to center a absolute div without using left, right and width:100%? And the width should be auto

div{
    position: absolute;
    width: 100%;
    margin: 0 auto;
    display: table;
}

Body:
.container {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #EEE;
}
.answer {
  position: absolute;
  width: auto;
  padding: 10px;
  background-color: #CCC;

  transform: translate(-50%, -50%);
  margin: 50% 0 0 50%;
}

<div class="container">
  <div class="answer">absolute</div>
</div>


问:
How do i get the horizontal line behind buttons?
Hi there i was trying to create background line behind the buttons, before that i was using image but i want the line.

```<code><div class="feedback-option">
  <div class="radios2">
    <label>
      <input type="radio" name="rating-1" value="1">
      <span>1</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="2" />
      <span>2</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="3">
      <span>3</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="4">
      <span>4</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="5">
      <span>5</span>
    </label>
  </div>
</div>
</code>```

JsFiddle

答:
Since there is no line in HTML. I have achieved the same by adding an empty div with required background-color and height. And with position: absolute to place it where required.

```<code>.line {
  position: absolute;
  top: 25px;
  height: 5px;
  width: 100%;
  background-color: black;
}
</code>```

P.S: I think you were trying to center the radios. For that I have changed display: block; for .radios2.

.radios2 {
  display: block;
  text-align: center;
}

.line {
  position: absolute;
  top: 25px;
  height: 5px;
  width: 100%;
  background-color: black;
}

.radios2 label + label {
    margin-left: 10px;
}

.radios2 input[type="radio"] {
    opacity: 0;
    /* hidden but still tabable */
    position: absolute;
}

.radios2 input[type="radio"] + span {
    display: block;
    line-height: 40px;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    background: #eee;
    color: #555;
    -webkit-transform: scale(1);
    transform: scale(1);
}

.radios2 input[type="radio"]:not(:checked) + span:hover {
    cursor: pointer;
    -webkit-transform: scale(1.25);
    transform: scale(1.25);
    -webkit-transition: -webkit-transform 0.2s ease-in;
    transition: -webkit-transform 0.2s ease-in;
    transition: transform 0.2s ease-in;
    transition: transform 0.2s ease-in, -webkit-transform 0.2s ease-in;
}

.radios2 input[type="radio"]:checked + span {
    color: #D9E7FD;
    background-color: #4285F4;
}

.radios2 input[type="radio"]:focus + span {
    color: #fff;
}

label {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="feedback-option">
<div class="line"></div>
  <div class="radios2">
    <label>
      <input type="radio" name="rating-1" value="1">
      <span>1</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="2" />
      <span>2</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="3">
      <span>3</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="4">
      <span>4</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="5">
      <span>5</span>
    </label>
  </div>
</div></code>```

Body:
Hi there i was trying to create background line behind the buttons, before that i was using image but i want the line.

      <input type="radio" name="rating-1" value="1">
      1

      <input type="radio" name="rating-1" value="2" />
      2

      <input type="radio" name="rating-1" value="3">
      3

      <input type="radio" name="rating-1" value="4">
      4

      <input type="radio" name="rating-1" value="5">
      5

JsFiddle

Body:
Since there is no line in HTML. I have achieved the same by adding an empty div with required background-color and height. And with position: absolute to place it where required.

.line {
  position: absolute;
  top: 25px;
  height: 5px;
  width: 100%;
  background-color: black;
}

P.S: I think you were trying to center the radios. For that I have changed display: block; for .radios2.

.radios2 {
  display: block;
  text-align: center;
}

.line {
  position: absolute;
  top: 25px;
  height: 5px;
  width: 100%;
  background-color: black;
}

.radios2 label + label {
    margin-left: 10px;
}

.radios2 input[type="radio"] {
    opacity: 0;
    /* hidden but still tabable */
    position: absolute;
}

.radios2 input[type="radio"] + span {
    display: block;
    line-height: 40px;
    height: 40px;
    width: 40px;
    border-radius: 50%;
    background: #eee;
    color: #555;
    -webkit-transform: scale(1);
    transform: scale(1);
}

.radios2 input[type="radio"]:not(:checked) + span:hover {
    cursor: pointer;
    -webkit-transform: scale(1.25);
    transform: scale(1.25);
    -webkit-transition: -webkit-transform 0.2s ease-in;
    transition: -webkit-transform 0.2s ease-in;
    transition: transform 0.2s ease-in;
    transition: transform 0.2s ease-in, -webkit-transform 0.2s ease-in;
}

.radios2 input[type="radio"]:checked + span {
    color: #D9E7FD;
    background-color: #4285F4;
}

.radios2 input[type="radio"]:focus + span {
    color: #fff;
}

label {
  display: inline-block;
}

<div class="feedback-option">
<div class="line"></div>
  <div class="radios2">
    <label>
      <input type="radio" name="rating-1" value="1">
      <span>1</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="2" />
      <span>2</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="3">
      <span>3</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="4">
      <span>4</span>
    </label>
    <label>
      <input type="radio" name="rating-1" value="5">
      <span>5</span>
    </label>
  </div>
</div>


问:
start and stop tomcat via command prompt
Im currently using tomcat 6.0.18.  I have installed tomcat server and set the CATALINA_HOME variable in the environment variables. Inside the tomcat installation location under the bin folder, there is no startup.bat or shutdown.bat file available. There are only two exe files: tomcat6.exe & tomcat6w.exe. I would like to know how to start the tomcat server via command prompt.

I tried executing the below command

```<code>C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe start
</code>```

The start command works fine. But I'm unable to stop the server using the command

```<code>C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe stop
</code>```

But the stop command does not stop the server. It only starts the tomcat server.

Both the commands 'tomcat6.exe start' & 'tomcat6.exe stop' starts the tomcat server. I would like to know what options should I use to stop the tomcat server via command prompt.

Any help on this is much appreciated. Thanks in Advance.

答: If tomcat server is 64 bit and system is 32 bit server wont start...Check the system type also when configuring</p>

Body:
Im currently using tomcat 6.0.18.  I have installed tomcat server and set the CATALINA_HOME variable in the environment variables. Inside the tomcat installation location under the bin folder, there is no startup.bat or shutdown.bat file available. There are only two exe files: tomcat6.exe & tomcat6w.exe. I would like to know how to start the tomcat server via command prompt.

I tried executing the below command

C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe start

The start command works fine. But I'm unable to stop the server using the command

C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe stop

But the stop command does not stop the server. It only starts the tomcat server.

Both the commands 'tomcat6.exe start' & 'tomcat6.exe stop' starts the tomcat server. I would like to know what options should I use to stop the tomcat server via command prompt.

Any help on this is much appreciated. Thanks in Advance.


问:
How to Limit the the Days that Could be Picked by Ionic 2 Datetime picker
I am trying to Make an app with Ionic 2, Angular2 and Typescript.
In this app i am compelled to use the Ionic DateTime picker :

```<code>    <ion-datetime displayFormat="MM DDD YYYY" min="{{startDate}}" pickerFormat="MM/DDD/YYYY" [(ngModel)]="Date" item-right></ion-datetime>
</code>```

So what i want is to limit the days that can be selected via the datetime picker, like I want the user to be able to select ONLY Fridays, or ONLY Mondays and Tuesdays.

I didn't really find anything in the Docs that can resolve this, so i am asking for help here, any ideas ?

答: You can specify dayValues for more see Ionic DateTime

Body:
I am trying to Make an app with Ionic 2, Angular2 and Typescript.
In this app i am compelled to use the Ionic DateTime picker :

    <ion-datetime displayFormat="MM DDD YYYY" min="{{startDate}}" pickerFormat="MM/DDD/YYYY" [(ngModel)]="Date" item-right></ion-datetime>

So what i want is to limit the days that can be selected via the datetime picker, like I want the user to be able to select ONLY Fridays, or ONLY Mondays and Tuesdays.

I didn't really find anything in the Docs that can resolve this, so i am asking for help here, any ideas ?


问:
$Env:ComputerName doesnt work with powershell Send-MailMessage in batch file
After a lot of errors and edits I got the Send-MailMessage to work through a command prompt.  Below iteration sends out the emails perfect.

```<code>powershell Send-MailMessage -From " `<user@domain>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
</code>```

However, this does not fetch the computername in the body. I have tried running this command in powershell directly and it works with the computername variable in body.

To get it to simply send out mails, I have already tried doing
  powershell -command "command" or powershell -command "{command} or
  powershell -command "& {command}" and so on and it doesnt even send
  out emails.

As I am now successful sending out emails, I need to have the Computername inside the body text.

答:
Use double quotes around the argument value to have variables contained expanded.

I.e.:

```<code>-Body "Some body with alert regarding Host: **$env:computername**. ..."
</code>```

Relevant reading.

Body:
After a lot of errors and edits I got the Send-MailMessage to work through a command prompt.  Below iteration sends out the emails perfect.

powershell Send-MailMessage -From " `<user@domain>`" -To " `<user@domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'

However, this does not fetch the computername in the body. I have tried running this command in powershell directly and it works with the computername variable in body.

To get it to simply send out mails, I have already tried doing
  powershell -command "command" or powershell -command "{command} or
  powershell -command "& {command}" and so on and it doesnt even send
  out emails.

As I am now successful sending out emails, I need to have the Computername inside the body text.

Body:
Use double quotes around the argument value to have variables contained expanded.

I.e.:

-Body "Some body with alert regarding Host: **$env:computername**. ..."

Relevant reading.


问:
How to hide all li except first two in one list, and third and fourth in another?
could you please tell me how to hide all li expect first two li ? in secnd case I want to hide all li expect show 3 and 4 li on buttn click
here is my code

https://jsbin.com/damolibule/edit?html,js,output

```<code>$(function() {
  $('#id_show12').click(function() {
    $('.show12').not(":nth-child(2)").css("display", "none");
  })

  $('#id_show34').click(function() {
    $('.show34').not(":nth-child(5)").css("display", "none");
  })
})
</code>```

Expected output: when first button click it shows 1 and 2 only. If user clicks on second button it show 3 and 4.

答:
edit button's id

```<code><button id="id_show12">show only one two li</button>
<button id="id_show34">show three four two li</button>
</code>```

Jquery code

```<code>$(function(){
  $('#id_show12').click(function(){
        $('.show12 li:nth-child(n+3)').css("display", "none");
    })
  $('#id_show34').click(function(){
       $('.show34 li:nth-child(-n+2), .show34 li:nth-child(n+5)').css("display", "none");
    })
})
</code>```

jsbin

Body:
could you please tell me how to hide all li expect first two li ? in secnd case I want to hide all li expect show 3 and 4 li on buttn click
here is my code

https://jsbin.com/damolibule/edit?html,js,output

$(function() {
  $('#id_show12').click(function() {
    $('.show12').not(":nth-child(2)").css("display", "none");
  })

  $('#id_show34').click(function() {
    $('.show34').not(":nth-child(5)").css("display", "none");
  })
})

Expected output: when first button click it shows 1 and 2 only. If user clicks on second button it show 3 and 4.

Body:
edit button's id

<button id="id_show12">show only one two li</button>
<button id="id_show34">show three four two li</button>

Jquery code

$(function(){
  $('#id_show12').click(function(){
        $('.show12 li:nth-child(n+3)').css("display", "none");
    })
  $('#id_show34').click(function(){
       $('.show34 li:nth-child(-n+2), .show34 li:nth-child(n+5)').css("display", "none");
    })
})

jsbin


问:
How to call web service or rest api from jaspersoft Studio Proffessional?
I want call web service or rest API from  jaspersoft Studio Proffessional proffesional, I tired to create JSON file/XML file adapter and putted http://api.population.io:80/1.0/countries in File or url section but it's not working.

Is there any other way to call web services or rest API from jasperstudio proffessional or I can add some web service adapter to jaspersoft studio proffesional?
In my jasper studio there is not adapter which connect to web service or rest api and use them as data source.
Note: my jasperstudio version is : 6.2

Thanks.

答: Use a local JSON file to check if it works. If not, the problem is in your JSON (or better in the expression you are using to get records out of it, or even the way you are mapping your fields).</p>


问:
Elasticsearch parent-child searching
My mappings:

```<code>"mappings": {
"role_permission_parent": {
  "properties": {
    "resourceURI": {
      "type": "string"
    },
    "resourceLabel": {
      "type": "string"
    }
  }
},
"role_permission_child": {
  "_parent": {
    "type": "role_permission_parent"
  },
  "properties": {
    "resourceURI": {
      "type": "string"
    },
    "resourceLabel": {
      "type": "string"
    }
  }
}
}
</code>```

I have over 100k document indexed by parents.

Question:
How can I permoform searching accross childs inside some parent?
That mean.. I want to find child with value "someting" in field "resourceLabale" inside "_parent":12345.

答:
You need to search for the parent with the id 12345 and have a has_child query that search for value: something

looks like this

```<code>bool:
  must:
    term: parentId: 12345
    has_child:
      term:
        something: value
</code>```

See the has_child query

Title: Elasticsearch parent-child searching

Body:
My mappings:

"mappings": {
"role_permission_parent": {
  "properties": {
    "resourceURI": {
      "type": "string"
    },
    "resourceLabel": {
      "type": "string"
    }
  }
},
"role_permission_child": {
  "_parent": {
    "type": "role_permission_parent"
  },
  "properties": {
    "resourceURI": {
      "type": "string"
    },
    "resourceLabel": {
      "type": "string"
    }
  }
}
}

I have over 100k document indexed by parents.

Question:
How can I permoform searching accross childs inside some parent?
That mean.. I want to find child with value "someting" in field "resourceLabale" inside "_parent":12345.

Body:
You need to search for the parent with the id 12345 and have a has_child query that search for value: something

looks like this

bool:
  must:
    term: parentId: 12345
    has_child:
      term:
        something: value

See the has_child query


问:
How to use Rxjs and document.querySelector('button') in angular2 cli project
Getting Error "Clicked NaN times".
What is the correct way to execute  Rxjs code below?</p>

```<code>import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/throttleTime';
export class AppComponent {
    count: number;
    title = 'app';
    @ViewChild('input') button: ElementRef;
    // @ViewChild('input1') button: ElementRef;
    constructor() {
    }

    ngAfterViewInit() {
        Observable.fromEvent(this.button.nativeElement, 'click')
            .throttleTime(1000)
            .scan(count => this.count + 1, 0)
            .subscribe(count => console.log(`Clicked ${count} times`));

    }
}
</code>```

答:
You have to initiate your count field value in your class:

```<code>export class AppComponent {
     count:number = 0;
     // ...
}
</code>```

Body:
Getting Error "Clicked NaN times".
What is the correct way to execute  Rxjs code below?

import { Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/scan';
import 'rxjs/add/operator/throttleTime';
export class AppComponent {
    count: number;
    title = 'app';
    @ViewChild('input') button: ElementRef;
    // @ViewChild('input1') button: ElementRef;
    constructor() {
    }

    ngAfterViewInit() {
        Observable.fromEvent(this.button.nativeElement, 'click')
            .throttleTime(1000)
            .scan(count => this.count + 1, 0)
            .subscribe(count => console.log(`Clicked ${count} times`));

    }
}

Body:
You have to initiate your count field value in your class:

export class AppComponent {
     count:number = 0;
     // ...
}


问:
Recalculate the hash of the keys in Dictionary
I'm working on an approach to have a collection that efficiently can search based on more than one property. The sample code of the approach:

```<code>class SampleCollection
{
    Dictionary<Sample, Sample> _dictItems;

    public SampleCollection()
    {
        _dictItems = new Dictionary<Sample, Sample>(new SampleEqualityComparer());
    }

    public Sample FindById(int id)
    {
        return _dictItems[new Sample(id, string.Empty)];
    }

    public Sample FindByName(string name)
    {
        return _dictItems[new Sample(-1, name)];
    }
}

class Sample
{
    public Sample(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public string ALotOfOtherProperties { get; set; }
}

class SampleEqualityComparer : IEqualityComparer<Sample>
{
    public bool Equals(Sample x, Sample y)
    {
        if (x.Id >= 0 && y.Id >= 0)
        {
            return x.Id == y.Id;
        }

        return x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase);
    }

    public int GetHashCode(Sample obj)
    {
        //try with only name now
        return obj.Name.GetHashCode();
        //return 0;
    }
}
</code>```

This approach works perfectly fine as long as the Name property is not modified. Understandably, the Hash value no longer matches the original item in the Dictionary when the Name is modified.

Is it possible to force the Dictionary to recalculate the hash of its keys or any other workaround if it is not possible directly.?

答:
It is really a performance hit when using a custom class as a key.  The handling can take a 10 times longer.

I suggest that you have a dictionary for name and one for id.

I recommend that you set your Name and Id setter to private like:public string Name { get; private set; }

```<code>class SampleCollection
{
    public SampleCollection()
    {
          NameLookup = new Dictionary<string, List<Sample>>();
          IdLookup = new Dictionary<int, Sample>();
    }
    private Dictionary<string, List<Sample>> NameLookup;
    private Dictionary<int, Sample> IdLookup;
    public void Add(Sample sample)
    {
       IdLookup.Add(sample.Id, Sample);
       List<Sample> list;
       if (!NameLookup.TryGetValue(sample.Name, out list))
          NameLookup.Add(sample.Name, list = new List<Sample>());
       list.Add(Sample);
    }
    public Sample FindById(int id)
    {
       Sample result;
       IdLookup.TryGetValue(id, out result);
       return result;
    }
    public IEnumerable<Sample> FindByName(string name)
    {
       List<Sample> list;
       if (NameLookup.TryGetValue(name, out list))
         foreach(var sample in list)
           yield return sample;
    }
}
</code>```

Body:
I'm working on an approach to have a collection that efficiently can search based on more than one property. The sample code of the approach:

class SampleCollection
{
    Dictionary<Sample, Sample> _dictItems;

    public SampleCollection()
    {
        _dictItems = new Dictionary<Sample, Sample>(new SampleEqualityComparer());
    }

    public Sample FindById(int id)
    {
        return _dictItems[new Sample(id, string.Empty)];
    }

    public Sample FindByName(string name)
    {
        return _dictItems[new Sample(-1, name)];
    }
}

class Sample
{
    public Sample(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public string ALotOfOtherProperties { get; set; }
}

class SampleEqualityComparer : IEqualityComparer<Sample>
{
    public bool Equals(Sample x, Sample y)
    {
        if (x.Id >= 0 && y.Id >= 0)
        {
            return x.Id == y.Id;
        }

        return x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase);
    }

    public int GetHashCode(Sample obj)
    {
        //try with only name now
        return obj.Name.GetHashCode();
        //return 0;
    }
}

This approach works perfectly fine as long as the Name property is not modified. Understandably, the Hash value no longer matches the original item in the Dictionary when the Name is modified.

Is it possible to force the Dictionary to recalculate the hash of its keys or any other workaround if it is not possible directly.?

Body:
It is really a performance hit when using a custom class as a key.  The handling can take a 10 times longer.

I suggest that you have a dictionary for name and one for id.

I recommend that you set your Name and Id setter to private like:public string Name { get; private set; }

class SampleCollection
{
    public SampleCollection()
    {
          NameLookup = new Dictionary<string, List<Sample>>();
          IdLookup = new Dictionary<int, Sample>();
    }
    private Dictionary<string, List<Sample>> NameLookup;
    private Dictionary<int, Sample> IdLookup;
    public void Add(Sample sample)
    {
       IdLookup.Add(sample.Id, Sample);
       List<Sample> list;
       if (!NameLookup.TryGetValue(sample.Name, out list))
          NameLookup.Add(sample.Name, list = new List<Sample>());
       list.Add(Sample);
    }
    public Sample FindById(int id)
    {
       Sample result;
       IdLookup.TryGetValue(id, out result);
       return result;
    }
    public IEnumerable<Sample> FindByName(string name)
    {
       List<Sample> list;
       if (NameLookup.TryGetValue(name, out list))
         foreach(var sample in list)
           yield return sample;
    }
}


答:
Why you don't use @media Rule on CSS?
For example

```<code>@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}

@media screen and (max-width: 480px) {
    body {
        background-color: red;
    }
}
</code>```

Now your style will changes based on screen width. For your case we could write like this

```<code>@media screen and (max-width: 600px) {
    carousel {
        width: 100%
    }
}
@media screen and (min-width: 600px) {
    carousel {
        <whatever you want>
    }
}
</code>```

You could write common attribute without @media Rule and write exclusive attribute like that.

Title: Making images responsive

Body:
I'm creating an image slider and when the screen gets to 600 or below I want the images to be 100% of the screen width. I have tried to use width: 100% and max: width: 600px thinking this would make them responsive. But now I realise that that just makes them 600px wide not 100% of the screen with a max width. How can I achieve this?

$(document).ready(function(){
  var image_width = $(".img_cont").width();
  var image_count = $(".carousel li").length;
  var carousel_width = image_width * image_count + image_width;
  var padding = $(".active img").height() /4;

  $(".carousel").css("width", carousel_width);
  $(".img_cont").css("paddingTop", padding);
  $(".active").css("paddingTop", 0);

  $(window).resize(function(){
    if($(window).width() <= 600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", 0);
        $(".active").css("paddingTop", 0);
      }else if($(window).width() < 1600){
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }else {
        var image_width = $(".img_cont").width();
        var image_count = $(".carousel li").length;
        var carousel_width = image_width * image_count + image_width;
        var padding = $(".active img").height() /4;

        $(".carousel").css("width", carousel_width);
        $(".img_cont").css("paddingTop", padding);
        $(".active").css("paddingTop", 0);
      }
      });
  });

*{
  padding: 0;
  margin: 0;
}

body{
  width: 100%;
  margin: 0;
  padding: 0;
}

.cont{
  position: relative;
  font-size: 0;/*removes white space*/
  margin: 60px auto;
  padding: 0;
/*   overflow: hidden; */
}

.carousel{
  padding: 0;
  list-style-type: none;
  height: auto;
  position: relative;
  left: 50%;
  -webkit-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -o-transform: translateX(-50%);
  transform: translateX(-50%);
  overflow: hidden;
}

.carousel li{
  float: left;
  background-color: pink;
}

#next{
  position: absolute;
  top: 45%;
  right: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  font-size: 0;
  z-index: 1;
}

#prev{
  position: absolute;
  top: 45%;
  left: 0;
  width: 40px;
  height: 40px;
  background-color: blue;
  z-index: 1;
}

.img_cont img{
  width: 100%;
  max-width: 600px;
  height: auto;
  max-height:600px;
}

.active img{
  width: 100%;
  max-width: 1200px;
  height: auto;
  padding: 0;
}

@media screen and (max-width: 1600px){
  .img_cont img{
    width: 100%;
    max-width: 500px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 1000px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1200px){
  .img_cont img{
    width: 100%;
    max-width: 400px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 800px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 1000px){
  .img_cont img{
    width: 100%;
    max-width: 300px;
    height: auto;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

@media screen and (max-width: 600px){

  img_cont{
    width: 100%;
    max-width: none;
  }

  .img_cont img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }

  .active img{
    width: 100%;
    max-width: 600px;
    height: auto;
    padding: 0;
  }
}

Body:
Why you don't use @media Rule on CSS?
For example

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}

@media screen and (max-width: 480px) {
    body {
        background-color: red;
    }
}

Now your style will changes based on screen width. For your case we could write like this

@media screen and (max-width: 600px) {
    carousel {
        width: 100%
    }
}
@media screen and (min-width: 600px) {
    carousel {
        <whatever you want>
    }
}

You could write common attribute without @media Rule and write exclusive attribute like that.


问:
How to calculate means and std at once in pandas?
For example, we have data like :

```<code>>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3
</code>```

I want to get a result like

```<code>   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0
</code>```

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

答:
you can apply agg functon for calculate mean

```<code>df = df.groupby('name').agg({'score': ['mean', 'std']})
</code>```

then you will get multiindex dataFrame, to extract level do following.

```<code>df = df.xs('score', axis=1, drop_level=True)
    # 'score' : key on which to get cross section
    # axis=1 : get cross section of column
    # drop_level=True : returns cross section without the multilevel index
</code>```

As you given output do following:

```<code>df = df.reset_index('name')
</code>```

Then rename

```<code>df.rename(columns={"mean":"score"}, inplace=True)
</code>```

output:

```<code>   name       score      std
0  jack   99.000000  0.00000
1   tom   99.666667  0.57735
2  tony  100.000000  0.00000
</code>```

Body:
For example, we have data like :

>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3

I want to get a result like

   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

Body:
you can apply agg functon for calculate mean

df = df.groupby('name').agg({'score': ['mean', 'std']})

then you will get multiindex dataFrame, to extract level do following.

df = df.xs('score', axis=1, drop_level=True)
    # 'score' : key on which to get cross section
    # axis=1 : get cross section of column
    # drop_level=True : returns cross section without the multilevel index

As you given output do following:

df = df.reset_index('name')

Then rename

df.rename(columns={"mean":"score"}, inplace=True)

output:

   name       score      std
0  jack   99.000000  0.00000
1   tom   99.666667  0.57735
2  tony  100.000000  0.00000


问:
Pentaho install error: Error running initdb.exe -U postgres -E UTF8 -D
I am new to Pentaho, I just download a Pentaho Business Analytics 64 bit version(My os is Windows 64bit). When I install, I'm getting an "Error running initdb.exe -U postgres -E UTF8 -D C:/PENTAH~1/POSTGR~1/data" message. Does anybody know how to solve this problem?Thanks!</p>

答:
Check if Postgres is already installed in your system with port 5432, using netstat -a

This error most likely appears when there's problem while installing Postgres. Go to "My Computer" right-click "properties", choose "Advanced System Settings",  "Environmental Variables". In "system variables" for the variable ComSpec remove the semicolon after cmd.exe. This worked for me and allowed me to install Postgres.


问:
Rails: Advantages of storing session in database?
I'm just wondering why storing session in database? Is there any advantage to storing session in database?</p>

答:
There are at least three reasons I can think of. If you save the session in the DB you can:

access it easily on any Rails instance you execute. So if you have more than one machine, you don't have to worry about distributing the session data.

You don't have the 4kb session limit session that only aplies when using cookie session store. Although you are not supposed to use the session to store objects, you may that functionality some day.

When using and RDBM (and not Memcached, or any other non persisted storage) you don't have to worry about loosing session data.


问:
Custom button with curved progress bar in Android
I need to design something like this, kindly help me.
Thanks in advance.

Looking for android design

Any help will be appreciated.

答:
You can create a component that implements onTouchEvent. In the onTouchEvent you detect the location and direction of the touch, and you change the rotational position of the graphic, as well as the volume, accordingly. onTouchEvent is documented in the Android API docs under "View".

Ref link

Write below code into your touch event.

```<code>switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        // reset the touched quadrants
        for (int i = 0; i < quadrantTouched.length; i++) {
            quadrantTouched[i] = false;
        }
        allowRotating = false;
        startAngle = getAngle(event.getX(), event.getY());
        break;
    case MotionEvent.ACTION_MOVE:
        double currentAngle = getAngle(event.getX(), event.getY());
        rotateDialer((float) (startAngle - currentAngle));
        startAngle = currentAngle;
        break;
    case MotionEvent.ACTION_UP:
        allowRotating = true;
        break;
}

// set the touched quadrant to true
quadrantTouched[getQuadrant(event.getX() - (dialerWidth / 2), dialerHeight - event.getY() - (dialerHeight / 2))] = true;
detector.onTouchEvent(event);
return true;
</code>```

And use below link for more reference.

Custom Button

Body:
You can create a component that implements onTouchEvent. In the onTouchEvent you detect the location and direction of the touch, and you change the rotational position of the graphic, as well as the volume, accordingly. onTouchEvent is documented in the Android API docs under "View".

Ref link

Write below code into your touch event.

switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        // reset the touched quadrants
        for (int i = 0; i < quadrantTouched.length; i++) {
            quadrantTouched[i] = false;
        }
        allowRotating = false;
        startAngle = getAngle(event.getX(), event.getY());
        break;
    case MotionEvent.ACTION_MOVE:
        double currentAngle = getAngle(event.getX(), event.getY());
        rotateDialer((float) (startAngle - currentAngle));
        startAngle = currentAngle;
        break;
    case MotionEvent.ACTION_UP:
        allowRotating = true;
        break;
}

// set the touched quadrant to true
quadrantTouched[getQuadrant(event.getX() - (dialerWidth / 2), dialerHeight - event.getY() - (dialerHeight / 2))] = true;
detector.onTouchEvent(event);
return true;

And use below link for more reference.

Custom Button


问:
Possible to use both "or" and "and" to select rows based on column values in df?
I know how to select rows in a dataframe based on the values of two columns (using code from accepted answer on this question: Conditionally Remove Dataframe Rows with R)

My dataframe looks like this (simplified):

```<code>Date        Afd  Count
2012-03-23  12   0
2012-03-23  16   10
2012-03-23  17   12
2012-03-27  12   3
2012-03-27  16   9
2012-03-27  13   7
2012-03-27  22   5
2012-04-05  12   11
2012-04-05  23   8
</code>```

Now I use this code:

```<code>df <- df[!(df$Afd=="12" & df$Date=="2012-03-23"),]
</code>```

But I also want to drop another Afd and another Date. Following this logic:
if Afd = 12 or 16, and Date = 2012-03-23 or 2012-03-27, then delete row.

Do I have to repeat this line 4 times with the different combinations or is there a better solution? (I suspect the latter)

答:
You can add or statements with | or use %in%

```<code>df <- subset(df, !(Afd %in% c("12", "16") &
                   Date %in% as.Date(c("2012-03-23", "2012-03-27"))
                  )
            )
</code>```

Body:
I know how to select rows in a dataframe based on the values of two columns (using code from accepted answer on this question: Conditionally Remove Dataframe Rows with R)

My dataframe looks like this (simplified):

Date        Afd  Count
2012-03-23  12   0
2012-03-23  16   10
2012-03-23  17   12
2012-03-27  12   3
2012-03-27  16   9
2012-03-27  13   7
2012-03-27  22   5
2012-04-05  12   11
2012-04-05  23   8

Now I use this code:

df <- df[!(df$Afd=="12" & df$Date=="2012-03-23"),]

But I also want to drop another Afd and another Date. Following this logic:
if Afd = 12 or 16, and Date = 2012-03-23 or 2012-03-27, then delete row.

Do I have to repeat this line 4 times with the different combinations or is there a better solution? (I suspect the latter)

Body:
You can add or statements with | or use %in%

df <- subset(df, !(Afd %in% c("12", "16") &
                   Date %in% as.Date(c("2012-03-23", "2012-03-27"))
                  )
            )


问:
Identify Week Number, Month Number, Year from DatePicker control in VBA userform
I have been trying to make my user form work by getting codes everywhere. I don't have any experience in VBA so the code that I have are patches from different sources.

I have a datepicker control in my user form and i'd like to get the corresponding week number, month number and year based on the date that is chosen from the datepicker control box and populate the corresponding textboxes for each

datepicker and textbox dependencies.

答:
To get the week number use the below. The third and fourth arguments allow you to dictate the first day/first week of the year.

```<code>TextBoxWeek.Value =  DatePart("ww", TextBoxDatePicker.Value, vbMonday, vbFirstJan1 )
</code>```

Month:

```<code>TextBoxMonth.Value = format(TextBoxDatePicker.value,"mm")
</code>```

Year: (you can also use "yy" to get the shorthand date eg. '17' rather than '2017')

```<code>TextBoxYear.Value = format(TextBoxDatePicker.value, "yyyy")
</code>```

Body:
To get the week number use the below. The third and fourth arguments allow you to dictate the first day/first week of the year.

TextBoxWeek.Value =  DatePart("ww", TextBoxDatePicker.Value, vbMonday, vbFirstJan1 )

Month:

TextBoxMonth.Value = format(TextBoxDatePicker.value,"mm")

Year: (you can also use "yy" to get the shorthand date eg. '17' rather than '2017')

TextBoxYear.Value = format(TextBoxDatePicker.value, "yyyy")