问:
Remove Duplicate ids from select query
I have the following table

```<code>ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50
</code>```

I would like to delete duplicate id from this table. I would like to get below

```<code>ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50
</code>```

I already used DISTINCT keyword in my select query likes this

```<code>SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;
</code>```

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

答:
```<code>CREATE TABLE #Table1
    ([ID] int, [NAME] varchar(3), [POINT] int)
;

INSERT INTO #Table1
    ([ID], [NAME], [POINT])
VALUES
    (100, 'AAA', 100),
    (100, 'AAA', 150),
    (100, 'AAA', 70),
    (200, 'DDD', 100),
    (200, 'DDD', 65),
    (300, 'FFF', 50)

SELECT ID,NAME,POINT FROM (SELECT* , ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID,NAME ) AS RN FROM #TABLE1)A
WHERE RN=1
</code>```

output

```<code>ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50
</code>```

Title: Remove Duplicate ids from select query

Body:
I have the following table

ID     NAME    POINT
100    AAA     100
100    AAA     150
100    AAA     70
200    DDD     100
200    DDD     65
300    FFF     50

I would like to delete duplicate id from this table. I would like to get below

ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50

I already used DISTINCT keyword in my select query likes this

SELECT DISTINCT ID,NAME,POINT FROM Tab ORDER BY ID;

It is not ok. I just need one unique id per record.So How to remove duplicate ids from select query? My condition is If all records are the same then take the first record.

Body:
CREATE TABLE #Table1
    ([ID] int, [NAME] varchar(3), [POINT] int)
;

INSERT INTO #Table1
    ([ID], [NAME], [POINT])
VALUES
    (100, 'AAA', 100),
    (100, 'AAA', 150),
    (100, 'AAA', 70),
    (200, 'DDD', 100),
    (200, 'DDD', 65),
    (300, 'FFF', 50)

SELECT ID,NAME,POINT FROM (SELECT* , ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID,NAME ) AS RN FROM #TABLE1)A
WHERE RN=1

output

ID     NAME    POINT
100    AAA     100
200    DDD     100
300    FFF     50


来源: stackexchange

问:
Copy selected data from one worksheet to another with Excel VBA
I am trying to copy selected data from one worksheet to another with Excel VBA. As you can see in my pictures when the value is a 0, the value of the test_Point should be written in another worksheet. So I want to copy the test_Point value of each cell where the value is 0.

Source data on Sheet1:

Expected result to be put on Sheet2:

答:
I have worksheet one named "aaaa" and second one named "bbbb".

In "bbbb" I put function in one cell:

```<code>=IF(aaaa!A1<10; "dog"; "cat")
</code>```

This will look in first one in cell A1 if the value is less than 10 and then display some text in cell that is second worksheet.

You need to change the condition in function so that will give you result that you want.

Is this what you were looking for?

Here are some links that also might be helpful regarding accessing values in VBA

https://chartio.com/resources/tutorials/how-to-get-values-from-another-sheet-in-excel-using-vba/

https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/

ContentLicense: CC BY-SA 3.0

Body:
I have worksheet one named "aaaa" and second one named "bbbb".

In "bbbb" I put function in one cell:

=IF(aaaa!A1<10; "dog"; "cat")

This will look in first one in cell A1 if the value is less than 10 and then display some text in cell that is second worksheet.

You need to change the condition in function so that will give you result that you want.

Is this what you were looking for?

Here are some links that also might be helpful regarding accessing values in VBA

https://chartio.com/resources/tutorials/how-to-get-values-from-another-sheet-in-excel-using-vba/

https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/


问:
Difference between classes in Java vs JavaScript?
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

```<code>const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();
</code>```

The MyClass it's calling has this code:

```<code>class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;
</code>```

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

答:
Class member-variable in JavaScript can be accessed using this.member-variable syntax.

The correct way to solve the problem is following:

Main.js

```<code>const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");
myclass.repeatString();
</code>```

MyClass.js

```<code>class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(this.myString);
    }
}

module.exports = MyClass;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();

The MyClass it's calling has this code:

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

Body:
Class member-variable in JavaScript can be accessed using this.member-variable syntax.

The correct way to solve the problem is following:

Main.js

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");
myclass.repeatString();

MyClass.js

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(this.myString);
    }
}

module.exports = MyClass;


问:
Is there a "nice" way to advance a pointer to a struct by one byte?
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

```<code>#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}
</code>```

The compiler reports an error on the "nice" part:

```<code>% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^
</code>```

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?

答: Obviously type casting such as (uint8_t*) doesn't result in an lvalue. Since your code is in C++, you may use this casting (uint8_t*&).

Body:
I have a pointer to a structure that I would like to move over an
address range, byte-by-byte. I have an approach that's working, but
it's ugly in my eyes. Unfortunately, the "nice" way doesn't work. Here's a minimum example:

#include <stdint.h>

typedef struct {
    uint32_t a;
    uint32_t b;
} s_t;

int main( int argc, char** argv )
{
    uint32_t address = 17;
    s_t* ps = (s_t*) address;

    // ugly
    uint8_t* gna = (uint8_t*) ps;
    ++gna;
    ps = (s_t*) gna;

    // nice
    ++((uint8_t*) ps);
}

The compiler reports an error on the "nice" part:

% gcc test.c -o test.bin
test.c: In function 'main':
test.c:17:5: error: lvalue required as increment operand
     ++((uint8_t*) ps);
     ^

I understand the error, but I thought casting to an uint8_t* would
create an lvalue. Obviously, I'm wrong.

Is there a way to make it better?


问:
How to stop the Visibility of the ProgressBar inside LinearLayout
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

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

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}
</code>```

Here is my activity.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

This is my fragment.java

```<code>    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}
</code>```

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

答:
Use</p>

```<code>linearLayout.setVisibility(LinearLayout.GONE);
</code>```

Body:
I have an activity which have 5-6 fragments in it and i am trying to show a progress bar whenever a fragment loads its data from REST api.  I am able to show the progress bar but not able to stop visibility of it. whenever i am trying to stop the visibility of it, Progress Bar doesn't come up at all.   Here is my Activity.java

public class MainActivity extends AppCompatActivity {

    private Toolbar   toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    public LinearLayout linearLayout;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView imageTitle = (ImageView) toolbar.findViewById(R.id.appbar_image);
           setSupportActionBar(toolbar);
           getSupportActionBar().setDisplayShowTitleEnabled(false);
           getSupportActionBar().setDisplayHomeAsUpEnabled(false);
           linearLayout = (LinearLayout)findViewById(R.id.linlaHeaderProgress);
           linearLayout.setVisibility(View.VISIBLE);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

       }

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new HomeFragment(), "Home News");
        adapter.addFragment(new BusinessFragment(),"Business News");
        adapter.addFragment(new PoliticsFragment(),"Politics News");
        adapter.addFragment(new TechnologyFragment(),"Technology News");
        adapter.addFragment(new SportsFragment(),"Sports News");
        adapter.addFragment(new EntertainmentFragment(),"Entertainment News");
        adapter.addFragment(new HealthFragment(),"Health News");
        adapter.addFragment(new WorldFragment(),"World News");
        adapter.addFragment(new MoreFragment(),"More News");

        viewPager.setAdapter(adapter);

}

private void stopBar() {

    linearLayout.setVisibility(View.GONE);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
     private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
    super(manager);
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFragment(Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);

}

     @Override
    public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
   }
 }
}

Here is my activity.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/appbar_image"
                android:foregroundGravity="center"
                android:scaleType="fitCenter"
                android:src="@drawable/splash"

                />

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Widget.AppCompat.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:theme="@style/CircularProgress">
        </ProgressBar>

    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

This is my fragment.java

    public class HomeFragment extends android.support.v4.app.Fragment {

    private RecyclerView recyclerView;
    private ArrayList<HomeNews> data;
    private HomeNewsAdapter adapter;
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = (RecyclerView)rootView.findViewById(R.id.rv_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);

        loadJSON();

        return rootView;

    }

    private void loadJSON() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.vaonlinenews.com/news_api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<HomeResponse> call = request.getHomeJSON();

        call.enqueue(new Callback<HomeResponse>() {
            @Override
            public void onResponse(Call<HomeResponse> call, Response<HomeResponse> response) {

                HomeResponse homeResponse = response.body();
                data = new ArrayList<>(Arrays.asList(homeResponse.getArticles()));
                adapter = new HomeNewsAdapter(getContext(),data);
                recyclerView.setAdapter(adapter);

            }

            @Override
            public void onFailure(Call<HomeResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
                Error_Dialog alert = new Error_Dialog();
                alert.showDialog(getActivity()," Please Check Your Internet Connection");

            }
        });

    }

}

