问:
EditText with DatePicker dialog not showing error text when date is not selected
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

```<code>  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }
</code>```

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!

答:
So try this, i actually use TextInputLayout and TextInputEditText and never had problems </p>

<p>EditText.setError doesnt show Error text and only shows icon </p>

Body:
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!

Body:
So try this, i actually use TextInputLayout and TextInputEditText and never had problems

EditText.setError doesnt show Error text and only shows icon


来源: stackexchange

问:
Python program error at closing
I hope you can help me once again, I am still noob at programming so please bear with me. I got this error:

```<code>Traceback (most recent call last):
  File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module>
    postcodeinvoer = int(postcodeinvoer)
TypeError: int() argument must be a string or a number, not 'NoneType'
</code>```

The program works, but when I compile it, it will give an error when you close the program, saying there is something wrong with the code. I've tried deleting the line but the program wont work without it as it will go directly to the ELSE statement. Postcode1 is a range between certain numbers. The users have to fill in a number. If the number is within that range it will show the msgbox.

```<code>elif keuze in week2:

        postcodeinvoer = easygui.enterbox(msg="Voer een postcode in:", title="Postcodezoeker")
        postcodeinvoer = int(postcodeinvoer)

        if postcodeinvoer in postcode1:
            easygui.msgbox(msg="[Woensdag 3 mei, 10 mei, 17 mei, 24 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode2:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode3:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
</code>```

Btw is it possible to compile a python file to a single .exe file?
Hope you guys can help me. Thanks in advance!

Problem resolved!

答:
Check postcodeinvoeris not None.

```<code>if postcodeinvoer:
    postcodeinvoer = int(postcodeinvoer)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python program error at closing

Body:
I hope you can help me once again, I am still noob at programming so please bear with me. I got this error:

Traceback (most recent call last):
  File "C:\Python27\cx_Freeze exe Creator\Postcodezoekernl.py", line 136, in <module>
    postcodeinvoer = int(postcodeinvoer)
TypeError: int() argument must be a string or a number, not 'NoneType'

The program works, but when I compile it, it will give an error when you close the program, saying there is something wrong with the code. I've tried deleting the line but the program wont work without it as it will go directly to the ELSE statement. Postcode1 is a range between certain numbers. The users have to fill in a number. If the number is within that range it will show the msgbox.

elif keuze in week2:

        postcodeinvoer = easygui.enterbox(msg="Voer een postcode in:", title="Postcodezoeker")
        postcodeinvoer = int(postcodeinvoer)

        if postcodeinvoer in postcode1:
            easygui.msgbox(msg="[Woensdag 3 mei, 10 mei, 17 mei, 24 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode2:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)
        elif postcodeinvoer in postcode3:
            easygui.msgbox(msg="[Dinsdag 2 mei, 9 mei, 16 mei, 23 mei] [Donderdag 4 mei, 11 mei, 18 mei]", title=postcodeinvoer)

Btw is it possible to compile a python file to a single .exe file?
Hope you guys can help me. Thanks in advance!

Problem resolved!

Body:
Check postcodeinvoeris not None.

if postcodeinvoer:
    postcodeinvoer = int(postcodeinvoer)


问:
When scrolling custom ListView, the checkbox value changes

What I have: a custom listview with Textviews and checkbox.

Problem: Suppose my screen can show only 6 items of list at time, and the others are invisible.
So I checked the first element on the list (item at position 0). I scroll down to see all my list, when I scroll up at first element (item at position 0) the checkbox is checked correctly. Great! But now there are new items thath are checked too, for example the item at position 8 (because when I scroll the list (for theRycicling) it become the new item at position 0..remember my screen shows only 7 elements at time). And it become checked, but i have never checked it!

Question: How i can avoid this problem? I don't want that the checkbox that I don't click change their status.

Below my adapter for listView with the getView function where I have implemented the setOnCheckedChangeListener:

```<code>public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;

public NewQAAdapterSelectFriends(Context context) {
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
        convertView.setTag(viewHolder);
        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                        Person element = (Person) viewHolder.checkBox.getTag();

                        if(isChecked){
                            element.setCheck(buttonView.isChecked());
                            //data[position].setCheck(true); //this is equivalent to previous line

                        }
                        else{
                            //to-do

                        }

                    }
                });
        viewHolder.checkBox.setTag(data[position]);

    } else {

    }

     ViewHolder holder = (ViewHolder) convertView.getTag();
     holder.nameText.setText(data[position].getName());
     holder.surnameText.setText(data[position].getSurname());
     holder.contactImage.setImageResource(data[position].getPhotoRes());
     holder.contactImage.setScaleType(ScaleType.FIT_XY);
     holder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}
}
</code>```

Thanks for the answers :)

EDIT: With the suggestion i changed my getView like below:

```<code>@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setChecked(data[position].isCheck());
        viewHolder.checkBox.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

                if(viewHolder.checkBox.isChecked()==true)
                    data[position].setCheck(true);
                else
                    data[position].setCheck(false);
            }
        });

    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}
</code>```

SITUATION AFTER EDIT: Now, if i check the initial items that are shows on the screen and then I scrool the list, their value is correctly saved. But When I scroll the list and for example i want to check the last tree checkboxs of my list then after I scroll they become uncheked....BUT WHY??????

SOLVED: I solved my problem of getView with this code:

```<code>    public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;
boolean[] checkBoxState;
ViewHolder viewHolder;

public NewQAAdapterSelectFriends(Context context) {
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
    checkBoxState=new boolean[data.length];
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();

        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(checkBoxState[position]);
    viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {

           public void onClick(View v) {
               if(((CheckBox)v).isChecked()){
                   checkBoxState[position]=true;
                   data[position].setCheck(true);
               }else{
                   checkBoxState[position]=false;
                   data[position].setCheck(false);
               }
            }
        });
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}
</code>```

}

I have seen this tutorial to do my getView: http://androidcocktail.blogspot.it/2012/04/adding-checkboxes-to-custom-listview-in.html

答:
I have a good alternative for a CheckBox. You can use android:state_activated="true" for your ListView rows. It does not lose its state and does not require lots of code.

Here is how to works

create active_row.xml in your drawable folder

<selector xmlns:android="http://schemas.android.com/apk/res/android">

```<code><item android:state_activated="true"
          android:drawable="@android:color/darker_gray"/>
 </selector>
</code>```

Set the the Background of your Row layout as android:background="@drawable/active_row.xml"

And finally add this to your ListView
android:choiceMode="multipleChoice"

You can check the State of every row like this

```<code>View v;