Please suggest me where i should place the code to stop the visibility of progress bar after the fragments gets loaded.

Body:
Use

linearLayout.setVisibility(LinearLayout.GONE);


问:
Prefix for testing methods in Unit: "test" vs "should"
It is a common practice to prefix the tests method names in JUnit with "test". But in the last few years, some people changed this to the prefix "should".

If I want to test the customer creation in a database, I would normally name the method "testCustomerCreation". However, some people would name "shouldCreateCustomer".

This is a lot of personal taste when I am the only person in the project or when everyone else in the project agrees with me. But when/where this is not the case, some divergences or inconsistent mixes starts to shows up.

I readed somewhere an article of a guy that named his methods like "testShouldCreateCustomer", and for this reason he decided to drop the "test" prefix. But in fact he wasn't prefixing with "test", he was using "testShould" and changed to "should". Obviously, this did not convinced me.

I am personally strongly inclined to stick to "test" prefix because the methods names normally starts with verbs in the infinitive form ("get", "set", "add", "remove", "clear", "send", "receive", "open", "close", "read", "write", "create", "list", "pop", "print", etc, so is "test"). So, prefixing a method name with "should" makes it sound really very strange for me, looks wrong.

So, what is the real good reason to use "should" instead of "test"? What are the great advantages and disadvantages?

答: Consistency is more important than being correct on naming issues. If there is any question on a project, the technical member responsible for the project should outline the coding practices formally so that issues like this don't kill valuable project time.</p>

ContentLicense: CC BY-SA 2.5


问:
UIView borderWidth not visible
I want to have a rounded view with a black center and a colored border. When I set up my view like this:

```<code>myView.backgroundColor = UIColor.red
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3
</code>```

I get just a red round. But when I go to the Debug View Hierarchy, I see, that myView has a white border. Madness! What do I make wrong?

iPhone:
and Debug View Hierarchy:

答:
I have tested it, working fine in my simulator</p>

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    myView.layer.cornerRadius = myView.frame.size.width/2 //first make your view as rounded.

    myView.layer.backgroundColor = UIColor.red.cgColor //convert into cgColor
    myView.layer.borderColor = UIColor.white.cgColor
    myView.layer.borderWidth = 3
}
</code>```

Title: UIView borderWidth not visible

Body:
I want to have a rounded view with a black center and a colored border. When I set up my view like this:

myView.backgroundColor = UIColor.red
myView.layer.borderColor = UIColor.white.cgColor
myView.layer.borderWidth = 3

I get just a red round. But when I go to the Debug View Hierarchy, I see, that myView has a white border. Madness! What do I make wrong?

iPhone:
and Debug View Hierarchy:

Body:
I have tested it, working fine in my simulator

override func viewDidLoad() {
    super.viewDidLoad()

    myView.layer.cornerRadius = myView.frame.size.width/2 //first make your view as rounded.

    myView.layer.backgroundColor = UIColor.red.cgColor //convert into cgColor
    myView.layer.borderColor = UIColor.white.cgColor
    myView.layer.borderWidth = 3
}


问:
how to insert multiple row in form method using for loop in asp.net mvc
i am written the code for CREATE Operation in view which will insert multiple of rows in database using form-tag with for-loop. when click on Create button it will save only one row so i want that when i click on button no.of row should be created.

here code for View..

```<code>@model CarParking.Models.Area

@for (int i = 1; i <= Model.NoOfParkingPlaces; i++)
{
    using (Html.BeginForm("Create", "ParkingPlace", FormMethod.Post))
    {
        <label>AreaID:</label>
        <input id="AreaID" name="AreaID" type="text" value="@Model.AreaID" />

        <label for="Parking_IDs">Parking IDs</label>
        <input type="text" value="P.Id: @i" name="PlaceId" />

        <input type="submit" value="Create" />
    }
}
</code>```

here code for Controller...

```<code>public ActionResult Create(string areaName)
    {
        Area area = db.Areas.SingleOrDefault(x => x.ParkingPlaceName == areaName);
        return View(area);
    }

    [HttpPost]
    public ActionResult Create([Bind(Include = "ParkID,PlaceId,CarID,AreaID")] ParkingPlace parkingPlace)
    {
        if (ModelState.IsValid)
        {
            db.ParkingPlaces.Add(parkingPlace);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(parkingPlace);
    }
</code>```

Here some images how my View looksenter image description here

答:
Are you saying you want to post ALL the forms on the page at once?

If so - it doesn't work like that... One option would be to use javascript to AJAX post them all, but the correct way to do it is to use one form, with each of the ParkingPlaces in it.

This article goes through it in detail: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

```<code>@for( int i = 0; i < Model.NoOfParkingPlaces; ++i)
{
    @Html.EditorFor(m => m.ParkingPlaces[i].AreaId)
    @Html.EditorFor(m => m.ParkingPlaces[i].Id)
    ... etc
}
</code>```

and your action parameters become;

```<code>public ActionResult Create(IEnumerable<ParkingPlace> ParkingPlaces)
{
</code>```

Body:
i am written the code for CREATE Operation in view which will insert multiple of rows in database using form-tag with for-loop. when click on Create button it will save only one row so i want that when i click on button no.of row should be created.

here code for View..

@model CarParking.Models.Area

@for (int i = 1; i <= Model.NoOfParkingPlaces; i++)
{
    using (Html.BeginForm("Create", "ParkingPlace", FormMethod.Post))
    {
        AreaID:
        <input id="AreaID" name="AreaID" type="text" value="@Model.AreaID" />

        Parking IDs
        <input type="text" value="P.Id: @i" name="PlaceId" />

        <input type="submit" value="Create" />
    }
}

here code for Controller...

public ActionResult Create(string areaName)
    {
        Area area = db.Areas.SingleOrDefault(x => x.ParkingPlaceName == areaName);
        return View(area);
    }

    [HttpPost]
    public ActionResult Create([Bind(Include = "ParkID,PlaceId,CarID,AreaID")] ParkingPlace parkingPlace)
    {
        if (ModelState.IsValid)
        {
            db.ParkingPlaces.Add(parkingPlace);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(parkingPlace);
    }

Here some images how my View looksenter image description here

Body:
Are you saying you want to post ALL the forms on the page at once?

If so - it doesn't work like that... One option would be to use javascript to AJAX post them all, but the correct way to do it is to use one form, with each of the ParkingPlaces in it.

This article goes through it in detail: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

@for( int i = 0; i < Model.NoOfParkingPlaces; ++i)
{
    @Html.EditorFor(m => m.ParkingPlaces[i].AreaId)
    @Html.EditorFor(m => m.ParkingPlaces[i].Id)
    ... etc
}

and your action parameters become;

public ActionResult Create(IEnumerable<ParkingPlace> ParkingPlaces)
{


问:
Alternate signals for test bench without manually typing out all times in iverilog
I am writing a test bench that I want to be able to have signals go high and low in a certain pattern (something like this):
Currently I manually type out what I want each time to be like this:

```<code>module TestExample;
reg a, b, c;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end
endmodule
</code>```

The problem with this is when I get more signals (lets say a-z instead of a-b) it will take a really long time to manually type out each time and the associated value.  Because of this I am wondering if there is a way I can automate the signals.  For example if I could say switch your state every 10 u-seconds for a, every 20 u-seconds for b, and every 30 u-seconds for c?

答:
As Greg says...</p>

```<code>module TestExample;
wire a, b, c, d ...
integer i;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);
    for (i = 0; i < 1<<26; i=i+1)
        #10;
    $stop;
end

assign a = i[0], b = i[1], c = i[2], d = i[3] ...

endmodule
</code>```

Body:
I am writing a test bench that I want to be able to have signals go high and low in a certain pattern (something like this):
Currently I manually type out what I want each time to be like this:

module TestExample;
reg a, b, c;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);

    # 0 a=0; b=0; c=0;
    # 10 a=1; b=0; c=0;
    # 20 a=0; b=1; c=0;
    # 30 a=1; b=1; c=0;
    # 40 a=0; b=0; c=1;
    # 50 a=1; b=0; c=1;
    # 60 a=0; b=1; c=1;
    # 70 a=1; b=1; c=1;
    # 80 a=0; b=0; c=0;

    # 90 $stop;
end
endmodule

The problem with this is when I get more signals (lets say a-z instead of a-b) it will take a really long time to manually type out each time and the associated value.  Because of this I am wondering if there is a way I can automate the signals.  For example if I could say switch your state every 10 u-seconds for a, every 20 u-seconds for b, and every 30 u-seconds for c?

Body:
As Greg says...

module TestExample;
wire a, b, c, d ...
integer i;

initial begin
    $dumpfile("test.vcd");
    $dumpvars(0, TestExample);
    for (i = 0; i < 1<<26; i=i+1)
        #10;
    $stop;
end

assign a = i[0], b = i[1], c = i[2], d = i[3] ...

endmodule


问:
Werkzeug version view/change on debian/ubuntu odoo 9
How view current version of werkzeug on debian / ubuntu and install other version from downloads directory?

Any example with terminal?

答:
To view all installed python module version you can use pip freeze

For Werkzeug

You should use virtualenv, and with it you can install your desired version of any python module


问:
Is there a way to "fail fast" for junit with the maven surefire plugin?
I'm currently working on a java project using maven.  We use the maven surefire plugin to run our junit suite as part of the build process.

Our test suite is rapidly growing, in both coverage and execution time.  The execution time is very frustrating  and time consuming when you end up waiting ten minutes to find out that a test failed in the first minute of testing.

I would like to find a way to make the build process fail upon the first error/failure in the test suite.  I know that this is possible for other build tools, but I have been unable to find a way to do this with maven surefire.

I know that there is an unresolved ticket for this functionality in the surefire jira, but I'm hoping that there is an existing solution out there for this.

答:
A few ways to speed it up if not exactly what you need:

If it's a multi module build, add
--fail-fast to the command line to drop out after the first module.

Look into failsafe to move long
running integration tests onto a
different phase of the lifecycle.

Look into a profile based solution for fast and slow tests -
Is there a way to tell surefire to skip tests in a certain package?.


问:
How to get SUM of a column in PDO query
I am trying to get Summation of a column from my database table. But I get just 0.00. My codes are:

```<code>$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];
</code>```

It supposed to echo 306700.80. I've checked the query. It works fine in Database but not in my PHP script. What's wrong with it?

答:
OK, the problem was with my PDO code. I supposed to write $total_income_query instead of $stmt. The code should look like this...</p>

```<code>$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$total_income_query->bindParam(':startDate',$startDate);
$total_income_query->bindParam(':endDate',$endDate);
$total_income_query->execute();

$total = $total_income_query->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];
</code>```

Title: How to get SUM of a column in PDO query

Body:
I am trying to get Summation of a column from my database table. But I get just 0.00. My codes are:

$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();

$total = $stmt->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];

It supposed to echo 306700.80. I've checked the query. It works fine in Database but not in my PHP script. What's wrong with it?

Body:
OK, the problem was with my PDO code. I supposed to write $total_income_query instead of $stmt. The code should look like this...

$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");

$total_income_query->bindParam(':startDate',$startDate);
$total_income_query->bindParam(':endDate',$endDate);
$total_income_query->execute();

$total = $total_income_query->fetch(PDO::FETCH_NUM);

echo $total_income = $total[0];


问:
How to display working digital clock using React
I want to render digital clock on the browser , i don't know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.</p>

```<code><!DOCTYPE html>
    <html>
    <head>
        <title>My First App</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    </head>
    <body>
    <div id="react-app"></div>
    <div id="clock-box"></div>

    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

    <script type="text/jsx">

    class StoryBox extends React.Component{
            render(){
                return(<div> Hello World </div> );
            }
        }
    var target= document.getElementById('react-app');
    var clockTarget=document.getElementById('clock-box');
    ReactDOM.render(<StoryBox/>,target)

    class ClockFunction extends React.Component{
        render(){
            return(<div>
                <h1>Digital Clock</h1>
                <h2>
                {
                    new Date().toLocaleTimeString()
                    }
                </h2>
            </div>) ;
        }
    }

    ReactDOM.render(<ClockFunction />,clockTarget);

    </script>

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

答:
```<code>class ClockFunction extends React.Component{
    //setInterval and setState go in component Did mount
    componentDidMount (){
    this.setState({time : (new Date()).getTime()}
    // update every second
    this.tick = setInterval( () => this.setState(time : this.state.time + 1000, 1000)
    }

    //use state to display time in render function
    render(){
        return(<div>
            <h1>Digital Clock</h1>
            <h2>
            {
                this.state.time
            }
            </h2>
        </div>) ;
    }
}
</code>```

Body:
I want to render digital clock on the browser , i don't know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.

<!DOCTYPE html>

        <title>My First App</title>


问:
Check if file is already open
I need to write a custom batch File renamer. I've got the bulk of it done except I can't figure out how to check if a file is already open. I'm just using the java.io.File package and there is a canWrite() method but that doesn't seem to test if the file is in use by another program. Any ideas on how I can make this work?

答:
On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using

fileIsLocked = !file.renameTo(file)

most useful, as it avoids false positives when processing write protected (or readonly) files.

Title: Check if file is already open


问:
Configure ASP.NET application to use two authentication methods?
I am new to ASP.NET development and moreover I am only extending an existing application which i did not create.

I have a working ASP.NET application which uses "Forms authentication" throughout all its pages. I have added a new webservice in a subfolder "webservices\Dummy.asmx". This webservice works fine but because it should be called by an external application which can't authenticate through a form, i need to enable "Integrated Windows Authentication (Basic Authentication or Digest Authentication)" ONLY for the subfolder "webservices".

I tried to configure it in IIS but it did not work.
So that i can set a different authentication method i have to create the folder "webservices" as an "Application". But if i do so then my function stops working with the error "Could not create type 'Dummy'."

Is it possible to have one web application and to authentication methods ?
If yes how is it configured in IIS ?

Or what would be the better way if i need ONLY one page (webservice) to use a different authentication then the rest of my application.

Thank you in advance for any information.

Bye

PS: I use Windows 2008 Server and the app runs on .NET Framwork 2.0

答:
I tried to configure it in IIS but it
  did not work. So that i can set a
  different authentication method i have
  to create the folder "webservices" as
  an "Application". But if i do so then
  my function stops working with the
  error "Could not create type 'Dummy'."

This is the correct way. Can you explain the problem you are having here ? What is dummy ?

Mixing Forms and Windows Security in
  ASP.NET
  http://msdn.microsoft.com/en-us/library/ms972958.aspx


答:
For this you're going to need a few things:

a setInterval to update the time

a variable in the component's state for keeping track of the time

a safe way of adding and removing the setInterval when the component mounts and unmounts respectively

This component will do all of those things:

```<code>class ClockFunction extends React.Component {

    constructor() {
        super();
        this.state = { time: new Date() }; // initialise the state
    }

    componentDidMount() { // create the interval once component is mounted
        this.update = setInterval(() => {
            this.setState({ time: new Date() });
        }, 1 * 1000); // every 1 seconds
    }

    componentWillUnmount() { // delete the interval just before component is removed
        clearInterval(this.update);
    }

    render() {
        const { time } = this.state; // retrieve the time from state

        return (<div>
            <h1>Digital Clock</h1>
            <h2>
                {/* print the string prettily */}
                {time.toLocaleTimeString()}
            </h2>
        </div>);
    }
}
</code>```

Title: How to display working digital clock using React

Body:
For this you're going to need a few things:

a setInterval to update the time

a variable in the component's state for keeping track of the time

a safe way of adding and removing the setInterval when the component mounts and unmounts respectively

This component will do all of those things:

class ClockFunction extends React.Component {

    constructor() {
        super();
        this.state = { time: new Date() }; // initialise the state
    }

    componentDidMount() { // create the interval once component is mounted
        this.update = setInterval(() => {
            this.setState({ time: new Date() });
        }, 1 * 1000); // every 1 seconds
    }

    componentWillUnmount() { // delete the interval just before component is removed
        clearInterval(this.update);
    }

    render() {
        const { time } = this.state; // retrieve the time from state

        return (<div>
            <h1>Digital Clock</h1>
            <h2>
                {/* print the string prettily */}
                {time.toLocaleTimeString()}
            </h2>
        </div>);
    }
}


问:
Select all checkbox issue
In HTML, when I click on checkbox from the list it adds class to its parent li, but when I need to select all checkbox when any one of the lists is already selected then it mismatches.

HTML:

```<code><div class="row lml-dashboard">
                        <div class="col-xs-12 col-sm-3 col-md-3 left-section">
                            <div class="panel panel-default">
                                <!-- Default panel contents -->
                                <div class="panel-heading"><input type="checkbox" id="select_all">
                                    <select class="select-admin">
                                        <option>7 Operators</option>
                                        <option>7 Trainers</option>
                                    </select>
                                </div>

                                <!-- List group -->
                                <ul class="list-group member-list">
                                    <li class="list-group-item checked">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]" checked="checked">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Kimberly Palmer
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Christopher Henry
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Henry Edwards
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Dylan Gordon
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Aaron Ford
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Benjamin Allen
                                        </label>
                                    </li>
                                    <li class="list-group-item">
                                        <label>
                                            <input class="checkbox-lms" type="checkbox" name="check[]">
                                            <span class="avatar"><img src="images/user.png"></span>
                                            Henry Sanchez
                                        </label>
                                    </li>
                                </ul>
                            </div>
                        </div>
</code>```

JS:

```<code>$(".member-list li :checkbox").on('click', function(){
        $(this).parents(".list-group-item").toggleClass("checked");
    });
    $("#select_all").on('click', function(){
        $(".list-group-item").toggleClass("checked",this.checked);
    });
</code>```

Demo:

https://fiddle.jshell.net/regrduq5/

答:
You can use select all checkbox checked state while toggling the class checked in list groups:

```<code>$("#select_all").on('click', function(){
  $(".list-group-item").toggleClass("checked",this.checked);
});
</code>```

Working Demo

Title: Select all checkbox issue

Body:
In HTML, when I click on checkbox from the list it adds class to its parent li, but when I need to select all checkbox when any one of the lists is already selected then it mismatches.

HTML:

<input type="checkbox" id="select_all">
                                    <select class="select-admin">
                                        <option>7 Operators</option>
                                        <option>7 Trainers</option>
                                    </select>

                                            <input class="checkbox-lms" type="checkbox" name="check[]" checked="checked">

                                            Kimberly Palmer

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Christopher Henry

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Henry Edwards

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Dylan Gordon

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Aaron Ford

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Benjamin Allen

                                            <input class="checkbox-lms" type="checkbox" name="check[]">

                                            Henry Sanchez

JS:

$(".member-list li :checkbox").on('click', function(){
        $(this).parents(".list-group-item").toggleClass("checked");
    });
    $("#select_all").on('click', function(){
        $(".list-group-item").toggleClass("checked",this.checked);
    });

Demo:

https://fiddle.jshell.net/regrduq5/

Body:
You can use select all checkbox checked state while toggling the class checked in list groups:

$("#select_all").on('click', function(){
  $(".list-group-item").toggleClass("checked",this.checked);
});

Working Demo


问:
The sandbox for Neo4J not working in Internet Explorer 11
I'm currently working on an organization that prevents me from installing other browsers so I have to work on IE 11. Is there any limitation to Neo4J's Sandbox or is it generally not working right now?

For those with access to other browsers here's the link:

https://neo4j.com/sandbox-v2/

Thank you for your replies

答:
This is not working on IE 11.0!
Thanks to Tom Geudens and Dave Bennett for your help.</p>


问:
How to convert Meters to Foot using PHP
I have used this code which shows an error:ie if my meters is 175m but when i convert it does'nt show that thing</p>

```<code><?php
function metersToFeetInches($meters, $echo = true)
{
    $m = $meters;
    $valInFeet = $m*3.2808399;
    $valFeet = (int)$valInFeet;
    $valInches = round(($valInFeet-$valFeet)*12);
    $data = $valFeet."′".$valInches."″";
    if($echo == true)
    {
            echo $data;
    } else {
            return $data;
    }
}
?>
<?php
$feetInches = metersToFeetInches(1.75,false);
echo $feetInches;
?>
</code>```

答:
```<code><?php
function metersToFeetInches($meters, $echo = true)
{
    $m = $meters;
    $valInFeet = $m*3.2808399;
    $valFeet = (int)$valInFeet;
    $valInches = round(($valInFeet-$valFeet)*12);
    $data = $valFeet."′".$valInches."″";
    if($echo == true)
    {
        echo $data;
    } else {
        return $data;
    }
}
?>
</code>```

Title: How to convert Meters to Foot using PHP

Body:
I have used this code which shows an error:ie if my meters is 175m but when i convert it does'nt show that thing

<?php
function metersToFeetInches($meters, $echo = true)
{
    $m = $meters;
    $valInFeet = $m*3.2808399;
    $valFeet = (int)$valInFeet;
    $valInches = round(($valInFeet-$valFeet)*12);
    $data = $valFeet."′".$valInches."″";
    if($echo == true)
    {
            echo $data;
    } else {
            return $data;
    }
}
?>
<?php
$feetInches = metersToFeetInches(1.75,false);
echo $feetInches;
?>

Body:
<?php
function metersToFeetInches($meters, $echo = true)
{
    $m = $meters;
    $valInFeet = $m*3.2808399;
    $valFeet = (int)$valInFeet;
    $valInches = round(($valInFeet-$valFeet)*12);
    $data = $valFeet."&prime;".$valInches."&Prime;";
    if($echo == true)
    {
        echo $data;
    } else {
        return $data;
    }
}
?>


问:
How to write JUnit for equals() of static inner class
I have this following

```<code>public class PlayerHandler {

  public static class PlayerValue {
    public String name;
    public String value;
    public String status;

    @Override
    public boolean equals(Object o) {

        PlayerValue playerValue = (PlayerValue) o;
        return playerValue != null && StringUtils.equals(playerValue.name, name)
                && StringUtils.equals(playerValue.value, value) && StringUtils.equals(playerValue.status, status);
    }
}
</code>```

}

how to write jUnit for this ? Please help.

答:
```<code>private PlayerHandler.PlayerValue value;
private PlayerHandler.PlayerValue value2;

@BeforeTest(){
     value = new PlayerHandler.PlayerValue();
     value2 =new  PlayerHandler.PlayerValue();

     value.name = "name1";
     value.playerValue = "value1";
     value.status = "status1";
}

@Test
public void checkEquals(){
     value2.name = value.name;
     value2.playerValue = value.playerValue;
     value2.status = value.status;

     assertEquals(value , value2 );
}

@Test
public void checkThaNotEquals(){
     value2.name = "value2";
     value2.playerValue = "playerValue2";
     value2.status = "status 2";

     assertNotEquals(value , value2 );
}

@Test
public void checkNotEqualsWithNull(){
     assertNotEquals(value , null);
}
</code>```

Body:
I have this following

public class PlayerHandler {

  public static class PlayerValue {
    public String name;
    public String value;
    public String status;

    @Override
    public boolean equals(Object o) {

        PlayerValue playerValue = (PlayerValue) o;
        return playerValue != null && StringUtils.equals(playerValue.name, name)
                && StringUtils.equals(playerValue.value, value) && StringUtils.equals(playerValue.status, status);
    }
}

}

how to write jUnit for this ? Please help.


问:
Login in with Alamofire : Could not cast value of type '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString' (0x102e66c40)
Hi I am new to programming and I'm stuck at this error. I am logging in from Xcode to MySQL, but I am unable to move on to home page. My code works fine in PHP and I am unable to login.

Below is my code:

```<code>@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters = [
            "username":username.text!,
            "password":password.text!
    ]

    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
        response in
        //printing response
        print(response)

        if let result = response.result.value
        {
            let resultValue:String = result as! String;

            if (resultValue == "login_success")
            {
                //login is successful
                UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                UserDefaults.standard.synchronize();

                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}
</code>```

It returns:

login_success Could not cast value of type
  '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString'
  (0x102e66c40).

That's why I am unable to move on to my home page.

答:
Because your result is dictionary type not string type:-

use this

```<code>let resultValue = result as! [String:Any];
</code>```

later you can get value of login_success based on key

Body:
Hi I am new to programming and I'm stuck at this error. I am logging in from Xcode to MySQL, but I am unable to move on to home page. My code works fine in PHP and I am unable to login.

Below is my code:

@IBAction func Login(_ sender: UIButton)
{
    let URL_USER_REGISTER = "http://localhost/login.php"

    let parameters: Parameters = [
            "username":username.text!,
            "password":password.text!
    ]

    Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
    {
        response in
        //printing response
        print(response)

        if let result = response.result.value
        {
            let resultValue:String = result as! String;

            if (resultValue == "login_success")
            {
                //login is successful
                UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                UserDefaults.standard.synchronize();

                self.dismiss(animated: true, completion: nil)
            }
        }
    }
}