LinearLayout yourRowLayout;
for (int i = 0; i < yourListView.getChildCount(); i++) {
v = yourListView.getChildAt(i);
yourRowLayout = (LinearLayout) v.findViewById(R.id. yourRowLayout);
if(yourRowLayout.isActivated()){....  }  }
</code>```

Body:
What I have: a custom listview with Textviews and checkbox.

Problem: Suppose my screen can show only 6 items of list at time, and the others are invisible.
So I checked the first element on the list (item at position 0). I scroll down to see all my list, when I scroll up at first element (item at position 0) the checkbox is checked correctly. Great! But now there are new items thath are checked too, for example the item at position 8 (because when I scroll the list (for theRycicling) it become the new item at position 0..remember my screen shows only 7 elements at time). And it become checked, but i have never checked it!

Question: How i can avoid this problem? I don't want that the checkbox that I don't click change their status.

Below my adapter for listView with the getView function where I have implemented the setOnCheckedChangeListener:

public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;

public NewQAAdapterSelectFriends(Context context) {
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        final ViewHolder viewHolder = new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);
        convertView.setTag(viewHolder);
        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setOnCheckedChangeListener(
                new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                        Person element = (Person) viewHolder.checkBox.getTag();

                        if(isChecked){
                            element.setCheck(buttonView.isChecked());
                            //data[position].setCheck(true); //this is equivalent to previous line

                        }
                        else{
                            //to-do

                        }

                    }
                });
        viewHolder.checkBox.setTag(data[position]);

    } else {

    }

     ViewHolder holder = (ViewHolder) convertView.getTag();
     holder.nameText.setText(data[position].getName());
     holder.surnameText.setText(data[position].getSurname());
     holder.contactImage.setImageResource(data[position].getPhotoRes());
     holder.contactImage.setScaleType(ScaleType.FIT_XY);
     holder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}
}

Thanks for the answers :)

EDIT: With the suggestion i changed my getView like below:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();
        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

        viewHolder.nameText.setTag(viewHolder.nameText);
        viewHolder.nameText.setTag(viewHolder.surnameText);
        viewHolder.contactImage.setTag(data[position]);
        viewHolder.checkBox.setChecked(data[position].isCheck());
        viewHolder.checkBox.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {

                if(viewHolder.checkBox.isChecked()==true)
                    data[position].setCheck(true);
                else
                    data[position].setCheck(false);
            }
        });

    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(data[position].isCheck());
    return convertView;
}

SITUATION AFTER EDIT: Now, if i check the initial items that are shows on the screen and then I scrool the list, their value is correctly saved. But When I scroll the list and for example i want to check the last tree checkboxs of my list then after I scroll they become uncheked....BUT WHY??????

SOLVED: I solved my problem of getView with this code:

    public class NewQAAdapterSelectFriends extends BaseAdapter {
private LayoutInflater mInflater;
private Person[] data;
boolean[] checkBoxState;
ViewHolder viewHolder;

public NewQAAdapterSelectFriends(Context context) {
    mInflater = LayoutInflater.from(context);
}

public void setData(Person[] data) {
    this.data = data;
    checkBoxState=new boolean[data.length];
}

@Override
public int getCount() {
    return data.length;
}

@Override
public Object getItem(int item) {
    return data[item];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item_select_friends, null);
        viewHolder=new ViewHolder();

        viewHolder.nameText=(TextView) convertView.findViewById(R.id.personName);
        viewHolder.surnameText=(TextView) convertView.findViewById(R.id.personSurname);
        viewHolder.contactImage=(ImageView) convertView.findViewById(R.id.personImage);
        viewHolder.checkBox=(CheckBox)convertView.findViewById(R.id.checkBox);

        convertView.setTag(viewHolder);

    }
    else{
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.nameText.setText(data[position].getName());
    viewHolder.surnameText.setText(data[position].getSurname());
    viewHolder.contactImage.setImageResource(data[position].getPhotoRes());
    viewHolder.contactImage.setScaleType(ScaleType.FIT_XY);
    viewHolder.checkBox.setChecked(checkBoxState[position]);
    viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {

           public void onClick(View v) {
               if(((CheckBox)v).isChecked()){
                   checkBoxState[position]=true;
                   data[position].setCheck(true);
               }else{
                   checkBoxState[position]=false;
                   data[position].setCheck(false);
               }
            }
        });
    return convertView;
}

static class ViewHolder {
    TextView nameText;
    TextView surnameText;
    ImageView contactImage;
    CheckBox checkBox;
}

}

I have seen this tutorial to do my getView: http://androidcocktail.blogspot.it/2012/04/adding-checkboxes-to-custom-listview-in.html

Body:
I have a good alternative for a CheckBox. You can use android:state_activated="true" for your ListView rows. It does not lose its state and does not require lots of code.

Here is how to works

create active_row.xml in your drawable folder

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true"
          android:drawable="@android:color/darker_gray"/>
 </selector>

Set the the Background of your Row layout as android:background="@drawable/active_row.xml"

And finally add this to your ListView
android:choiceMode="multipleChoice"

You can check the State of every row like this

View v;

LinearLayout yourRowLayout;
for (int i = 0; i < yourListView.getChildCount(); i++) {
v = yourListView.getChildAt(i);
yourRowLayout = (LinearLayout) v.findViewById(R.id. yourRowLayout);
if(yourRowLayout.isActivated()){....  }  }


问:
Auto-increment not created
domain class

```<code>package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}
</code>```

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

答:
If you're using Grails and you're happy with the primary key named id you don't need to specify any of the info you've specified. Grails will take care of the auto-increment strategy based on your underlying DB.

Again if you're happy with the table name team you don't need to add anything to mapping related to this.

You've specified you're okay having a null name which may not be correct as you'll end up with rows with just a primary key.

You should also go with a non-pluralised name for your table i.e. team.

```<code>package testgrails12

    class Team {

    String name

    static mapping = {
        version false
    }

    static constraints = {
        name nullable: true
    }
}
</code>```

Title: Auto-increment not created

Body:
domain class

package testgrails12

class Teams {
    Integer id
    String name
    static mapping = {
        table 'teams'
        version false
        name column: 'name', sqlType: 'VARCHAR(200)'
        id generator: 'increment',
                params: [table:'teams', column: 'idteam', sqlType: 'INT(10)', updateable: false, insertable: false]
        /*id column: 'idteam', sqlType: 'INT(11)', updateable: false, insertable: false,
                generator: 'increment'*/
    }
    static constraints = {
        name nullable: true
    }
}

This class creates a table

I need to create a table with a field id auto incremental. Help me whith mapping.

Body:
If you're using Grails and you're happy with the primary key named id you don't need to specify any of the info you've specified. Grails will take care of the auto-increment strategy based on your underlying DB.

Again if you're happy with the table name team you don't need to add anything to mapping related to this.

You've specified you're okay having a null name which may not be correct as you'll end up with rows with just a primary key.

You should also go with a non-pluralised name for your table i.e. team.

package testgrails12

    class Team {

    String name

    static mapping = {
        version false
    }

    static constraints = {
        name nullable: true
    }
}


问:
React Router 4 + Redux 5 Actions not passing to Reducer
I have a react project using react-router 4 and redux 5
if i make a simple axios request i can receive data but when trying to pass it to the reducers i get the reducer call back but without the data from the action nor do i see it in my store. so i am trying to figure out how to receive that data back. in the console log i get back 2 messages from the reducer. the firt is @@redux/INIT and the second is: @@redux/PROBE_UNKNOWN_ACTION_1.d.5.t.z.5

index.js:

```<code>  import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

// Redux
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'; // Redux Dev Tools for Chrome
import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';
import { Provider } from 'react-redux';

// Redux Promise Middleware
import promiseMiddleware from 'redux-promise-middleware';

// Redux Thunk Middleware for Action Creators
import thunk from 'redux-thunk';

// React Router 4
import createHistory from 'history/createBrowserHistory';

import reducers from './reducers';

// import configureStore from './reducers/configureStore';
// const store = configureStore();

const history = createHistory()
const middleware = routerMiddleware(history)

const store = createStore(combineReducers({...reducers, router: routerReducer}),
  composeWithDevTools(applyMiddleware(promiseMiddleware(),thunk)));

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);
</code>```

index.js (rootReducer)

```<code>import { combineReducers } from 'redux';
import adverts from './adverts_reducer';

const rootReducer = combineReducers({
  adverts,
});

export default rootReducer;
</code>```

reducer file:

```<code>import { FETCH_ADVERTS } from '../actions/adverts_action';

export default function(state = {}, action) {
  console.log('Reducer found', action);

  switch(action.type) {
    case FETCH_ADVERTS:
      return {
        adverts: action.payload.result,
        ...state
      };
  }
  return state;
}
</code>```

action file:

```<code>import axios from 'axios';

const ROOT_URL = `https://somecoolurltopullin`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
  const url = `${ROOT_URL}/images/`;
  const request = axios.get(url);

  console.log('Action Request:', request);

  return {
    type: FETCH_ADVERTS,
    payload: request
  };
}
</code>```

EDIT:

actioncreator:

```<code>import axios from 'axios';