It returns:

login_success Could not cast value of type
  '__NSSingleEntryDictionaryI' (0x103860210) to 'NSString'
  (0x102e66c40).

That's why I am unable to move on to my home page.

Body:
Because your result is dictionary type not string type:-

use this

let resultValue = result as! [String:Any];

later you can get value of login_success based on key


问:
Unity Custom Inspector List<SerializableObject> is not saving values when scene is changed (or unity is closed)
I'm trying to create a custom inspector for one of my classes in Unity:

my main class looks like this:

```<code>public class MapGenerator : MonoBehaviour
{

    public int width;
    public int height;

    [SerializeField]
    public List<Tile> tiles;
}
</code>```

my Tile class looks like this:

```<code>[System.Serializable]
public class Tile  {

    public TileType tileType;
    public Sprite tileTexture;
}
</code>```

And this is my Editor class:

```<code>    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(MapGenerator))]
public class MapGeneratorEditor : Editor
{

    static bool showMapProperties = true;
    static bool showTiles = true;
    private SerializedObject _target;
    SerializedProperty _mTiles;
    int _mTilesSize;
    public override void OnInspectorGUI()
    {
        MapGenerator myTarget = (MapGenerator)target;
        SerializedObject _mySerializedTarget = new SerializedObject(target);

        _mySerializedTarget.Update();
        _mySerializedTarget.ApplyModifiedProperties();
        //SerializedProperty _mySerializedTileList = _mySerializedTarget.FindProperty("tiles");

        showMapProperties = EditorGUILayout.Foldout(showMapProperties, new GUIContent("Map Properties", "Set different properties fot the map generation."));

        if (showMapProperties)
        {
            myTarget.width = EditorGUILayout.IntSlider(new GUIContent("Width", "Specify the width of the map"), myTarget.width, 1, 100);
            myTarget.height = EditorGUILayout.IntSlider(new GUIContent("Height", "Specify the height of the map"), myTarget.height, 1, 100);
        }

        showTiles = EditorGUILayout.Foldout(showTiles, new GUIContent("Tiles List", "Tiles that are used to generate the map"));

        if (showTiles)
        {

            _mTilesSize = myTarget.tiles.Count;

            for (int y = 0; y < _mTilesSize; y++)
            {
                myTarget.tiles[y].tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", myTarget.tiles[y].tileType);
                myTarget.tiles[y].tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Walkable Tile", "Tile where the enemies can walk"), myTarget.tiles[y].tileTexture, typeof(Sprite), false, null);
                GUILayout.Label("____________________________________________________________________________________________________________");
            }

            if (GUILayout.Button(new GUIContent("Add new Tile", "Click to add a new tile to the list")))
            {
                Tile newTile = new Tile();
                newTile.tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", TileType.NONE);
                //newTile.tileType = (TileType)EditorGUILayout.EnumPopup(new GUIContent("Tile Type", "Type of selected tile"), newTile.tileType,GUIStyle.none,null);
                newTile.tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), newTile.tileTexture, typeof(Sprite), false, null);
                //tiles.Add(newTile);
                myTarget.tiles.Add(newTile);

            }

            if (GUILayout.Button(new GUIContent("Remove Tile", "Click to remove the last tile in the list")))
            {
                //myTarget.Invoke("RemoveTile", 0.0f);
                //if (tiles.Count > 0)
                //    tiles.RemoveAt(tiles.Count - 1);

                if (myTarget.tiles.Count > 0)
                    myTarget.tiles.RemoveAt(myTarget.tiles.Count - 1);
            }

            if (GUILayout.Button(new GUIContent("Remove All Tile", "Click to remove all tiles in the list")))
            {
                myTarget.tiles.Clear();
            }

        }

        if (GUI.changed)
        {
            Debug.Log("GUI Changed");
            EditorUtility.SetDirty(target);
        }
        _mySerializedTarget.Update();
        _mySerializedTarget.ApplyModifiedProperties();
    }
</code>```

It looks like this in my editor:

My problem is that if I change any property of the Tiles List, meaning if I modify a enum or add a texture to one of the variables the value or texture assigned is removed once I change the scene or if Unity is closed.

This is the very first time that I tried something like this in the editor. any help is appreciated.

答:
It seems to me like the problem was that Unity was not recognizing the changes on the scene so I have forced them using

EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());

I found that behaviour after clicking on "Reset Component" then clicking on my button "Add new Tile" , the new tile is added successfully then I tried to change the scene and unity asked to save the scene, I clicked on "OK" and when I returned to the scene everything was fine, so I tried adding a new Tile, the new tile is added but when I changed the scene Unity didn't asked to save changes.

now my MapGeneratorEditor.cs script looks like this:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;

[CustomEditor(typeof(MapGenerator))]
public class MapGeneratorEditor : Editor
{

    static bool showMapProperties = true;
    static bool showTiles = true;
    private SerializedObject _target;
    SerializedProperty _mTiles;
    int _mTilesSize;
    MapGenerator myTarget;

    public override void OnInspectorGUI()
    {

        myTarget = (MapGenerator)target;

        //SerializedProperty _mySerializedTileList = _mySerializedTarget.FindProperty("tiles");

        showMapProperties = EditorGUILayout.Foldout(showMapProperties, new GUIContent("Map Properties", "Set different properties fot the map generation."));

        if (showMapProperties)
        {
            myTarget.width = EditorGUILayout.IntSlider(new GUIContent("Width", "Specify the width of the map"), myTarget.width, 1, 100);
            myTarget.height = EditorGUILayout.IntSlider(new GUIContent("Height", "Specify the height of the map"), myTarget.height, 1, 100);
        }

        showTiles = EditorGUILayout.Foldout(showTiles, new GUIContent("Tiles List", "Tiles that are used to generate the map"));

        if (showTiles)
        {

            _mTilesSize = myTarget.tiles.Count;

            for (int y = 0; y < _mTilesSize; y++)
            {
                myTarget.tiles[y].tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", myTarget.tiles[y].tileType);
                myTarget.tiles[y].tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), myTarget.tiles[y].tileTexture, typeof(Sprite), false, null);

                GUILayout.Label("____________________________________________________________________________________________________________");
            }