const ROOT_URL = `urlhere`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
 const url = `${ROOT_URL}/images`;
 return function (dispatch) {

     const request = axios.get(url)
     .then(result=>{
          console.log('Action Request:', request);

          dispatch({
             type: FETCH_ADVERTS,
             payload: request
          });
      })
      .catch(err=>{
          // handle the err
      })
  }
}
</code>```

答:
you missing the disaotch on your actions file, after you execute the api method you should dispatch the result to the reducers.
in your reduce you use the name: FETCH_ADVERTS.

please add dispatch before you return the response

```<code>import axios from 'axios';

const ROOT_URL = `https://somecoolurltopullin`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
  const url = `${ROOT_URL}/images/`;
  return function (dispatch) {

     const request = axios.get(url)
         .then(result=>{
              console.log('Action Request:', request);

              dispatch({
                 type: FETCH_ADVERTS,
                 payload: result
              });
          })
          .catch(err=>{
              // handle the err
          })
  }
}
</code>```

with that change i also recmoended to make your api action async and the dispatch method on the return of your api get respone, something like that:

```<code>api.getData().then(rsult=>{
 dispatch({type: FETCH_ADVERTS,payload: request});
})
.catch(err=>{
// do something for err handling
})
</code>```

if it help you please vote
Thanks Hod

Body:
I have a react project using react-router 4 and redux 5
if i make a simple axios request i can receive data but when trying to pass it to the reducers i get the reducer call back but without the data from the action nor do i see it in my store. so i am trying to figure out how to receive that data back. in the console log i get back 2 messages from the reducer. the firt is @@redux/INIT and the second is: @@redux/PROBE_UNKNOWN_ACTION_1.d.5.t.z.5

index.js:

  import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

// Redux
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'; // Redux Dev Tools for Chrome
import { ConnectedRouter, routerReducer, routerMiddleware } from 'react-router-redux';
import { Provider } from 'react-redux';

// Redux Promise Middleware
import promiseMiddleware from 'redux-promise-middleware';

// Redux Thunk Middleware for Action Creators
import thunk from 'redux-thunk';

// React Router 4
import createHistory from 'history/createBrowserHistory';

import reducers from './reducers';

// import configureStore from './reducers/configureStore';
// const store = configureStore();

const history = createHistory()
const middleware = routerMiddleware(history)

const store = createStore(combineReducers({...reducers, router: routerReducer}),
  composeWithDevTools(applyMiddleware(promiseMiddleware(),thunk)));

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

index.js (rootReducer)

import { combineReducers } from 'redux';
import adverts from './adverts_reducer';

const rootReducer = combineReducers({
  adverts,
});

export default rootReducer;

reducer file:

import { FETCH_ADVERTS } from '../actions/adverts_action';

export default function(state = {}, action) {
  console.log('Reducer found', action);

  switch(action.type) {
    case FETCH_ADVERTS:
      return {
        adverts: action.payload.result,
        ...state
      };
  }
  return state;
}

action file:

import axios from 'axios';

const ROOT_URL = `https://somecoolurltopullin`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
  const url = `${ROOT_URL}/images/`;
  const request = axios.get(url);

  console.log('Action Request:', request);

  return {
    type: FETCH_ADVERTS,
    payload: request
  };
}

EDIT:

actioncreator:

import axios from 'axios';

const ROOT_URL = `urlhere`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
 const url = `${ROOT_URL}/images`;
 return function (dispatch) {

     const request = axios.get(url)
     .then(result=>{
          console.log('Action Request:', request);

          dispatch({
             type: FETCH_ADVERTS,
             payload: request
          });
      })
      .catch(err=>{
          // handle the err
      })
  }
}

Body:
you missing the disaotch on your actions file, after you execute the api method you should dispatch the result to the reducers.
in your reduce you use the name: FETCH_ADVERTS.

please add dispatch before you return the response

import axios from 'axios';

const ROOT_URL = `https://somecoolurltopullin`;

export const FETCH_ADVERTS = 'FETCH_ADVERTS';

export function fetchHomepageAdverts() {
  const url = `${ROOT_URL}/images/`;
  return function (dispatch) {

     const request = axios.get(url)
         .then(result=>{
              console.log('Action Request:', request);

              dispatch({
                 type: FETCH_ADVERTS,
                 payload: result
              });
          })
          .catch(err=>{
              // handle the err
          })
  }
}

with that change i also recmoended to make your api action async and the dispatch method on the return of your api get respone, something like that:

api.getData().then(rsult=>{
 dispatch({type: FETCH_ADVERTS,payload: request});
})
.catch(err=>{
// do something for err handling
})

if it help you please vote
Thanks Hod


问:
Fastest way to assign item from a list to another item in a list
I've two class which is product and order, please look at the class attribute blow

```<code>public class Product()
{
  public int ProductId { get;set; }
  public string ProductName { get;set; }
  public List<Order> OrderList { get;set; }
}

public class Order()
{
  public int OrderId { get;set; }
  public int ProductId { get;set; }
  public string OrderNumber { get;set; }
  public string OrderDescription { get;set; }
}
</code>```

and i have a separate call to get the data from each of the class

```<code>var productList = ProductService.GetAllProductList();
var orderList = OrderService.GetAllOrderList();
</code>```

What i'm trying to achieve here is that i want to assign order list object to product, i can achieve this by doing like below

```<code>  foreach(var product in productList)
  {
     var selectedOrderList = orderList.Where(x => x.ProductId = product.ProductId).ToList();
     product.OrderList = selectedOrderList;
  }
</code>```

Imaging if my product and order has large amount of data, it could caused some performance issue.

It's because we are doing unnecessary lookup in orderList as some of the order data is already assigned.

Is there any better way to achieve this ?

答:
It's because we are doing unnecessary lookup in orderList

I would not call it unnecessary, but for sure it is inefficient due to linear time complexity of the LINQ to Objects Where method, leading to O(N * M) complexity of the processing algorithm.

So you need a fast alternative, and the easiest standard (and quite efficient hash based implementation) is to build and use Orders lookup by ProductId using ToLookup method, which will trim the time complexity to O(N + M):

```<code>var ordersByProductId = orderList.ToLookup(order => order.ProductId);
foreach (var product in productList)
     product.OrderList = ordersByProductId[product.ProductId].ToList();
</code>```

Body:
I've two class which is product and order, please look at the class attribute blow

public class Product()
{
  public int ProductId { get;set; }
  public string ProductName { get;set; }
  public List<Order> OrderList { get;set; }
}

public class Order()
{
  public int OrderId { get;set; }
  public int ProductId { get;set; }
  public string OrderNumber { get;set; }
  public string OrderDescription { get;set; }
}

and i have a separate call to get the data from each of the class

var productList = ProductService.GetAllProductList();
var orderList = OrderService.GetAllOrderList();

What i'm trying to achieve here is that i want to assign order list object to product, i can achieve this by doing like below

  foreach(var product in productList)
  {
     var selectedOrderList = orderList.Where(x => x.ProductId = product.ProductId).ToList();
     product.OrderList = selectedOrderList;
  }

Imaging if my product and order has large amount of data, it could caused some performance issue.

It's because we are doing unnecessary lookup in orderList as some of the order data is already assigned.

Is there any better way to achieve this ?

Body:
It's because we are doing unnecessary lookup in orderList

I would not call it unnecessary, but for sure it is inefficient due to linear time complexity of the LINQ to Objects Where method, leading to O(N * M) complexity of the processing algorithm.

So you need a fast alternative, and the easiest standard (and quite efficient hash based implementation) is to build and use Orders lookup by ProductId using ToLookup method, which will trim the time complexity to O(N + M):

var ordersByProductId = orderList.ToLookup(order => order.ProductId);
foreach (var product in productList)
     product.OrderList = ordersByProductId[product.ProductId].ToList();


问:
How to retrieve arraylist from firebase database in recyclerview in android studio?
I want to populate my recyclerview from the data stored on firebase database.I tried searching net but most the examples have simple json tree structure and my Json db has following format:

and my android code is as follows:

ModelClass.java

```<code>package com.example.android.directory;

import java.util.ArrayList;

public class ModelClass {

    private ArrayList<CategoryList> categoryList;

    public ModelClass(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public  static class CategoryList{
        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList(int category_id, String category_name, ArrayList<String> emails,
                            ArrayList<String> epabx, ArrayList<String> category_Fax, ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }
    }

    public static class Persons{
        private int Person_ID;
        private String Name;
        private String Designation;
        private String Office_Phone;
        private String Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;

        public Persons(int person_ID, String name, String designation, String office_Phone,
                       String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
        }

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public String getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(String office_Phone) {
            Office_Phone = office_Phone;
        }

        public String getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(String residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.android.directory.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar">
    </include>

    <EditText android:id="@+id/inputSearchMain"
        android:layout_below="@id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/edit_text_search"
        android:hint="@string/searchtext_hint"
        android:padding="5dp"
        android:textColor="#233343"
        android:inputType="textVisiblePassword"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:drawableRight="@drawable/search"/>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@id/inputSearchMain"
        android:id="@+id/recyclerView_Main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>
</code>```

cardview_row_main.xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp">

            <ImageView
                android:id="@+id/govt_logo_Main"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/logo"
                android:layout_centerVertical="true"/>
            <TextView
                android:id="@+id/category_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textSize="14sp"
                android:textColor="#233343"
                android:layout_centerInParent="true"/>
            <ImageView
                android:id="@+id/nextMain"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/next"
                android:background="#1DE9B6"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"/>

        </RelativeLayout>

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

</RelativeLayout>
</code>```

MainActivity.java

```<code>package com.example.android.directory;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference databaseCategory;
    private ArrayList<ModelClass.CategoryList> mcategoryset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseCategory= FirebaseDatabase.getInstance().getReference().child("Category");
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<ModelClass,CategoryViewHolder>firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<ModelClass, CategoryViewHolder>(
                ModelClass.class, R.layout.cardview_row_main,CategoryViewHolder.class,databaseCategory
        ) {
            @Override
            protected void populateViewHolder(CategoryViewHolder viewHolder, ModelClass model, int position) {
                viewHolder.category_name.setText(model.getCategoryList().get);
            }
        };
        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }
}
</code>```

How should i retrieve "Category_name" from the firebase database in this activity?

答:
1. Get instance of DatabaseReference

DatabaseReference mDatabase = FirebaseApplication.getFirebaseDbInstance();

2 .Set Firebase db listener

mDatabase.addChildEventListener(childEventListener);

ChildEventListener childEventListener = new ChildEventListener()

```<code>{
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot)
    {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onCancelled(DatabaseError databaseError)
    {
     //empty
    }
};
</code>```

DataSnapshot will give you list of data

Body:
I want to populate my recyclerview from the data stored on firebase database.I tried searching net but most the examples have simple json tree structure and my Json db has following format:

and my android code is as follows:

ModelClass.java

package com.example.android.directory;

import java.util.ArrayList;

public class ModelClass {

    private ArrayList<CategoryList> categoryList;

    public ModelClass(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public ArrayList<CategoryList> getCategoryList() {
        return categoryList;
    }

    public void setCategoryList(ArrayList<CategoryList> categoryList) {
        this.categoryList = categoryList;
    }

    public  static class CategoryList{
        public int Category_id;
        public String Category_name;
        public ArrayList<String>Emails;
        public ArrayList<String>Epabx;
        public ArrayList<String>Category_Fax;
        public ArrayList<Persons> persons;

        public CategoryList(int category_id, String category_name, ArrayList<String> emails,
                            ArrayList<String> epabx, ArrayList<String> category_Fax, ArrayList<Persons> persons) {
            Category_id = category_id;
            Category_name = category_name;
            Emails = emails;
            Epabx = epabx;
            Category_Fax = category_Fax;
            this.persons = persons;
        }

        public int getCategory_id() {
            return Category_id;
        }

        public void setCategory_id(int category_id) {
            Category_id = category_id;
        }

        public String getCategory_name() {
            return Category_name;
        }

        public void setCategory_name(String category_name) {
            Category_name = category_name;
        }

        public ArrayList<String> getEmails() {
            return Emails;
        }

        public void setEmails(ArrayList<String> emails) {
            Emails = emails;
        }

        public ArrayList<String> getEpabx() {
            return Epabx;
        }

        public void setEpabx(ArrayList<String> epabx) {
            Epabx = epabx;
        }

        public ArrayList<String> getCategory_Fax() {
            return Category_Fax;
        }

        public void setCategory_Fax(ArrayList<String> category_Fax) {
            Category_Fax = category_Fax;
        }

        public ArrayList<Persons> getPersons() {
            return persons;
        }

        public void setPersons(ArrayList<Persons> persons) {
            this.persons = persons;
        }
    }

    public static class Persons{
        private int Person_ID;
        private String Name;
        private String Designation;
        private String Office_Phone;
        private String Residence_Phone;
        private String VOIP;
        private String Address;
        private ArrayList<String>Fax;
        private String Ext;

        public Persons(int person_ID, String name, String designation, String office_Phone,
                       String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
            Person_ID = person_ID;
            Name = name;
            Designation = designation;
            Office_Phone = office_Phone;
            Residence_Phone = residence_Phone;
            this.VOIP = VOIP;
            Address = address;
            Fax = fax;
            Ext = ext;
        }

        public int getPerson_ID() {
            return Person_ID;
        }

        public void setPerson_ID(int person_ID) {
            Person_ID = person_ID;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getDesignation() {
            return Designation;
        }

        public void setDesignation(String designation) {
            Designation = designation;
        }

        public String getOffice_Phone() {
            return Office_Phone;
        }

        public void setOffice_Phone(String office_Phone) {
            Office_Phone = office_Phone;
        }

        public String getResidence_Phone() {
            return Residence_Phone;
        }

        public void setResidence_Phone(String residence_Phone) {
            Residence_Phone = residence_Phone;
        }

        public String getVOIP() {
            return VOIP;
        }

        public void setVOIP(String VOIP) {
            this.VOIP = VOIP;
        }

        public String getAddress() {
            return Address;
        }

        public void setAddress(String address) {
            Address = address;
        }

        public ArrayList<String> getFax() {
            return Fax;
        }

        public void setFax(ArrayList<String> fax) {
            Fax = fax;
        }

        public String getExt() {
            return Ext;
        }

        public void setExt(String ext) {
            Ext = ext;
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_card_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.android.directory.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar">
    </include>

    <EditText android:id="@+id/inputSearchMain"
        android:layout_below="@id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/edit_text_search"
        android:hint="@string/searchtext_hint"
        android:padding="5dp"
        android:textColor="#233343"
        android:inputType="textVisiblePassword"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:drawableRight="@drawable/search"/>

    <android.support.v7.widget.RecyclerView
        android:layout_below="@id/inputSearchMain"
        android:id="@+id/recyclerView_Main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

cardview_row_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView_mainActivity"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingLeft="10dp">

            <ImageView
                android:id="@+id/govt_logo_Main"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/logo"
                android:layout_centerVertical="true"/>
            <TextView
                android:id="@+id/category_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:textSize="14sp"
                android:textColor="#233343"
                android:layout_centerInParent="true"/>
            <ImageView
                android:id="@+id/nextMain"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:src="@drawable/next"
                android:background="#1DE9B6"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"/>

        </RelativeLayout>

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

</RelativeLayout>

MainActivity.java

package com.example.android.directory;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    DatabaseReference databaseCategory;
    private ArrayList<ModelClass.CategoryList> mcategoryset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseCategory= FirebaseDatabase.getInstance().getReference().child("Category");
        recyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<ModelClass,CategoryViewHolder>firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<ModelClass, CategoryViewHolder>(
                ModelClass.class, R.layout.cardview_row_main,CategoryViewHolder.class,databaseCategory
        ) {
            @Override
            protected void populateViewHolder(CategoryViewHolder viewHolder, ModelClass model, int position) {
                viewHolder.category_name.setText(model.getCategoryList().get);
            }
        };
        recyclerView.setAdapter(firebaseRecyclerAdapter);
    }
}

How should i retrieve "Category_name" from the firebase database in this activity?

Body:
1. Get instance of DatabaseReference

DatabaseReference mDatabase = FirebaseApplication.getFirebaseDbInstance();

2 .Set Firebase db listener

mDatabase.addChildEventListener(childEventListener);

ChildEventListener childEventListener = new ChildEventListener()

{
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot)
    {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s)
    {

    }

    @Override
    public void onCancelled(DatabaseError databaseError)
    {
     //empty
    }
};

DataSnapshot will give you list of data


问:
Select same table twice, in single query
My table:

```<code>id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12
</code>```

I need to calculate visit count difference between days something like this

```<code>2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...
</code>```

I managed to get similar results, but not exatcly what i wanted

```<code>$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "<br/>";
        echo "{$dat1}-->Visitors:{$y}";
        echo "<br/>";
        echo "Difference between days:{$d}";
        echo "<br/><br/><br/>";
    }
}
</code>```

So i guess i need to select same table twice with one query.

答:
Group and order by the date. Then you can use a variable to store the last view value in it and compare it to the current one.</p>

```<code>select date,
       sum(views) as currentViews
       sum(views) - @previous as viewsDiff,
       @previous := sum(views)
from your_table
cross join (select @previous:= 0) p
group by date
order by date
</code>```

Body:
My table:

id | views | date
1  | 100   | 2017-03-09
2  | 150   | 2017-03-10
3  | 300   | 2017-03-11
4  | 350   | 2017-03-12

I need to calculate visit count difference between days something like this

2017-03-12-->Visitors:350
2017-03-11-->Visitors:300
Difference between days:50

2017-03-11-->Visitors:300
2017-03-10-->Visitors:150
Difference between days:150

2017-03-10-->Visitors:150
2017-03-09-->Visitors:100
Difference between days:50

and so on...

I managed to get similar results, but not exatcly what i wanted

$sql = "SELECT * FROM `table` ORDER BY `table`.`id` DESC";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{

    $t = $row['views'];
    $dat = $row['date'];

    $sql1 = "SELECT * FROM `table` ORDER BY `table`.`id` DESC LIMIT 1, 99";
    $result1 = mysql_query($sql1) or die(mysql_error());
    while($row1 = mysql_fetch_array($result1))
    {

        $y = $row1['views'];
        $dat1 = $row1['date'];

        $d = $t-$y;

        echo "{$dat}-->Visitors:{$t}";
        echo "
";
        echo "{$dat1}-->Visitors:{$y}";
        echo "
";
        echo "Difference between days:{$d}";
        echo "

";
    }
}

So i guess i need to select same table twice with one query.

Body:
Group and order by the date. Then you can use a variable to store the last view value in it and compare it to the current one.

select date,
       sum(views) as currentViews
       sum(views) - @previous as viewsDiff,
       @previous := sum(views)
from your_table
cross join (select @previous:= 0) p
group by date
order by date


问:
Blurry text after using CSS transform: scale(); in Chrome
Seems like there has been a recent update to Google Chrome that causes blurry text after doing a transform: scale(). Specifically I'm doing this:

@-webkit-keyframes bounceIn {
  0% {
    opacity: 0;
    -webkit-transform: scale(.3);
  }

  50% {
    opacity: 1;
    -webkit-transform: scale(1.05);
  }

  70% {
    -webkit-transform: scale(.9);
  }

  100% {
    -webkit-transform: scale(1);
  }
}
```

If you visit http://rourkery.com in Chrome, you should see the problem on the main text area. It didn't used to do this and it doesn't seem to effect other webkit browsers (like Safari). There were some other posts about people experiencing a similar issue with 3d transforms, but can't find anything about 2d transforms like this.

Any ideas would be appreciated, thanks!

答:
This must be a bug with Chrome (Version 56.0.2924.87), but the below fixes the bluriness for me when changing css properties in the console('.0'). I'll report it.</p>

```<code>filter: blur(.0px)
</code>```

Body:
Seems like there has been a recent update to Google Chrome that causes blurry text after doing a transform: scale(). Specifically I'm doing this:

@-webkit-keyframes bounceIn {
  0% {
    opacity: 0;
    -webkit-transform: scale(.3);
  }

  50% {
    opacity: 1;
    -webkit-transform: scale(1.05);
  }

  70% {
    -webkit-transform: scale(.9);
  }

  100% {
    -webkit-transform: scale(1);
  }
}

If you visit http://rourkery.com in Chrome, you should see the problem on the main text area. It didn't used to do this and it doesn't seem to effect other webkit browsers (like Safari). There were some other posts about people experiencing a similar issue with 3d transforms, but can't find anything about 2d transforms like this.

Any ideas would be appreciated, thanks!

Body:
This must be a bug with Chrome (Version 56.0.2924.87), but the below fixes the bluriness for me when changing css properties in the console('.0'). I'll report it.

filter: blur(.0px)


问:
Uploading of photos in VTiger 6.5 doesn't show up
I installed VTiger 6.5 (patch 4.2). In Contacts modules I added an additional upload feature beside upload profile pic.

enter image description here

In the image, the part encircled in blue is the field I added. Now when I attached picture it is working and saving all picture in the storage folder, but I noticed that It is not saving in the database. Now since it was not saving in the database, the profile pic and the calling card pic in the view is missing.

Link is here, take note that I have this installed in my localhost.

```<code>http://localhost/crm__/index.php?module=Contacts&view=Detail&record=19&mode=showDetailViewByMode&requestMode=full
</code>```

enter image description here

If you needed the code for the contacts.php or rather the controller then I can post it here. But since it was long I'll just skip that part for now and just show u the saving to database part.

```<code>        $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?, ?, ?, ?, ?)";

        $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path);

        $result = $adb->pquery($sql2, $params2);
</code>```

I reall don;t know much how to debug php in Vtiger as I cannot just insert an echo and die.

Thanks for the help.

答:
Please Open this file of c:\xampp\php\php.ini search this line into file

;extension=php_fileinfo.dll and remove semicolon(;) and save it

Body:
I installed VTiger 6.5 (patch 4.2). In Contacts modules I added an additional upload feature beside upload profile pic.

enter image description here

In the image, the part encircled in blue is the field I added. Now when I attached picture it is working and saving all picture in the storage folder, but I noticed that It is not saving in the database. Now since it was not saving in the database, the profile pic and the calling card pic in the view is missing.

Link is here, take note that I have this installed in my localhost.

http://localhost/crm__/index.php?module=Contacts&view=Detail&record=19&mode=showDetailViewByMode&requestMode=full

enter image description here

If you needed the code for the contacts.php or rather the controller then I can post it here. But since it was long I'll just skip that part for now and just show u the saving to database part.

        $sql2 = "insert into vtiger_attachments(attachmentsid, name, description, type, path) values(?, ?, ?, ?, ?)";

        $params2 = array($current_id, $filename, $this->column_fields['description'], $filetype, $upload_file_path);

        $result = $adb->pquery($sql2, $params2);

I reall don;t know much how to debug php in Vtiger as I cannot just insert an echo and die.

Thanks for the help.