            if (GUILayout.Button(new GUIContent("Add new Tile", "Click to add a new tile to the list")))
            {
                Tile newTile = new Tile();
                newTile.tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", TileType.NONE);
                //newTile.tileType = (TileType)EditorGUILayout.EnumPopup(new GUIContent("Tile Type", "Type of selected tile"), newTile.tileType,GUIStyle.none,null);
                newTile.tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), newTile.tileTexture, typeof(Sprite), false, null);
                //tiles.Add(newTile);
                myTarget.tiles.Add(newTile);

            }

            if (GUILayout.Button(new GUIContent("Remove Tile", "Click to remove the last tile in the list")))
            {
                //myTarget.Invoke("RemoveTile", 0.0f);
                //if (tiles.Count > 0)
                //    tiles.RemoveAt(tiles.Count - 1);

                if (myTarget.tiles.Count > 0)
                    myTarget.tiles.RemoveAt(myTarget.tiles.Count - 1);
            }

            if (GUILayout.Button(new GUIContent("Remove All Tiles", "Click to remove all tiles in the list")))
            {
                myTarget.tiles.Clear();
            }

        }

        if(GUI.changed)
            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());

    }

}
</code>```

Body:
I'm trying to create a custom inspector for one of my classes in Unity:

my main class looks like this:

public class MapGenerator : MonoBehaviour
{

    public int width;
    public int height;

    [SerializeField]
    public List<Tile> tiles;
}

my Tile class looks like this:

[System.Serializable]
public class Tile  {

    public TileType tileType;
    public Sprite tileTexture;
}

And this is my Editor class:

    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(MapGenerator))]
public class MapGeneratorEditor : Editor
{

    static bool showMapProperties = true;
    static bool showTiles = true;
    private SerializedObject _target;
    SerializedProperty _mTiles;
    int _mTilesSize;
    public override void OnInspectorGUI()
    {
        MapGenerator myTarget = (MapGenerator)target;
        SerializedObject _mySerializedTarget = new SerializedObject(target);

        _mySerializedTarget.Update();
        _mySerializedTarget.ApplyModifiedProperties();
        //SerializedProperty _mySerializedTileList = _mySerializedTarget.FindProperty("tiles");

        showMapProperties = EditorGUILayout.Foldout(showMapProperties, new GUIContent("Map Properties", "Set different properties fot the map generation."));

        if (showMapProperties)
        {
            myTarget.width = EditorGUILayout.IntSlider(new GUIContent("Width", "Specify the width of the map"), myTarget.width, 1, 100);
            myTarget.height = EditorGUILayout.IntSlider(new GUIContent("Height", "Specify the height of the map"), myTarget.height, 1, 100);
        }

        showTiles = EditorGUILayout.Foldout(showTiles, new GUIContent("Tiles List", "Tiles that are used to generate the map"));

        if (showTiles)
        {

            _mTilesSize = myTarget.tiles.Count;

            for (int y = 0; y < _mTilesSize; y++)
            {
                myTarget.tiles[y].tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", myTarget.tiles[y].tileType);
                myTarget.tiles[y].tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Walkable Tile", "Tile where the enemies can walk"), myTarget.tiles[y].tileTexture, typeof(Sprite), false, null);
                GUILayout.Label("____________________________________________________________________________________________________________");
            }

            if (GUILayout.Button(new GUIContent("Add new Tile", "Click to add a new tile to the list")))
            {
                Tile newTile = new Tile();
                newTile.tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", TileType.NONE);
                //newTile.tileType = (TileType)EditorGUILayout.EnumPopup(new GUIContent("Tile Type", "Type of selected tile"), newTile.tileType,GUIStyle.none,null);
                newTile.tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), newTile.tileTexture, typeof(Sprite), false, null);
                //tiles.Add(newTile);
                myTarget.tiles.Add(newTile);

            }

            if (GUILayout.Button(new GUIContent("Remove Tile", "Click to remove the last tile in the list")))
            {
                //myTarget.Invoke("RemoveTile", 0.0f);
                //if (tiles.Count > 0)
                //    tiles.RemoveAt(tiles.Count - 1);

                if (myTarget.tiles.Count > 0)
                    myTarget.tiles.RemoveAt(myTarget.tiles.Count - 1);
            }

            if (GUILayout.Button(new GUIContent("Remove All Tile", "Click to remove all tiles in the list")))
            {
                myTarget.tiles.Clear();
            }

        }

        if (GUI.changed)
        {
            Debug.Log("GUI Changed");
            EditorUtility.SetDirty(target);
        }
        _mySerializedTarget.Update();
        _mySerializedTarget.ApplyModifiedProperties();
    }

It looks like this in my editor:

My problem is that if I change any property of the Tiles List, meaning if I modify a enum or add a texture to one of the variables the value or texture assigned is removed once I change the scene or if Unity is closed.

This is the very first time that I tried something like this in the editor. any help is appreciated.

Body:
It seems to me like the problem was that Unity was not recognizing the changes on the scene so I have forced them using

EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());

I found that behaviour after clicking on "Reset Component" then clicking on my button "Add new Tile" , the new tile is added successfully then I tried to change the scene and unity asked to save the scene, I clicked on "OK" and when I returned to the scene everything was fine, so I tried adding a new Tile, the new tile is added but when I changed the scene Unity didn't asked to save changes.

now my MapGeneratorEditor.cs script looks like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.SceneManagement;

[CustomEditor(typeof(MapGenerator))]
public class MapGeneratorEditor : Editor
{

    static bool showMapProperties = true;
    static bool showTiles = true;
    private SerializedObject _target;
    SerializedProperty _mTiles;
    int _mTilesSize;
    MapGenerator myTarget;

    public override void OnInspectorGUI()
    {

        myTarget = (MapGenerator)target;

        //SerializedProperty _mySerializedTileList = _mySerializedTarget.FindProperty("tiles");

        showMapProperties = EditorGUILayout.Foldout(showMapProperties, new GUIContent("Map Properties", "Set different properties fot the map generation."));

        if (showMapProperties)
        {
            myTarget.width = EditorGUILayout.IntSlider(new GUIContent("Width", "Specify the width of the map"), myTarget.width, 1, 100);
            myTarget.height = EditorGUILayout.IntSlider(new GUIContent("Height", "Specify the height of the map"), myTarget.height, 1, 100);
        }

        showTiles = EditorGUILayout.Foldout(showTiles, new GUIContent("Tiles List", "Tiles that are used to generate the map"));

        if (showTiles)
        {

            _mTilesSize = myTarget.tiles.Count;

            for (int y = 0; y < _mTilesSize; y++)
            {
                myTarget.tiles[y].tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", myTarget.tiles[y].tileType);
                myTarget.tiles[y].tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), myTarget.tiles[y].tileTexture, typeof(Sprite), false, null);

                GUILayout.Label("____________________________________________________________________________________________________________");
            }

            if (GUILayout.Button(new GUIContent("Add new Tile", "Click to add a new tile to the list")))
            {
                Tile newTile = new Tile();
                newTile.tileType = (TileType)EditorGUILayout.EnumPopup("Tile Type", TileType.NONE);
                //newTile.tileType = (TileType)EditorGUILayout.EnumPopup(new GUIContent("Tile Type", "Type of selected tile"), newTile.tileType,GUIStyle.none,null);
                newTile.tileTexture = (Sprite)EditorGUILayout.ObjectField(new GUIContent("Tile Texture", "Tile Texture"), newTile.tileTexture, typeof(Sprite), false, null);
                //tiles.Add(newTile);
                myTarget.tiles.Add(newTile);

            }

            if (GUILayout.Button(new GUIContent("Remove Tile", "Click to remove the last tile in the list")))
            {
                //myTarget.Invoke("RemoveTile", 0.0f);
                //if (tiles.Count > 0)
                //    tiles.RemoveAt(tiles.Count - 1);

                if (myTarget.tiles.Count > 0)
                    myTarget.tiles.RemoveAt(myTarget.tiles.Count - 1);
            }

            if (GUILayout.Button(new GUIContent("Remove All Tiles", "Click to remove all tiles in the list")))
            {
                myTarget.tiles.Clear();
            }

        }

        if(GUI.changed)
            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());

    }

}


问:
set selected item of drop downlist equal to a text box
How can I make my drop down list shows the value in my text box? The value is always one the items of drop down list, but how can I set the selected item of drop down list equals to the value of my textbox, after click?</p>

```<code> $('<input  name="Product Name" data-type="string" \>')
     .appendTo(container)
     .kendoDropDownList({
         dataSource: mydata,
         dataTextField: "Text",
  });
</code>```

答:
As far as I could understand what you're trying to accomplish,  you can do it like this

```<code>var selectList = document.getElementById('selectList');
selectList.addEventListener('change', function() {
    var selectedVal = selectList.value;
    var inputText = document.getElementById('textInput');
  inputText.value = selectedVal;
});
</code>```

See it in action -> Fiddle

Body:
How can I make my drop down list shows the value in my text box? The value is always one the items of drop down list, but how can I set the selected item of drop down list equals to the value of my textbox, after click?

 $('<input  name="Product Name" data-type="string" \>')
     .appendTo(container)
     .kendoDropDownList({
         dataSource: mydata,
         dataTextField: "Text",
  });

Body:
As far as I could understand what you're trying to accomplish,  you can do it like this

var selectList = document.getElementById('selectList');
selectList.addEventListener('change', function() {
    var selectedVal = selectList.value;
    var inputText = document.getElementById('textInput');
  inputText.value = selectedVal;
});

See it in action -> Fiddle


问:
How to unselect multiple UITableview cell by tapping the selected button again

Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

```<code>-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}
</code>```

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}
</code>```

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

答:
You need to do in this way:

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/// first run a loop for deselect all data
//Make all Rows To UnSelected
for (int i = 0; i < [arrayOfServiceTypes count]; i++)
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];

}

Now which one you have selected you need to do like this:

[arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];

[self.tableView reloadData];

}
</code>```

I hope it will help your problem.

Body:
Hi, I wanted to select multiple UITableViewCells and unselect any by tapping again.

Following are my codes of didSelectRowAtIndexPath: and cellForRowAtIndexPath:

-(UITableViewCell *)tableView:(UITableView *)tableView
   cellForRowAtIndexPath:(NSIndexPath *)indexPath
   {
NSString *cellIdentifier = @"serviceTypeSelectionCell";
ServiceTypeSelectionTableViewCell *serviceTypeCell = (ServiceTypeSelectionTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (serviceTypeCell == nil)
{
    serviceTypeCell = [[ServiceTypeSelectionTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
//serviceDetailsCell.noOfQuantityTextField.tag = indexPath.row;
serviceTypeCell.serviceTypeNameLabel.text = [NSString stringWithFormat:@"%@",arrayOfServiceTypes[indexPath.row][@"sub_cat_name"]];

if([[arrayOfSelectedBoolValues objectAtIndex:indexPath.row] boolValue])
{
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_correct_icon"];
}
else {
    serviceTypeCell.serviceTypeImageView.image = [UIImage imageNamed:@"cancellation_reason_unselect_icon"];
}
return serviceTypeCell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
for (int i = 0; i < [arrayOfServiceTypes count]; i++)//Make all Rows To UnSelected
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];
}
[arrayOfSelectedBoolValues addObjectsFromArray:sele:indexPath.row];
if(arrayOfSelectedBoolValues!=nil)
{
    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
}

    [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
{
[self.tableView reloadData];
[self showOrHideAddButton];
}

I have an existing code of single select and unselect of the above uitableview. And I can get multiple selection only by disabling all the above code and keep this part in didSelectRowAtIndexPath:.

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    [self.tableView reloadData];
    [self showOrHideAddButton];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.doneButton.hidden = YES;
    arrayOfSelectedBoolValues = [[NSMutableArray alloc]init];

    for (int i = 0; i < [arrayOfServiceTypes count]; i++)
    {
        // [arrayOfexpOrCollBoolValues addObject:[NSNumber numberWithBool:NO]];
        [arrayOfSelectedBoolValues addObject:[NSNumber numberWithBool:NO]];
    }
    [self sendServiceToGetServiceTypes];
}

so please anyone post a structured code according to my code to select multiple tableviewcells and unselect any cells by tapping again before send selected values to the server.

Thanks in Advance.

Body:
You need to do in this way:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
/// first run a loop for deselect all data
//Make all Rows To UnSelected
for (int i = 0; i < [arrayOfServiceTypes count]; i++)
{
   [arrayOfSelectedBoolValues replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:NO]];

}

Now which one you have selected you need to do like this:

[arrayOfSelectedBoolValues replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];

[self.tableView reloadData];

}

I hope it will help your problem.


问:
The result of json.loads(string) is still a string
I'm currently trying to build a database using Python 3.6 (under Spyder) and more precisely sqlite3 (3.14.2). Since this last module wasn't designed to enable list insertion in the database, i'm using the json (2.0.9) module to transform my lists into strings. The following function, used to transfer data from a database to another, and where I create and insert list for the first time, returns me weird results :

```<code>def database_concatenation():
    global log,name2,name3,timefin,path
    conn = sqlite3.connect(path+name2)
    cursor = conn.cursor()
    conn2 = sqlite3.connect(path+name3)
    cursor2 = conn2.cursor()
    cursor.execute("""select sqlite_version()""")
    print(cursor.fetchall())
    cursor.execute("""SELECT * FROM {}""".format(name2))
    for dataline in cursor.fetchall():
        cursor2.execute("""
                       SELECT * FROM {}
                   WHERE (
                   timestp = ?
                   AND idq = ?
                   AND idz = ?
                   AND portq = ?
                   AND portz = ?
                   AND prot = ?);
                   """.format(name3) , (dataline[0],dataline[1],dataline[2],dataline[3],dataline[4],dataline[5]))
        result = cursor2.fetchone()

        if result == None:
            with open(path+log,"a") as login:

                login.write(timefin + " Warning ! Unusual connection :" + str(dataline)+ '\n')

            cursor2.execute("""
                       INSERT INTO {}(timestp,
                       idq,
                       idz,
                       portq,
                       portz,
                       prot,
                       Leftmean,
                       Leftstdev,
                       Leftmean10,
                       Leftstdev10,
                       Rightmean,
                       Rightstdev,
                       Rightmean10,
                       Rightstdev10,
                       nbdays) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);""".format(name3), (dataline[0],dataline[1],dataline[2],dataline[3],dataline[4],dataline[5],dataline[6],0,json.dumps([dataline[6]]),0,dataline[7],0,json.dumps([dataline[7]]),0,1))

        else:
            print(result[8])
            Leftmean10 = json.loads(result[8])
            print(Leftmean10)
            Rightmean10 = json.loads(result[12])
            print(type(Leftmean10))

            nbdays = result[14]
            aL,bL = intervalle_confiance(result[6],result[7],result[14])
            aL10,bL10 = intervalle_confiancebis(Leftmean10,result[9],min(nbdays,10))
            aR,bR = intervalle_confiance(result[10],result[11],result[14])
            aR10,bR10 = intervalle_confiancebis(Rightmean10,result[13],min(nbdays,10))
            rhwmny = dataline[7]
            lhwmny = dataline[6]

        if nbdays >= 10:
            Leftmean10.pop(0)
            Rightmean10.pop(0)
            Leftmean10.append(dataline[6])
            Rightmean10.append(dataline[7])
            Lmean = result[6]
            Lmean = Lmean*(nbdays/(nbdays+1)) + dataline[6]/(nbdays)
            Rmean = result[10]
            Rmean = Rmean*(nbdays/(nbdays+1)) + dataline[7]/(nbdays)
            Lstdev,Rstdev = result[7],result[11]

            add = (dataline[6] - Lmean)
            Lstdev = sqrt(Lstdev*Lstdev + (add*add))
            add = (dataline[7] - Rmean)
            Rstdev = sqrt(Rstdev*Rstdev + (add*add))
            mean = (sum(Leftmean10)/min(10,nbdays))
            meansquare = mean*mean

            othermean = (sum([i*i for i in Leftmean10])/min(10,nbdays))
            Lstdev10 = othermean - meansquare

            mean = (sum([int(i) for i in Rightmean10])/min(10,nbdays))
            meansquare = mean*mean

            othermean = (sum([i*i for i in Rightmean10])/min(10,nbdays))
            Rstdev10 = othermean - meansquare

            nbdays +=1

            Leftmean10 = json.dumps(result[8])
            Rightmean10 = json.dumps(result[12])
            print(Leftmean10)

            cursor2.execute("""UPDATE {} SET Leftmean = ?,
                   Leftstdev = ?,
                   Leftmean10 = ?,
                   Leftstdev10 = ?,
                   Rightmean = ?,
                   Rightstdev = ?,
                   Rightmean10 = ?,
                   Rightstdev10 = ?,
                   nbdays = ?  WHERE (timestp = ? AND idq = ?
                   AND idz = ?
                   AND portq = ?
                   AND portz = ?
                   AND prot = ?);""".format(name3), (Lmean,Lstdev,Leftmean10,Lstdev10,Rmean,Rstdev,Rightmean10,Rstdev10,nbdays,result[0],result[1],result[2],result[3],result[4],result[5]))

    conn.commit()
    conn2.commit()
    conn.close()
    conn2.close()
    bla= "it works"

    return(bla)