问:
Changing Input Of Invisible Neiron
I am trying to make a neiron net on Python. I have already make two classes: Neiron(it's an analogue of Invisible Neiron) and InputNeiron. Input Neiron works well but Neiron not.
The problem is that after Operate() Input of this Neiron change. How can i fix it? What is it caused by? (I am new in programming and i am not English native speaker :D )
Code here:

```<code>  import random
import math

class Neiron():
 Input = 0
 TargetNeiron = {}
 def Func(self, x):
  return (1/(1+ math.exp(-1*x)))
 def __init__(self, *neirons):
  for neiron in neirons:
   self.TargetNeiron[neiron] = random.triangular(0,100)
 def Operate(self):
  a = self.Func(self.Input)
  print(a)
  for neiron in self.TargetNeiron:
   neiron.Input = neiron.Input + (self.TargetNeiron[neiron] * a)

class InputNeiron(Neiron):
 def Func(self, x):
  if str(type(x)) == "<class 'str'>":
   return 1;
  else:
   if x < 1:
    return x;
   else:
    return 1/x;

b = Neiron()
a = Neiron(b);
c = InputNeiron(b,a)

try:
 c.Input = float(input('Input = '))
except:
 c.Input = 1;

print('target Neirons of c, first b, second a:',c.TargetNeiron)
print('Input of a before c.Operate:', a.Input)
print('Input of b before c.Operate:', b.Input)
c.Operate()
print('Input of a after c.Operate:', a.Input)
print('Input of b after c.Operate:', b.Input)
a.Operate()
print('Input of a after a.Operate:', a.Input)
print('Input of b after a.Operate:', b.Input)
</code>```

Neiron(a) or InputNeiron(a) means that this neiron will be connected to a.
TargetNeirons is a dictionary with {neiron: synaptic multiplier} paars. Func is a special function. She is different for Neiron and InputNeiron.

答:
The reason that the Input field of your Neiron changes after each call of n.Operate() is this peace of code, which changes it..

```<code>for neiron in self.TargetNeiron:
  neiron.Input = neiron.Input + (self.TargetNeiron[neiron] * a)
</code>```

As for the 'how can I fix it?' I suppose you could overwrite the Operate function for the InputNeiron class if you want to keep only the input for c constant, otherwise you would have to change the function Operate in the Neiron class to leave neiron.Input alone.

In general I would highly recommend you check out existing implementations of artificial neural nets for example at scikit learn.

hope this helps

Title: Changing Input Of Invisible Neiron

Body:
I am trying to make a neiron net on Python. I have already make two classes: Neiron(it's an analogue of Invisible Neiron) and InputNeiron. Input Neiron works well but Neiron not.
The problem is that after Operate() Input of this Neiron change. How can i fix it? What is it caused by? (I am new in programming and i am not English native speaker :D )
Code here:

  import random
import math

class Neiron():
 Input = 0
 TargetNeiron = {}
 def Func(self, x):
  return (1/(1+ math.exp(-1*x)))
 def __init__(self, *neirons):
  for neiron in neirons:
   self.TargetNeiron[neiron] = random.triangular(0,100)
 def Operate(self):
  a = self.Func(self.Input)
  print(a)
  for neiron in self.TargetNeiron:
   neiron.Input = neiron.Input + (self.TargetNeiron[neiron] * a)

class InputNeiron(Neiron):
 def Func(self, x):
  if str(type(x)) == "<class 'str'>":
   return 1;
  else:
   if x < 1:
    return x;
   else:
    return 1/x;

b = Neiron()
a = Neiron(b);
c = InputNeiron(b,a)

try:
 c.Input = float(input('Input = '))
except:
 c.Input = 1;

print('target Neirons of c, first b, second a:',c.TargetNeiron)
print('Input of a before c.Operate:', a.Input)
print('Input of b before c.Operate:', b.Input)
c.Operate()
print('Input of a after c.Operate:', a.Input)
print('Input of b after c.Operate:', b.Input)
a.Operate()
print('Input of a after a.Operate:', a.Input)
print('Input of b after a.Operate:', b.Input)

Neiron(a) or InputNeiron(a) means that this neiron will be connected to a.
TargetNeirons is a dictionary with {neiron: synaptic multiplier} paars. Func is a special function. She is different for Neiron and InputNeiron.

Body:
The reason that the Input field of your Neiron changes after each call of n.Operate() is this peace of code, which changes it..

for neiron in self.TargetNeiron:
  neiron.Input = neiron.Input + (self.TargetNeiron[neiron] * a)

As for the 'how can I fix it?' I suppose you could overwrite the Operate function for the InputNeiron class if you want to keep only the input for c constant, otherwise you would have to change the function Operate in the Neiron class to leave neiron.Input alone.

In general I would highly recommend you check out existing implementations of artificial neural nets for example at scikit learn.

hope this helps


问:
ActiveAdmin Register Page Batch Action
I have Custom page "All Posts"
Can i integrate batch action into this custom page for assigning the post to a particular category

```<code>ActiveAdmin.register_page "All Posts" do
  menu :priority => 1#, label: proc{ I18n.t("active_admin.dashboard")    }
  content do #title: proc{ I18n.t("active_admin.dashboard") }
      #how can i put here a batch action
  end
end
</code>```

how can i put here a batch action as it gives errors when i write the batch action for resource code.

should i write the page_action and then customize it using javascript and partials.

Thanks in advance

答:
You can try to add batch_action by

```<code>  batch_action :export do |selection|
    keys = Model.find()
    redirect_to admin_path_to_page_with_category_selection_path(post_ids: selection)
  end
</code>```

and selectable column

```<code>  index download_links: [:xlsx] do
    selectable_column
    .....
  end
</code>```

admin_path_to_page_with_category_selection_path goes to view with category combobox, selected posts and submit button

Title: ActiveAdmin Register Page Batch Action

Body:
I have Custom page "All Posts"
Can i integrate batch action into this custom page for assigning the post to a particular category

ActiveAdmin.register_page "All Posts" do
  menu :priority => 1#, label: proc{ I18n.t("active_admin.dashboard")    }
  content do #title: proc{ I18n.t("active_admin.dashboard") }
      #how can i put here a batch action
  end
end

how can i put here a batch action as it gives errors when i write the batch action for resource code.

should i write the page_action and then customize it using javascript and partials.

Thanks in advance

Body:
You can try to add batch_action by

  batch_action :export do |selection|
    keys = Model.find()
    redirect_to admin_path_to_page_with_category_selection_path(post_ids: selection)
  end

and selectable column

  index download_links: [:xlsx] do
    selectable_column
    .....
  end

admin_path_to_page_with_category_selection_path goes to view with category combobox, selected posts and submit button


问:
How to tackle this session problem in ASP.NET,VB.NET?
How to tackle this session problem in ASP.NET,VB.NET?

The following requirement are there:

When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.

The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".

When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.

Problem scenario:

When the user closes the browser the flag remains the same, that is, "1".

When power gets off, it remains the same as "1".

If the session timeouts after a predefined value it remains the same.

There may be different scenarios other than this.

Is there any way so that we can store this internal flagging for the user's login status using the application object?

It may improve efficiency of the system and also eliminates the above problematic scenarios.

答:
From a very top level view, here is what you can do

Use Cache with SlidingExpiration.

Everytime a user attempts login, check the cache with his username as the key. If an entry exists in the cache, you can say that user is already logged in and deny login.

If the key is not found, allow login and create a new key in the cache as the username and set the sliding expiration time. (This should be carefully chosen as this would be the duration, the user wouldnt be locked out after the browser is closed and user attempts to relogin.)

In the Application_PreRequestHandlerExecute handler in Global, check if the user is currently active (you can use sessions for this), reset the sliding expiration time for the user. This way, with each page request the cache expiration time would be reset.

If the user closes the browser and moves off, the cache would expire after the set period of time, and would free the user to log in again.

if in case the user attempts to login again before the cache expires, the user would have to wait for some time to let the cache expire.

if the user logs off properly, you can remove the cache entry on the logoff event such that user doesnt have to wait to relogin.

The Sliding expiration timeout can be synced with session timeout to emulate the actual session timeout for the application.

With this approach, you would also save on a lot of database round trips to update/check the user status and this would work irrespective of the hosting enviornment or the session modes.

ContentLicense: CC BY-SA 2.5


问:
How to add links to featherlight gallery afterContent
I use the afterContent functunality to add captions to a gallery.

```<code><script>
$(document).ready(function(){
  $('.all-imgs').featherlightGallery({
    filter: ".img-box-img a",
    afterContent: function() {
        var caption = this.$currentTarget.find('img').attr('data-caption');
        this.$instance.find('.caption').remove();
        $('<div class="caption">').text(caption).appendTo(this.$instance.find('.featherlight-content'));
    },
    variant: "featherlight-gallery2",
  });
});
</script>
</code>```

How do I have to escape links in the img elements data-caption attribute so that the browser renders them as links?

My usecase is to add a link to the fullsize image in the gallery.

Thanks

答:
If your data-caption attribute contains HTML, change the call to .text(caption) to .html(caption)

In your full example:

```<code><script>
$(document).ready(function(){
  $('.all-imgs').featherlightGallery({
    filter: ".img-box-img a",
    afterContent: function() {
        var caption = this.$currentTarget.find('img').attr('data-caption');
        this.$instance.find('.caption').remove();
        $('<div class="caption">').html(caption).appendTo(this.$instance.find('.featherlight-content'));
    },
    variant: "featherlight-gallery2",
  });
});
</script>
</code>```

Body:
I use the afterContent functunality to add captions to a gallery.

How do I have to escape links in the img elements data-caption attribute so that the browser renders them as links?

My usecase is to add a link to the fullsize image in the gallery.

Thanks

Body:
If your data-caption attribute contains HTML, change the call to .text(caption) to .html(caption)

In your full example:

<script>
$(document).ready(function(){
  $('.all-imgs').featherlightGallery({
    filter: ".img-box-img a",
    afterContent: function() {
        var caption = this.$currentTarget.find('img').attr('data-caption');
        this.$instance.find('.caption').remove();
        $('<div class="caption">').html(caption).appendTo(this.$instance.find('.featherlight-content'));
    },
    variant: "featherlight-gallery2",
  });
});
</script>


问:
How to generate a PKCS12 (.p12) from a .SPC (code signing certificate) and .PKCS12 (private key)?
I have a code-signing certificate (SPC) file from GoDaddy. The file was generated from an existing private key:

```<code>-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAvcG2SEalg9pvkTvtMI8cZg07tVA0RuK7LeGlFdk1smXgqrsH
.... snipped ....
MURwR0FXgNAuFNQ0yBNFNW2+o9uBceLuCSUalgi4pQw1uBmP5QkUYA==
-----END RSA PRIVATE KEY-----
</code>```

I generated a certificate signing request and sent this to GoDaddy:

```<code>-----BEGIN CERTIFICATE REQUEST-----
MIICiDCCAXACAQAwQzFBMD8GCSqGSIb3DQEJARYyYXBwbGVAdGVrNC1uZXdtZWRp
.... snipped ....
nJwd9pSDPuYaNHl33N1BJkXFusG7ta0D6UjisA==
-----END CERTIFICATE REQUEST-----
</code>```

GoDaddy then returned me an SPC file. My research shows that typically you'd have a SPC/PVK pair but obviously my private key isn't of PVK type.
I've tried several methods (pvkimprt, pvk2pfx, openssl, keytool) but can't seem to convert my key to PVK type or my SPC to a PKCS12 type independently without both the certificate (SPC) and private key being in a single key-store.

The command that I appear to need to do this in one step is:
    openssl pkcs12 -in cert_from_godaddy.spc -inkey private.key -export -out full_code_signing_chain.pkcs12

However, running that I just get:
    Loading 'screen' into random state - done
    No certificate matches private key

But, the certificate (SPC) is for the private key. What am I doing wrong?!

Background: I'm trying to generate a .p12 file sign an Adobe AIR application

答:
To create a P12 truststore from a private key and a SPC file do the following steps with OpenSSL:

(Optional): Extract the private key from an old P12 truststore:

openssl pkcs12 -in old.p12 -nocerts -out privateKey.pem

Extract the certificate chain from the SPC file:

openssl pkcs7 -inform DER -outform PEM -in godaddy.spc -print_certs > certificates.pem

Create the new P12 truststore:

openssl pkcs12 -export -out new.p12 -inkey privateKey.pem -in certificates.pem

Body:
I have a code-signing certificate (SPC) file from GoDaddy. The file was generated from an existing private key:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAvcG2SEalg9pvkTvtMI8cZg07tVA0RuK7LeGlFdk1smXgqrsH
.... snipped ....
MURwR0FXgNAuFNQ0yBNFNW2+o9uBceLuCSUalgi4pQw1uBmP5QkUYA==
-----END RSA PRIVATE KEY-----

I generated a certificate signing request and sent this to GoDaddy:

-----BEGIN CERTIFICATE REQUEST-----
MIICiDCCAXACAQAwQzFBMD8GCSqGSIb3DQEJARYyYXBwbGVAdGVrNC1uZXdtZWRp
.... snipped ....
nJwd9pSDPuYaNHl33N1BJkXFusG7ta0D6UjisA==
-----END CERTIFICATE REQUEST-----

GoDaddy then returned me an SPC file. My research shows that typically you'd have a SPC/PVK pair but obviously my private key isn't of PVK type.
I've tried several methods (pvkimprt, pvk2pfx, openssl, keytool) but can't seem to convert my key to PVK type or my SPC to a PKCS12 type independently without both the certificate (SPC) and private key being in a single key-store.

The command that I appear to need to do this in one step is:
    openssl pkcs12 -in cert_from_godaddy.spc -inkey private.key -export -out full_code_signing_chain.pkcs12

However, running that I just get:
    Loading 'screen' into random state - done
    No certificate matches private key

But, the certificate (SPC) is for the private key. What am I doing wrong?!

Background: I'm trying to generate a .p12 file sign an Adobe AIR application


问:
Deadlocks in GraphEngine
Working with GraphEngine for a while I very often find myself with a deadlocked thread while doing some operation against GraphEngine. Nested calls are definitely not on the menu. But now I encountered something strange:

```<code>foreach(long cellID ...)
{
    byte[] buffer;

    // the next line will block on the 54th call...
    Global.LocalStorage.LoadCell(cellID, out buffer);
}
</code>```

Suspecting a non-existing cellID I wrapped the call with

```<code>if(Global.LocalStorage.Contains(cellID))
{ ... }
</code>```

But now  this call blocks indefinitly.

Is this a bug? or

Under which conditions would the call block?

Cheerio,
Andreas.

答:
@Andreas Hassmann, I had met a similar issue, so I guess your trouble may be caused by the ... in the foreach-loop.

I used an iterator like Global.LocalStorage.xxxCell_Accessor_Selector().Select(c => c.CellID.Value). In this case, the locks of the storage haven't been released which causes the deadlock when Global.LocalStorage.LoadCell() acquires the locks.

If your problem is exact the same as mine, the solution will be to apply .ToList() to the iterator.

Here are my codes to reproduce your problem.

The TSL:

```<code>cell struct MyCell
{
    int A;
}
</code>```

The codes:

```<code>for (int i = 0; i < 100; i++)
{
    MyCell mc = new MyCell(i);
    Global.LocalStorage.SaveMyCell(i, mc);
}

var ids = Global.LocalStorage.MyCell_Accessor_Selector().Select(c => c.CellID.Value);

Console.WriteLine("1 start.");
foreach (long cellID in ids.ToList())
{
    byte[] buffer;
    Global.LocalStorage.LoadCell(cellID, out buffer);
    Console.WriteLine(cellID);
}
Console.WriteLine("1 done.");

Console.WriteLine("2 start.");
foreach (long cellID in ids)
{
    byte[] buffer;
    Global.LocalStorage.LoadCell(cellID, out buffer);
    Console.WriteLine(cellID);
}
Console.WriteLine("2 done.");
</code>```

Title: Deadlocks in GraphEngine

Body:
Working with GraphEngine for a while I very often find myself with a deadlocked thread while doing some operation against GraphEngine. Nested calls are definitely not on the menu. But now I encountered something strange:

foreach(long cellID ...)
{
    byte[] buffer;

    // the next line will block on the 54th call...
    Global.LocalStorage.LoadCell(cellID, out buffer);
}

Suspecting a non-existing cellID I wrapped the call with

if(Global.LocalStorage.Contains(cellID))
{ ... }

But now  this call blocks indefinitly.

Is this a bug? or

Under which conditions would the call block?

Cheerio,
Andreas.

Body:
@Andreas Hassmann, I had met a similar issue, so I guess your trouble may be caused by the ... in the foreach-loop.

I used an iterator like Global.LocalStorage.xxxCell_Accessor_Selector().Select(c => c.CellID.Value). In this case, the locks of the storage haven't been released which causes the deadlock when Global.LocalStorage.LoadCell() acquires the locks.

If your problem is exact the same as mine, the solution will be to apply .ToList() to the iterator.

Here are my codes to reproduce your problem.

The TSL:

cell struct MyCell
{
    int A;
}

The codes:

for (int i = 0; i < 100; i++)
{
    MyCell mc = new MyCell(i);
    Global.LocalStorage.SaveMyCell(i, mc);
}

var ids = Global.LocalStorage.MyCell_Accessor_Selector().Select(c => c.CellID.Value);

Console.WriteLine("1 start.");
foreach (long cellID in ids.ToList())
{
    byte[] buffer;
    Global.LocalStorage.LoadCell(cellID, out buffer);
    Console.WriteLine(cellID);
}
Console.WriteLine("1 done.");

Console.WriteLine("2 start.");
foreach (long cellID in ids)
{
    byte[] buffer;
    Global.LocalStorage.LoadCell(cellID, out buffer);
    Console.WriteLine(cellID);
}
Console.WriteLine("2 done.");


问:
How to change the background color of the UIAlertController?
Due to strange behavior of UIActionSheet in iOS 8, I have implemented UIAlertController with UIAction as buttons in it. I would like to change the entire background of the UIAlertController. But I can't find any ways to do it.

Tried even with,

```<code>actionController.view.backgroundColor = [UIColor blackColor];
</code>```

But didn't help me out. Any inputs on this regard will be appreciable.

Thanks in advance.

答:
for Swift 3/ Swift 4

```<code>let subview =(alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView

            subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

            alert.view.tintColor = UIColor.black
</code>```

.

Body:
Due to strange behavior of UIActionSheet in iOS 8, I have implemented UIAlertController with UIAction as buttons in it. I would like to change the entire background of the UIAlertController. But I can't find any ways to do it.

Tried even with,

actionController.view.backgroundColor = [UIColor blackColor];

But didn't help me out. Any inputs on this regard will be appreciable.

Thanks in advance.

Body:
for Swift 3/ Swift 4

let subview =(alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView

            subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

            alert.view.tintColor = UIColor.black

.


问:
Could not load file or assembly after upgrading DevExpress
I've been tearing my hair out over this one, and hopefully it'll be something simple that I'm too thick to work out for myself.

We've got a ASP.NET website (IIS7.5, Server 2008R2) that uses the wonderful DevExpress ASP modules. All was working fine until I had the bright idea of upgrading the modules from 10.1.4 to 10.1.7. Ever since, the site throws intermittent but regular errors that it:

```<code>Could not load file or assembly 'DevExpress.Data.v10.1, Version=10.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
</code>```

All the .aspx files have similar register tags, e.g.:

```<code><%@ Register assembly="DevExpress.Web.ASPxEditors.v10.1" namespace="DevExpress.Web.ASPxEditors" tagprefix="dx" %>
</code>```

I updated the VS2010 project using DevExpress's own upgrader utility. There is no reference to v10.1.4 anywhere in the code - I've checked the .aspx files, web.config etc - and the web server has all the latest .DLL's on too. I've even moved the site to a complete new, virgin server, yet the error still occurs. Specifying the subversion number and public key in the register tag doesn't make any different.

I've iisreset'd, cleared out temporary files, rebooted etc, all to no avail. The really frustrating thing is the error isn't reproducible - sometimes it happens, sometimes it doesn't. Can anyone help me out?

答: Please make certain that the application's bin folder does not contain our old assemblies.  Also, search your project for '10.1.4.0' substring and make sure that this string does not appear.  If this does not help, you must be sure that your application does not reference a dll which references our old assemblies or which is residing in the bin folder.  Finally, a good idea is to clear the Temporary ASP.NET Files Folder ("C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files")...   I hope, this will be helpful.  </p>

Body:
I've been tearing my hair out over this one, and hopefully it'll be something simple that I'm too thick to work out for myself.

We've got a ASP.NET website (IIS7.5, Server 2008R2) that uses the wonderful DevExpress ASP modules. All was working fine until I had the bright idea of upgrading the modules from 10.1.4 to 10.1.7. Ever since, the site throws intermittent but regular errors that it:

Could not load file or assembly 'DevExpress.Data.v10.1, Version=10.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

All the .aspx files have similar register tags, e.g.:

<%@ Register assembly="DevExpress.Web.ASPxEditors.v10.1" namespace="DevExpress.Web.ASPxEditors" tagprefix="dx" %>

I updated the VS2010 project using DevExpress's own upgrader utility. There is no reference to v10.1.4 anywhere in the code - I've checked the .aspx files, web.config etc - and the web server has all the latest .DLL's on too. I've even moved the site to a complete new, virgin server, yet the error still occurs. Specifying the subversion number and public key in the register tag doesn't make any different.

I've iisreset'd, cleared out temporary files, rebooted etc, all to no avail. The really frustrating thing is the error isn't reproducible - sometimes it happens, sometimes it doesn't. Can anyone help me out?


问:
Angular 2 map.set is not a function
I am trying to added some values to my map. For example I have the following,

My AddressBook class

```<code>export class AddressBook {
  constructor(
    public social: Map<string, string> = new Map<string, string>(),

  ) {
  }
}
</code>```

here is what the server is returning,

```<code>{
 social: {
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 }
}
</code>```

This is my method to add to my social map

```<code>this.addressBook.social.set('Google+','GooglePlusId');
</code>```

But I get the following error

```<code>caused by: this.addressBook.social.set is not a function
</code>```

Here is how i retrieve the data from the server

```<code> return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json())
      .catch(this.handleError);

this.addressBookService.getAddressBookFromId(address_book_id)
      .subscribe((res) => {
          this.addressBook = res;

        },
        error => {
          console.log(<any>error);
        });
</code>```

Not sure how to solve this. If anyone can point me the right direction that would be much appreciated. Thanks

答:
try to install @types/core-js module it contains typescript definitions for all es6 features (Map, Set ...) :

```<code>npm install @types/core-js --save

you may need to uninstall @types/es6-promise
</code>```

Title: Angular 2 map.set is not a function

Body:
I am trying to added some values to my map. For example I have the following,

My AddressBook class

export class AddressBook {
  constructor(
    public social: Map<string, string> = new Map<string, string>(),

  ) {
  }
}

here is what the server is returning,

{
 social: {
 twitter: "twitterId",
 facebook: "facebookId",
 linkedIn: "linkedinId",
 pinterest: "pinterestId"
 }
}

This is my method to add to my social map

this.addressBook.social.set('Google+','GooglePlusId');

But I get the following error

caused by: this.addressBook.social.set is not a function

Here is how i retrieve the data from the server

 return this.http.get(this.addressBookURL+address_book_id)
      .map(res => <AddressBook> res.json())
      .catch(this.handleError);

this.addressBookService.getAddressBookFromId(address_book_id)
      .subscribe((res) => {
          this.addressBook = res;

        },
        error => {
          console.log(<any>error);
        });

Not sure how to solve this. If anyone can point me the right direction that would be much appreciated. Thanks

Body:
try to install @types/core-js module it contains typescript definitions for all es6 features (Map, Set ...) :

npm install @types/core-js --save

you may need to uninstall @types/es6-promise