</code>```

When i launch it for the first time (base "name3" created but empty), the condition "if result = None" is always verified, and the database is correctly filled. Especially, my list is successfully stocked, using the function json.dumps(mylist)
The problem happens while processing a second time : the block

```<code>print(result[8])
Leftmean10 = json.loads(result[8])
print(Leftmean10)
Rightmean10 = json.loads(result[12])
print(type(Leftmean10))
</code>```

returns

```<code>"[69]"
[69]
<class 'str'>
</code>```

I furthermore get later errors because of this 'str' type.

I don't understand what is happening. The json.loads function should returns a list, doesn't it ? And that's what it seems to do : print(Leftmean10) returns me [69]and not "[69]", except.. It's for the program still a string ^^

Thank you in advance for answers !

答:
Your string result[8] actually contains the double quote characters in them:

```<code>>>> print('[69]')
[69]
>>> print('"[69]"')
"[69]"
</code>```

Inside json.loads this is correctly converted to the string "[69]". One way to fix this is by removing these two double quotes:

```<code>json.loads(result[8][1:-1])
</code>```

Body:
I'm currently trying to build a database using Python 3.6 (under Spyder) and more precisely sqlite3 (3.14.2). Since this last module wasn't designed to enable list insertion in the database, i'm using the json (2.0.9) module to transform my lists into strings. The following function, used to transfer data from a database to another, and where I create and insert list for the first time, returns me weird results :

def database_concatenation():
    global log,name2,name3,timefin,path
    conn = sqlite3.connect(path+name2)
    cursor = conn.cursor()
    conn2 = sqlite3.connect(path+name3)
    cursor2 = conn2.cursor()
    cursor.execute("""select sqlite_version()""")
    print(cursor.fetchall())
    cursor.execute("""SELECT * FROM {}""".format(name2))
    for dataline in cursor.fetchall():
        cursor2.execute("""
                       SELECT * FROM {}
                   WHERE (
                   timestp = ?
                   AND idq = ?
                   AND idz = ?
                   AND portq = ?
                   AND portz = ?
                   AND prot = ?);
                   """.format(name3) , (dataline[0],dataline[1],dataline[2],dataline[3],dataline[4],dataline[5]))
        result = cursor2.fetchone()

        if result == None:
            with open(path+log,"a") as login:

                login.write(timefin + " Warning ! Unusual connection :" + str(dataline)+ '\n')

            cursor2.execute("""
                       INSERT INTO {}(timestp,
                       idq,
                       idz,
                       portq,
                       portz,
                       prot,
                       Leftmean,
                       Leftstdev,
                       Leftmean10,
                       Leftstdev10,
                       Rightmean,
                       Rightstdev,
                       Rightmean10,
                       Rightstdev10,
                       nbdays) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);""".format(name3), (dataline[0],dataline[1],dataline[2],dataline[3],dataline[4],dataline[5],dataline[6],0,json.dumps([dataline[6]]),0,dataline[7],0,json.dumps([dataline[7]]),0,1))

        else:
            print(result[8])
            Leftmean10 = json.loads(result[8])
            print(Leftmean10)
            Rightmean10 = json.loads(result[12])
            print(type(Leftmean10))

            nbdays = result[14]
            aL,bL = intervalle_confiance(result[6],result[7],result[14])
            aL10,bL10 = intervalle_confiancebis(Leftmean10,result[9],min(nbdays,10))
            aR,bR = intervalle_confiance(result[10],result[11],result[14])
            aR10,bR10 = intervalle_confiancebis(Rightmean10,result[13],min(nbdays,10))
            rhwmny = dataline[7]
            lhwmny = dataline[6]

        if nbdays >= 10:
            Leftmean10.pop(0)
            Rightmean10.pop(0)
            Leftmean10.append(dataline[6])
            Rightmean10.append(dataline[7])
            Lmean = result[6]
            Lmean = Lmean*(nbdays/(nbdays+1)) + dataline[6]/(nbdays)
            Rmean = result[10]
            Rmean = Rmean*(nbdays/(nbdays+1)) + dataline[7]/(nbdays)
            Lstdev,Rstdev = result[7],result[11]

            add = (dataline[6] - Lmean)
            Lstdev = sqrt(Lstdev*Lstdev + (add*add))
            add = (dataline[7] - Rmean)
            Rstdev = sqrt(Rstdev*Rstdev + (add*add))
            mean = (sum(Leftmean10)/min(10,nbdays))
            meansquare = mean*mean

            othermean = (sum([i*i for i in Leftmean10])/min(10,nbdays))
            Lstdev10 = othermean - meansquare

            mean = (sum([int(i) for i in Rightmean10])/min(10,nbdays))
            meansquare = mean*mean

            othermean = (sum([i*i for i in Rightmean10])/min(10,nbdays))
            Rstdev10 = othermean - meansquare

            nbdays +=1

            Leftmean10 = json.dumps(result[8])
            Rightmean10 = json.dumps(result[12])
            print(Leftmean10)

            cursor2.execute("""UPDATE {} SET Leftmean = ?,
                   Leftstdev = ?,
                   Leftmean10 = ?,
                   Leftstdev10 = ?,
                   Rightmean = ?,
                   Rightstdev = ?,
                   Rightmean10 = ?,
                   Rightstdev10 = ?,
                   nbdays = ?  WHERE (timestp = ? AND idq = ?
                   AND idz = ?
                   AND portq = ?
                   AND portz = ?
                   AND prot = ?);""".format(name3), (Lmean,Lstdev,Leftmean10,Lstdev10,Rmean,Rstdev,Rightmean10,Rstdev10,nbdays,result[0],result[1],result[2],result[3],result[4],result[5]))

    conn.commit()
    conn2.commit()
    conn.close()
    conn2.close()
    bla= "it works"

    return(bla)

When i launch it for the first time (base "name3" created but empty), the condition "if result = None" is always verified, and the database is correctly filled. Especially, my list is successfully stocked, using the function json.dumps(mylist)
The problem happens while processing a second time : the block

print(result[8])
Leftmean10 = json.loads(result[8])
print(Leftmean10)
Rightmean10 = json.loads(result[12])
print(type(Leftmean10))

returns

"[69]"
[69]
<class 'str'>

I furthermore get later errors because of this 'str' type.

I don't understand what is happening. The json.loads function should returns a list, doesn't it ? And that's what it seems to do : print(Leftmean10) returns me [69]and not "[69]", except.. It's for the program still a string ^^

Thank you in advance for answers !

Body:
Your string result[8] actually contains the double quote characters in them:

>>> print('[69]')
[69]
>>> print('"[69]"')
"[69]"

Inside json.loads this is correctly converted to the string "[69]". One way to fix this is by removing these two double quotes:

json.loads(result[8][1:-1])


问:
Display a byte as a checkbox using a EditorTemplate?
My model class:

```<code>public class StatusList
{
   public int StatusID {get;set;}
   [UIHint("ByteCheckbox")]
   public byte Active {get;set;}
}
</code>```

In /Views/Shared/EditorTemplates I created a file called ByteCheckbox.cshtml

The editortemplate ByteCheckbox contains (My 3rd attempt):

```<code>@model byte
@if (Model == 1)
{
    @Html.CheckBox("", true)
}
else
{
    @Html.CheckBox("", false)
}
</code>```

Doing this nicely renders a checkbox.  When I change the checkbox status and try to save the changes the model validation complains that the value is 'false' (or 'true') instead of the expected 0 or 1.

How to modify the editortemplate to allow for the value to be translated?

答:
try this one </p>

```<code>    @model bool

   <div class="editor-for">
       @Html.CheckBox("", Model, new{@class="tickbox-single-line"})
   <div>
</code>```

Body:
My model class:

public class StatusList
{
   public int StatusID {get;set;}
   [UIHint("ByteCheckbox")]
   public byte Active {get;set;}
}

In /Views/Shared/EditorTemplates I created a file called ByteCheckbox.cshtml

The editortemplate ByteCheckbox contains (My 3rd attempt):

@model byte
@if (Model == 1)
{
    @Html.CheckBox("", true)
}
else
{
    @Html.CheckBox("", false)
}

Doing this nicely renders a checkbox.  When I change the checkbox status and try to save the changes the model validation complains that the value is 'false' (or 'true') instead of the expected 0 or 1.

How to modify the editortemplate to allow for the value to be translated?

Body:
try this one

    @model bool

   <div class="editor-for">
       @Html.CheckBox("", Model, new{@class="tickbox-single-line"})
   <div>


问:
VirtualStringTree - How to make it so that the nodes simply do not have a parent
I'm trying to move the nodes to the root of the tree so that they do not have a parent

```<code>Tree.MoveTo(LNodes[i], nil, amAddChildFirst, False);
</code>```

But they are simply deleted!
How to make it so that the nodes simply do not have a parent?

答:
I believe you need</p>

```<code>Tree.MoveTo( LNodes[i], LNodes[0], amInsertBefore, False);
</code>```

Body:
I'm trying to move the nodes to the root of the tree so that they do not have a parent

Tree.MoveTo(LNodes[i], nil, amAddChildFirst, False);

But they are simply deleted!
How to make it so that the nodes simply do not have a parent?

Body:
I believe you need

Tree.MoveTo( LNodes[i], LNodes[0], amInsertBefore, False);


问:
ES6 map array to string without comma
I am trying to map a list of errors into a list that I will show in a tooltip. The list added, but there's a , added between every li element.

I guess this is because this basically does errors.map(error => ...).toString() in the end. Any ideas how I can map the strings in errors array without having this comma added?

```<code>data-tip = {`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:</br>
  <ul>
    ${errors.map(error => `<li>${error}</li>`)}
  </ul>
`}
</code>```

答: .toString() of the array object uses Array.prototype.join method for converting the array into a string. The .join method by default uses , for joining the elements. You can replace the .toString() with .join('').

Title: ES6 map array to string without comma

Body:
I am trying to map a list of errors into a list that I will show in a tooltip. The list added, but there's a , added between every li element.

I guess this is because this basically does errors.map(error => ...).toString() in the end. Any ideas how I can map the strings in errors array without having this comma added?

data-tip = {`
  Precisa de corrigir os seguintes problemas antes de publicar o anúncio:

    ${errors.map(error => `<li>${error}</li>`)}

`}