问:
RecyclerView not refreshing after inserting item using Alertdialog
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.

Problem:

(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third  no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.

My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].

but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.

Below is my All Code.

CategoryAdapter

```<code>public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {

        private ArrayList<CategoryModel> dataList;

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategoryItem;

            MyViewHolder(View view) {
                super(view);
                tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
            }
        }

        CategoryAdapter(ArrayList<CategoryModel> dataSet) {
            this.dataList = dataSet;
            this.filterList = dataSet;
        }

        // I used this method too. but same problem.
        void refreshAdapter(ArrayList<CategoryModel> dataSet) {
            dataList.clear();
            dataList.addAll(dataSet);
            notifyDataSetChanged();
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.rv_row_category_list, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            CategoryModel categoryModel = dataList.get(position);
            holder.tvCategoryItem.setText(categoryModel.getCategoryName());
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }
</code>```

CategoryListActivity

```<code>MyDatabase myDb;
            CategoryModel categoryModel;
            RecyclerView recyclerCategory;
            RecyclerView.LayoutManager layoutManager;
            CategoryAdapter adapter;
            ArrayList<CategoryModel> allCategory;
            int CategoryType;

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

    CategoryType = CaseActivity.CategoryType;
    Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

    allCategory = myDb.getCategoryByType(CategoryType);

    if (allCategory.size() == 0) {
        Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);

    recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
            new RecyclerItemClickListener.OnItemTouchListener() {
                @Override
                public void onItemClick(View view, int position) {
                    TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
                    String CategoryName = tvCategoryItem.getText().toString();

                    Intent intent = new Intent();
                    CategoryId = allCategory.get(+position).getCategoryId();
                    intent.putExtra("CategoryId", String.valueOf(CategoryId));

                    Log.e("Clicked Cat Id is ", "" + CategoryId);
                    intent.putExtra("CategoryName", CategoryName);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            }
    ));
}

private void openAlert() {
    final EditText etCategoryName = new EditText(this);

    CustomAlertDialog dialog1 = new CustomAlertDialog(this);
    dialog1.setTitle("Add Category");
    dialog1.setView(etCategoryName);
    dialog1.setCancelable(true);

    dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final String CategoryName = etCategoryName.getText().toString().trim();
            final String storedCategoryName = myDb.ExistCategory(CategoryName);

            if (CategoryName.equals("") && CategoryName.length() == 0) {
                Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
                builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (CategoryName.equals(storedCategoryName)) {
                    Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
                    builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                } else {
                    dialogInterface.dismiss();

                    categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));

                    myDb.createCategory(categoryModel);

                    Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
                            + "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();

                    allCategory.clear();

                    allCategory = myDb.getCategoryByType(CategoryType);

                    adapter.notifyDataSetChanged();

                }
            }
        }
    });
    dialog1.show();
}

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_add:
                    openAlert();
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }
</code>```

my createCategory() method.

```<code>public long createCategory(CategoryModel categoryModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATEGORY_NAME, categoryModel.getCategoryName());
        values.put(CATEGORY_TYPE, categoryModel.getCategoryType());

        long CategoryId = db.insert(TABLE_CATEGORY, null, values);
        db.close();
        return CategoryId;
    }
</code>```

and Finally my getCategoryByType() method on My Database.

```<code>public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
        ArrayList<CategoryModel> Categories = new ArrayList<>();
        // String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
        String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
        Log.e(DB_LOG, selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    CategoryModel categoryModel = new CategoryModel();

                    categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
                    categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
                    categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));

                    Categories.add(categoryModel);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return Categories;
    }
</code>```

Any Type of Help, Suggestion is much Appreciated.....Thanks in advance

Below is Screenshot after adding First Item.

First Item Inserted but not shown in RecycleView

My LogCat Screenshot is below.

Logcat Screenshot

答:
change your onCreate in this way

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

     CategoryType = CaseActivity.CategoryType;
     Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

     allCategory = myDb.getCategoryByType(CategoryType);

     if (allCategory.size() == 0) {
         Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);
}
```

<p>and now you can use <code>adapter.notifyDataSetChanged();</code> without recreation of <code>adapter</code> and set them to <code>RecyclerView</code></p>

<p>if you make in <code>setPositiveButton</code> <code>allCategory = myDb.getCategoryByType(CategoryType);</code> then your reference to <code>allCategory</code> is lost.</p>

<p>you need instead</p>

```allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));
```

Body:
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.

Problem:

(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third  no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.

My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].

but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.

Below is my All Code.

CategoryAdapter

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {

        private ArrayList<CategoryModel> dataList;

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategoryItem;

            MyViewHolder(View view) {
                super(view);
                tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
            }
        }

        CategoryAdapter(ArrayList<CategoryModel> dataSet) {
            this.dataList = dataSet;
            this.filterList = dataSet;
        }

        // I used this method too. but same problem.
        void refreshAdapter(ArrayList<CategoryModel> dataSet) {
            dataList.clear();
            dataList.addAll(dataSet);
            notifyDataSetChanged();
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.rv_row_category_list, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            CategoryModel categoryModel = dataList.get(position);
            holder.tvCategoryItem.setText(categoryModel.getCategoryName());
        }

        @Override
        public int getItemCount() {
            return dataList.size();
        }
    }

CategoryListActivity

MyDatabase myDb;
            CategoryModel categoryModel;
            RecyclerView recyclerCategory;
            RecyclerView.LayoutManager layoutManager;
            CategoryAdapter adapter;
            ArrayList<CategoryModel> allCategory;
            int CategoryType;

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

    CategoryType = CaseActivity.CategoryType;
    Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

    allCategory = myDb.getCategoryByType(CategoryType);

    if (allCategory.size() == 0) {
        Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);

    recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
            new RecyclerItemClickListener.OnItemTouchListener() {
                @Override
                public void onItemClick(View view, int position) {
                    TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
                    String CategoryName = tvCategoryItem.getText().toString();

                    Intent intent = new Intent();
                    CategoryId = allCategory.get(+position).getCategoryId();
                    intent.putExtra("CategoryId", String.valueOf(CategoryId));

                    Log.e("Clicked Cat Id is ", "" + CategoryId);
                    intent.putExtra("CategoryName", CategoryName);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            }
    ));
}

private void openAlert() {
    final EditText etCategoryName = new EditText(this);

    CustomAlertDialog dialog1 = new CustomAlertDialog(this);
    dialog1.setTitle("Add Category");
    dialog1.setView(etCategoryName);
    dialog1.setCancelable(true);

    dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final String CategoryName = etCategoryName.getText().toString().trim();
            final String storedCategoryName = myDb.ExistCategory(CategoryName);

            if (CategoryName.equals("") && CategoryName.length() == 0) {
                Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
                builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (CategoryName.equals(storedCategoryName)) {
                    Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
                    builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                } else {
                    dialogInterface.dismiss();

                    categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));

                    myDb.createCategory(categoryModel);

                    Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
                            + "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();

                    allCategory.clear();

                    allCategory = myDb.getCategoryByType(CategoryType);

                    adapter.notifyDataSetChanged();

                }
            }
        }
    });
    dialog1.show();
}

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_add:
                    openAlert();
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }

my createCategory() method.

public long createCategory(CategoryModel categoryModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATEGORY_NAME, categoryModel.getCategoryName());
        values.put(CATEGORY_TYPE, categoryModel.getCategoryType());

        long CategoryId = db.insert(TABLE_CATEGORY, null, values);
        db.close();
        return CategoryId;
    }

and Finally my getCategoryByType() method on My Database.

public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
        ArrayList<CategoryModel> Categories = new ArrayList<>();
        // String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
        String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
        Log.e(DB_LOG, selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    CategoryModel categoryModel = new CategoryModel();

                    categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
                    categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
                    categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));

                    Categories.add(categoryModel);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return Categories;
    }

Any Type of Help, Suggestion is much Appreciated.....Thanks in advance

Below is Screenshot after adding First Item.

First Item Inserted but not shown in RecycleView

My LogCat Screenshot is below.

Logcat Screenshot

Body:
change your onCreate in this way

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

     CategoryType = CaseActivity.CategoryType;
     Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

     allCategory = myDb.getCategoryByType(CategoryType);

     if (allCategory.size() == 0) {
         Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);
}

and now you can use adapter.notifyDataSetChanged(); without recreation of adapter and set them to RecyclerView

if you make in setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); then your reference to allCategory is lost.

you need instead

allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));


来源: stackexchange

问:
Flowrouter Subscriptions
This is how my flowrouter looks like,
I tried all three options shown below: but unable to subscribe

import {CompanySettings} from '../imports/api/companysettingsMaster.js';
// And imported the api also..
FlowRouter.route('/', {
  name: 'home',
  subscriptions: function() {
    // 1.
    return this.register('companySettings', Meteor.subscribe('companySettings'));
    // 2.
    this.register('CompanySettings', Meteor.subscribe('companySettings'));
    // 3.
    return Meteor.subscribe('companySettings');
  },
  action: function() {

    var themeSettings = CompanySettings.findOne({
      "companyId": 101
    });
    if (themeSettings) {
      console.log(themeSettings);
      var scaleProcess = themeSettings.generalSettings.scaleProcess;

      if (scaleProcess == 'retail')
        BlazeLayout.render("retailMainLayout", {
          content: "homepages"
        });
      else {
        BlazeLayout.render("WSEmainLayout", {
          content: "homepages"
        });
      }
    } else {
      console.log('no themeSettings');
    }

  }
});
```

But, not getting document at the end .. Any suggestions.. Thanks in advance

答:
I got the answer for subscription in flowrouter which is as follows:

```<code>FlowRouter.route('/', {
    waitOn: function () {
       return Meteor.subscribe('companySettings');
    },
});
</code>```

Here companySettings is a name of collection in mongodb

ContentLicense: CC BY-SA 3.0

Title: Flowrouter Subscriptions

Body:
This is how my flowrouter looks like,
I tried all three options shown below: but unable to subscribe

import {CompanySettings} from '../imports/api/companysettingsMaster.js';
// And imported the api also..
FlowRouter.route('/', {
  name: 'home',
  subscriptions: function() {
    // 1.
    return this.register('companySettings', Meteor.subscribe('companySettings'));
    // 2.
    this.register('CompanySettings', Meteor.subscribe('companySettings'));
    // 3.
    return Meteor.subscribe('companySettings');
  },
  action: function() {

    var themeSettings = CompanySettings.findOne({
      "companyId": 101
    });
    if (themeSettings) {
      console.log(themeSettings);
      var scaleProcess = themeSettings.generalSettings.scaleProcess;

      if (scaleProcess == 'retail')
        BlazeLayout.render("retailMainLayout", {
          content: "homepages"
        });
      else {
        BlazeLayout.render("WSEmainLayout", {
          content: "homepages"
        });
      }
    } else {
      console.log('no themeSettings');
    }

  }
});

But, not getting document at the end .. Any suggestions.. Thanks in advance

Body:
I got the answer for subscription in flowrouter which is as follows:

FlowRouter.route('/', {
    waitOn: function () {
       return Meteor.subscribe('companySettings');
    },
});

Here companySettings is a name of collection in mongodb


问:
Can split recursion be done by hand?
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.</p>

```<code>static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}
</code>```

答:
So what you want is the n-th term of the serie : Un = n + U(n-1) + U(n-2).

Since no one mentionned it, here's the tail-recursive version using 2 accumulators, of what you want to do in OCaml :

```<code>let f x =
  let rec f' acc' acc'' i =
    if i = x then i+acc''
    else f' (i+acc'') (i+acc'+acc'') (i+1)
  in f' 1 1 0
</code>```

It's super fast if you're using a langage with tail-call optimization (like hum ... let say OCaml). Since you're not, here's the sad, inelegant, imperative version of it in Java:

```<code>public static int f (int x){
  int acc1 = 1 ,acc2 = 1;
  for (int i = 0; i<x; i++){
    int tmp = acc1;
    acc1 = i+acc2;
    acc2 = i+tmp+acc2;
  }
  return x+acc2;
}
</code>```

As you can see, no need to use memoization or gigantic arrays or complicated things like that. A simple for loop can do the trick :).

You can get all the intermediary results by printing (x+acc2) inside de the body of the loop

Title: Can split recursion be done by hand?

Body:
I have this worksheet problem to work on, and I just don't see how it can be done by hand. Each method calls 2 more methods to run, so each one would call 2 more. I don't know how to keep track of any of it. I don't know how one would even find the answer besides putting it into Eclipse.

static int fun(int x) {
    if(x < 1) {
        return 1;
    } else {
        return x + fun(x-1) + fun(x-2);
    }
}

public static void main(String[] args) {
    System.out.println(fun(4));
}

Body:
So what you want is the n-th term of the serie : Un = n + U(n-1) + U(n-2).

Since no one mentionned it, here's the tail-recursive version using 2 accumulators, of what you want to do in OCaml :

let f x =
  let rec f' acc' acc'' i =
    if i = x then i+acc''
    else f' (i+acc'') (i+acc'+acc'') (i+1)
  in f' 1 1 0

It's super fast if you're using a langage with tail-call optimization (like hum ... let say OCaml). Since you're not, here's the sad, inelegant, imperative version of it in Java:

public static int f (int x){
  int acc1 = 1 ,acc2 = 1;
  for (int i = 0; i<x; i++){
    int tmp = acc1;
    acc1 = i+acc2;
    acc2 = i+tmp+acc2;
  }
  return x+acc2;
}

As you can see, no need to use memoization or gigantic arrays or complicated things like that. A simple for loop can do the trick :).

You can get all the intermediary results by printing (x+acc2) inside de the body of the loop


问:
return sample date between min date and max date in R in a dataframe
How to return sample date between min date and max date in R in a dataframe as an additional column?</p>

```<code>Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017
</code>```

答:
Using dplyr we can do:

library(dplyr)

df <- df %>%
    rowwise() %>%
    mutate(MinEnrollmentDate = as.Date(MinEnrollmentDate, format = '%m/%d/%Y'),
           MaxEnrollmentDate = as.Date(MaxEnrollmentDate, format = '%m/%d/%Y'),
           sampleDate = sample(seq(MinEnrollmentDate, MaxEnrollmentDate, '-1 day'), 1))

df
#> Source: local data frame [5 x 4]
#> Groups: <by row>
#>
#> # A tibble: 5 x 4
#>      Course MinEnrollmentDate MaxEnrollmentDate  sampleDate
#>       <chr>            <date>            <date>      <date>
#> 1     Maths        2016-03-11        2016-03-04  2016-03-08
#> 2 Chemistry        2016-06-11        2016-06-04  2016-06-09
#> 3   Physics        2016-09-11        2016-09-04  2016-09-06
#> 4   English        2016-12-11        2016-12-04  2016-12-09
#> 5   Science        2017-03-11        2017-03-04  2017-03-06
```

<p>Not sure if I got the format of your dates right, it's ambiguous, feel free to correct the <code>format=</code> part.
Data:</p>

<pre class="lang-r prettyprint-override"><code>df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)
</code>```

Body:
How to return sample date between min date and max date in R in a dataframe as an additional column?

Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017

Body:
Using dplyr we can do:

library(dplyr)

df <- df %>%
    rowwise() %>%
    mutate(MinEnrollmentDate = as.Date(MinEnrollmentDate, format = '%m/%d/%Y'),
           MaxEnrollmentDate = as.Date(MaxEnrollmentDate, format = '%m/%d/%Y'),
           sampleDate = sample(seq(MinEnrollmentDate, MaxEnrollmentDate, '-1 day'), 1))

df
#> Source: local data frame [5 x 4]
#> Groups: <by row>
#>
#> # A tibble: 5 x 4
#>      Course MinEnrollmentDate MaxEnrollmentDate  sampleDate
#>       <chr>            <date>            <date>      <date>
#> 1     Maths        2016-03-11        2016-03-04  2016-03-08
#> 2 Chemistry        2016-06-11        2016-06-04  2016-06-09
#> 3   Physics        2016-09-11        2016-09-04  2016-09-06
#> 4   English        2016-12-11        2016-12-04  2016-12-09
#> 5   Science        2017-03-11        2017-03-04  2017-03-06

Not sure if I got the format of your dates right, it's ambiguous, feel free to correct the format= part.
Data:

df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)


问:
The request failed with HTTP status 401: Unauthorized. On a server where other apps use the same service fine
Ok I have a few web apps running on a server.  We will call them A, B and C.  A and B have been modified to use a webservice which does some logging.  I am now trying to add this webservice to app C but I am getting the above error.  I decided to experiment.  I took all of the code from app B which runs everything fine and remove it.  I then took app C and placed that code in that directory to make sure it is not a setting issue with the virtual directory.  App C still does not work and I am running out of ideas.  The code has been compiled in both .NET 2.0 and 3.5 with the same results.

Code for reference.  I have also tried passing in my credentials, this line was left out from below.

```<code>UserLogService.UserActivity TestService = new UserLogService.UserActivity();

TestService.PreAuthenticate = false;

TestService.Credentials = System.Net.CredentialCache.DefaultCredentials;
TestService.InitializeUserActivity();
ReturnValue = TestService.LogEntry("US043401", "VOL", "DQIF", "DEFAULT.ASPX",
                 "Data Source Id=" + ddlDatasource.SelectedItem, "Data Feed Id="
                 + ddlDataFeed.SelectedItem).ToString();
</code>```

答: At the risk of suggesting the obvious, what do the server logs say?</p>

ContentLicense: CC BY-SA 2.5

Body:
Ok I have a few web apps running on a server.  We will call them A, B and C.  A and B have been modified to use a webservice which does some logging.  I am now trying to add this webservice to app C but I am getting the above error.  I decided to experiment.  I took all of the code from app B which runs everything fine and remove it.  I then took app C and placed that code in that directory to make sure it is not a setting issue with the virtual directory.  App C still does not work and I am running out of ideas.  The code has been compiled in both .NET 2.0 and 3.5 with the same results.

Code for reference.  I have also tried passing in my credentials, this line was left out from below.

UserLogService.UserActivity TestService = new UserLogService.UserActivity();

TestService.PreAuthenticate = false;

TestService.Credentials = System.Net.CredentialCache.DefaultCredentials;
TestService.InitializeUserActivity();
ReturnValue = TestService.LogEntry("US043401", "VOL", "DQIF", "DEFAULT.ASPX",
                 "Data Source Id=" + ddlDatasource.SelectedItem, "Data Feed Id="
                 + ddlDataFeed.SelectedItem).ToString();


问:
Early exit from function in a forEach?
How can I early exit from a function in my TypeScript file?

```<code>checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}
</code>```

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.

答:
Another approach, with for loop:

checkIfFollowed() {
  for (let i = 0; i < this.currentUserInfos.followed.length; ++ i) {
    if (18785 == 18785) {
      console.log('its true');
      this.alreadyFollowed = true;
      return; // exit checkIfFollowed() here
    }
  }

  this.alreadyFollowed = false;
  console.log('the end');
  return;
}
```

ContentLicense: CC BY-SA 4.0

Title: Early exit from function in a forEach?

Body:
How can I early exit from a function in my TypeScript file?

checkIfFollowed(){

    this.currentUserInfos.followed.forEach(element => {
        if(18785 == 18785){
            console.log('its true');
            this.alreadyFollowed = true;
            return; // Exit checkIfFollowed() here
        }

    });

    this.alreadyFollowed = false;
    console.log('the end');
    return;
}

When I'm running it, it's executed completely, but it should exit after the first:

'its true'

But in my console, I get:

its true

its true

the end

Foreach loops 2 times as expected, but why the method doesn't stop after hitting a "return"?

I'm not trying to get out of the forEach, but ending the method 'checkIfFollowed' in the foreach.

'the end' should not be printed.


问:
Ant for script how to continue if any iteration fails
I writing an ant build file to check all translate files in a directory.
I want the ant for script to continue checking the rest files if an checking error in any file appear.
My ant task:

```<code>    <taskdef name="validate" classname="ValidateTranslateFile">
        <classpath>
            <pathelement location="${ant-libs-dir}/TranslateFileUtilities.jar" />
            <pathelement location="../web/WEB-INF/lib/commons-io-2.5.jar" />
            <pathelement location="../web/WEB-INF/lib/commons-lang3-3.5.jar" />
        </classpath>
    </taskdef>

    <for param="program">
        <path>
            <fileset dir="../web/WEB-INF" includes="*.txt" />
        </path>
        <sequential>
            <validate targetFile="@{program}" checkLanguages="true" checkKeysOrder="true" />
        </sequential>
    </for>

</target>
</code>```

the Result:
it checks the files till the first error appear, and then the BUILD FAILED.

Could any one help me with that?

答:
The for task is not part of standard ANT. It is a 3rd party extension documented here:

http://ant-contrib.sourceforge.net/tasks/tasks/for.html

The documentation suggests using a "keepgoing" attribute to ignore errors, this might be the answer you're looking for.

If this is a custom ANT task you are writing, perhaps you should consider refactoring the code to operate on a fileset? This would enable you to call task as follows:

```<code><validate checkLanguages="true" checkKeysOrder="true">
  <fileset dir="../web/WEB-INF" includes="*.txt" />
</validate>
</code>```

Simpler and more robust.

Body:
I writing an ant build file to check all translate files in a directory.
I want the ant for script to continue checking the rest files if an checking error in any file appear.
My ant task:

    <taskdef name="validate" classname="ValidateTranslateFile">
        <classpath>
            <pathelement location="${ant-libs-dir}/TranslateFileUtilities.jar" />
            <pathelement location="../web/WEB-INF/lib/commons-io-2.5.jar" />
            <pathelement location="../web/WEB-INF/lib/commons-lang3-3.5.jar" />
        </classpath>
    </taskdef>

    <for param="program">
        <path>
            <fileset dir="../web/WEB-INF" includes="*.txt" />
        </path>
        <sequential>
            <validate targetFile="@{program}" checkLanguages="true" checkKeysOrder="true" />
        </sequential>
    </for>

</target>

the Result:
it checks the files till the first error appear, and then the BUILD FAILED.

Could any one help me with that?

Body:
The for task is not part of standard ANT. It is a 3rd party extension documented here:

http://ant-contrib.sourceforge.net/tasks/tasks/for.html

The documentation suggests using a "keepgoing" attribute to ignore errors, this might be the answer you're looking for.

If this is a custom ANT task you are writing, perhaps you should consider refactoring the code to operate on a fileset? This would enable you to call task as follows:

<validate checkLanguages="true" checkKeysOrder="true">
  <fileset dir="../web/WEB-INF" includes="*.txt" />
</validate>

Simpler and more robust.


问:
Using a struct which implements a traits from a different crate
Crate sha2 contains the type Sha256 which implements the trait Digest defined in the crate digest. This trait is also reexported from sha2.

I want to write a file which doesn't mention sha2, just digest:

merkle_tree.rs:

```<code>use digest::Digest;

#[derive(Default)]
pub struct MerkleTree<T: Digest> {
    digest: T,
}

impl<T: Digest+Default> MerkleTree<T> {
    pub fn new() -> MerkleTree<T> {
        MerkleTree{ ..Default::default() }
    }
}
</code>```

main.rs:

```<code>extern crate digest;
extern crate sha2;

mod merkle_tree;

use sha2::{Digest, Sha256};
use merkle_tree::MerkleTree;

fn main() {
    let mut mt = MerkleTree::<Sha256>::new();
    println!("Hello, world!");
}
</code>```

I have the following output:

error: no associated item named new found for type
  merkle_tree::MerkleTree<sha2::Sha256> in the current scope
  the trait digest::Digest is not implemented for sha2::Sha256

Cargo.toml:

```<code>[package]
name = "merkle_tree"
version = "0.1.0"
authors = ["Simon Prykhodko <semion.ababo@gmail.com>"]

[dependencies]
digest = "0.4.0"
sha2 = "0.3.0"
</code>```

What's wrong here?

答:
The digest you're using and the digest the sha2 crate is using are incompatible.  That they have the same name is irrelevant; as far as the compiler is concerned, you're trying to conflate two entirely different crates.

The quickest way to tell would be to see if digest shows up more than once during compilation, or more than once in your Cargo.lock file.  You can also verify this manually by looking at crate dependencies.  sha2 0.3.0 lists digest 0.3 in its dependencies, and 0.3 is not compatible with 0.4.

You need to either downgrade your crate's dependency on digest, or upgrade your crate's version of sha2 to one that uses a newer version of digest.

Body:
Crate sha2 contains the type Sha256 which implements the trait Digest defined in the crate digest. This trait is also reexported from sha2.

I want to write a file which doesn't mention sha2, just digest:

merkle_tree.rs:

use digest::Digest;

#[derive(Default)]
pub struct MerkleTree<T: Digest> {
    digest: T,
}

impl<T: Digest+Default> MerkleTree<T> {
    pub fn new() -> MerkleTree<T> {
        MerkleTree{ ..Default::default() }
    }
}

main.rs:

extern crate digest;
extern crate sha2;

mod merkle_tree;

use sha2::{Digest, Sha256};
use merkle_tree::MerkleTree;

fn main() {
    let mut mt = MerkleTree::<Sha256>::new();
    println!("Hello, world!");
}

I have the following output:

error: no associated item named new found for type
  merkle_tree::MerkleTree<sha2::Sha256> in the current scope
  the trait digest::Digest is not implemented for sha2::Sha256

Cargo.toml:

[package]
name = "merkle_tree"
version = "0.1.0"
authors = ["Simon Prykhodko <semion.ababo@gmail.com>"]

[dependencies]
digest = "0.4.0"
sha2 = "0.3.0"

What's wrong here?


问:
C# WinForms Model-View-Presenter (Passive View)
I'm developing a WinForms application in C#. I have limited experience in GUI programming, and I am having to learn a great deal on the fly. That being said, here's what I am building.

See the general GUI look at the following link:

GUI http://img227.imageshack.us/img227/1084/program0.jpg

Now, I have done a lot of the work already, but in the very bad Autonomous design pattern. I did not know the project would ever reach a certain size, and, as such, it is time to do some major refactoring.

I have been studying a great deal about GUI design patterns, and the pattern I am wishing to implement is the Passive View (see http://martinfowler.com/eaaDev/PassiveScreen.html). I am looking for some help on how to bring this all together.

Background:

1) Depending on what the user clicks in the "TreeView", the "List" in the bottom left-hand corner will display a list of objects that can populate the "Editor" area. These objects might be a TextBox or a DataGridView. The user toggles the List to choose what he/she wants to see in the "Editor"

2) The model is essentially a folder with data and configuration files. There is an external program that runs on a given directory, creates output files/folders, etc. This program I am developing is designed to effectively manage/configure these objects in a user-friendly way

3) The problem with the way I have been doing things is that it is next to impossible to test, and hence the move to the MVP-esque Passive View design pattern

I am trying to make it so that the program works independently of the View. I have not been able to find any examples where a more complex, interactive view is used with the Passive View pattern.

Questions:

1) Do I need to implement one large interface/view for the entire "look" of the program, then implement sub-interfaces/sub-views for each of the TreeView, Editor, Logger, etc.? Or is there a better "structure" to doing this?

2) When it comes to "handing off" events from the View to the Presenter/Controller (whatever terminology you wish to use W.R.T. the Passive View design pattern), what is the way I should be doing this? Sometimes I have simple properties that need to be updated, and sometimes I need a whole series of steps to unfold.

I would love suggestions and advice on this topic. I have scoured the Internet, and I haven't found adequate examples to help me continue with this project.

Thanks in advance!

Daniel

答:
Here is a simple example that demonstrates the concept of passive views using the MVP design pattern.  Because we are using passive views the view has no knowledge of the presenter.  The presenter will simply subscribe to events published by the view and act accordingly.

To start out we need to define a contract for our view. This is typically achieved using an interface, essentially, we want to have a very loose coupling with our view.  We want the ability to switch to different views or event create mock views for unit testing.

Here is a contract that describes a simple view that will be used to display customer information

```<code>public interface ICustomerManagementView
{
    void InitializeCustomers(ICustomer[] customers);
    void DisplayCustomer(ICustomer customer);
    event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
</code>```

It exposes a single method InitializeCustomers that will be used to initialize our view with objects from our model.

We also have an event SelectedCustomerChanged that will be used by our presenter to receive notification that an action has occurred in the view.

Once we have our contract we can start to handle these interactions in our presenter.

```<code>public class CustomerManagementPresenter
{
    private ICustomer _selectedCustomer;
    private readonly ICustomerManagementView _managementView;
    private readonly ICustomerRepository _customerRepository;

    public CustomerManagementPresenter(ICustomerManagementView managementView, ICustomerRepository customerRepository)
    {
        _managementView = managementView;
        _managementView.SelectedCustomerChanged += this.SelectedCustomerChanged;

        _customerRepository = customerRepository;

        _managementView.InitializeCustomers(_customerRepository.FetchCustomers());
    }

    private void SelectedCustomerChanged(object sender, EventArgs<ICustomer> args)
    {
        // Perform some logic here to update the view
        if(_selectedCustomer != args.Value)
        {
            _selectedCustomer = args.Value;
            _managementView.DisplayCustomer(_selectedCustomer);
        }
    }
}
</code>```

In the presenter we can use another design pattern called dependency injection to provide access to our view and any model classes that we may need. In this example I have a CustomerRepository that is responsible for fetching customer details.

In the constructor we have two important lines of code, firstly we have subscribed to the SelectedCustomerChanged event in our view, it is here that we can perform associated actions. Secondly we have called InitilaizeCustomers with data from the repository.

At this point we haven't actually defined a concrete implementation for our view, all we need to do is create an object that implements ICustomerManagementView. For example in a Windows Forms application we can do the following

```<code>public partial class CustomerManagementView : Form, ICustomerManagementView
{
    public CustomerManagementView()
    {
        this.InitializeComponents();
    }

    public void InitializeCustomers(ICustomer[] customers)
    {
        // Populate the tree view with customer details
    }

    public void DisplayCustomer(ICustomer customer)
    {
        // Display the customer...
    }

    // Event handler that responds to node selection
    private void CustomerTreeViewAfterSelect(object sender, TreeViewEventArgs e)
    {
        var customer = e.Node.Tag as ICustomer;
        if(customer != null)
        {
            this.OnSelectedCustomerChanged(new EventArgs<ICustomer>(customer));
        }
    }

    // Protected method so that we can raise our event
    protected virtual void OnSelectedCustomerChanged(EventArgs<ICustomer> args)
    {
        var eventHandler = this.SelectedCustomerChanged;
        if(eventHandler != null)
        {
            eventHandler.Invoke(this, args);
        }
    }

    // Our view will raise an event each time the selected customer changes
    public event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
</code>```

If we wanted to test our presentation logic we could mock our view and perform some assertions.

EDIT : Included custom event args

```<code>public class EventArgs<T> : EventArgs
{
    private readonly T _value;

    public EventArgs(T value)
    {
        _value = value;
    }

    public T Value
    {
        get { return _value; }
    }
}
</code>```

Body:
Here is a simple example that demonstrates the concept of passive views using the MVP design pattern.  Because we are using passive views the view has no knowledge of the presenter.  The presenter will simply subscribe to events published by the view and act accordingly.

To start out we need to define a contract for our view. This is typically achieved using an interface, essentially, we want to have a very loose coupling with our view.  We want the ability to switch to different views or event create mock views for unit testing.

Here is a contract that describes a simple view that will be used to display customer information

public interface ICustomerManagementView
{
    void InitializeCustomers(ICustomer[] customers);
    void DisplayCustomer(ICustomer customer);
    event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}

It exposes a single method InitializeCustomers that will be used to initialize our view with objects from our model.

We also have an event SelectedCustomerChanged that will be used by our presenter to receive notification that an action has occurred in the view.

Once we have our contract we can start to handle these interactions in our presenter.

public class CustomerManagementPresenter
{
    private ICustomer _selectedCustomer;
    private readonly ICustomerManagementView _managementView;
    private readonly ICustomerRepository _customerRepository;

    public CustomerManagementPresenter(ICustomerManagementView managementView, ICustomerRepository customerRepository)
    {
        _managementView = managementView;
        _managementView.SelectedCustomerChanged += this.SelectedCustomerChanged;

        _customerRepository = customerRepository;

        _managementView.InitializeCustomers(_customerRepository.FetchCustomers());
    }

    private void SelectedCustomerChanged(object sender, EventArgs<ICustomer> args)
    {
        // Perform some logic here to update the view
        if(_selectedCustomer != args.Value)
        {
            _selectedCustomer = args.Value;
            _managementView.DisplayCustomer(_selectedCustomer);
        }
    }
}

In the presenter we can use another design pattern called dependency injection to provide access to our view and any model classes that we may need. In this example I have a CustomerRepository that is responsible for fetching customer details.

In the constructor we have two important lines of code, firstly we have subscribed to the SelectedCustomerChanged event in our view, it is here that we can perform associated actions. Secondly we have called InitilaizeCustomers with data from the repository.

At this point we haven't actually defined a concrete implementation for our view, all we need to do is create an object that implements ICustomerManagementView. For example in a Windows Forms application we can do the following

public partial class CustomerManagementView : Form, ICustomerManagementView
{
    public CustomerManagementView()
    {
        this.InitializeComponents();
    }

    public void InitializeCustomers(ICustomer[] customers)
    {
        // Populate the tree view with customer details
    }

    public void DisplayCustomer(ICustomer customer)
    {
        // Display the customer...
    }

    // Event handler that responds to node selection
    private void CustomerTreeViewAfterSelect(object sender, TreeViewEventArgs e)
    {
        var customer = e.Node.Tag as ICustomer;
        if(customer != null)
        {
            this.OnSelectedCustomerChanged(new EventArgs<ICustomer>(customer));
        }
    }

    // Protected method so that we can raise our event
    protected virtual void OnSelectedCustomerChanged(EventArgs<ICustomer> args)
    {
        var eventHandler = this.SelectedCustomerChanged;
        if(eventHandler != null)
        {
            eventHandler.Invoke(this, args);
        }
    }

    // Our view will raise an event each time the selected customer changes
    public event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}

If we wanted to test our presentation logic we could mock our view and perform some assertions.

EDIT : Included custom event args

public class EventArgs<T> : EventArgs
{
    private readonly T _value;

    public EventArgs(T value)
    {
        _value = value;
    }

    public T Value
    {
        get { return _value; }
    }
}


问:
Get an input from tkinter and then close the window
I have two python files, one in which i store the code inputData.py and one which is the main file, main_project.py.

In inputData i have this code:

```<code>class Prompt(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.inputDt = self.entry.get()
</code>```

In main_project i have this code:

```<code>from inputData import Prompt
promptData = Prompt()
promptData.mainloop()

class Hearing(object):
    numberBirths = promptData.inputDt
</code>```

What i am trying to do is to assign the value numberBirths the value from the input in tkinter, and after i do that, i need the prompt to close and continue with the rest of the code.
Can you help me with that?

答:
your entry widget does not have text variable for using get and set function

please add followings before entry and
edit entry() by inserting textvariable

```<code>input_var=0
self.entry = tk.Entry(self,textvariable=input_var)
</code>```

Body:
I have two python files, one in which i store the code inputData.py and one which is the main file, main_project.py.

In inputData i have this code:

class Prompt(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        self.inputDt = self.entry.get()

In main_project i have this code:

from inputData import Prompt
promptData = Prompt()
promptData.mainloop()

class Hearing(object):
    numberBirths = promptData.inputDt

What i am trying to do is to assign the value numberBirths the value from the input in tkinter, and after i do that, i need the prompt to close and continue with the rest of the code.
Can you help me with that?

Body:
your entry widget does not have text variable for using get and set function

please add followings before entry and
edit entry() by inserting textvariable

input_var=0
self.entry = tk.Entry(self,textvariable=input_var)


问:
Networkx Minimum Spanning Tree - precision issues?
I am creating a graph from a weighted adjacency matrix the size of 222 x 222 nodes. All of the weights given in the matrix are a floating point numbers between 0.42757498546089029 and 1.6671726002927263. nx.minimum_spanning_tree(G, weight = "weight") method gives me the first picture below, meanwhile if I multiply all matrix values by 100.0 the same method gives me the second picture. This doesn't occur while plotting the same with igraph. Documentation of Networkx is silent about precision issues. Do you know why it might occur?

networkx code:

```<code>G=nx.from_numpy_matrix(M)
G1=nx.minimum_spanning_tree(G, weight = "weight")

labels = {i : node_names[i][1] for i in G1.nodes()}
colors = {i : node_attributes[labels[i]] for i in G1.nodes()}
for i in G1.nodes():
    G1.node[i]["color"] = 'white'
    G1.node[i]["style"] = "filled"
    G1.node[i]["fillcolor"] = colors[i]
color=nx.get_node_attributes(G1,'color')
fillcolor=nx.get_node_attributes(G1,'fillcolor')
H=nx.relabel_nodes(G1,labels)
nx.draw(H, scale=30, nodelist=H.nodes(), linewidths=0, with_labels = True, node_size=500,font_size=8)
</code>```

igraph code:

```<code>    g = igraph.Graph.Weighted_Adjacency(M.tolist())
    for i, v in enumerate(g.vs):
        v["color"] = colors[i]
        v["label"] = labels[i]
        v["frame_color"] = colors[i]
        v["label_size"] = 10
        v["size"] = 26
    G = g.spanning_tree(weights='weight', return_tree=True)
    G.to_undirected()
    igraph.plot(G, labels=False, bbox = (900, 900), margin=40, loops=False

)
</code>```

答:
What you see is expected behaviour and not a precision issue at all. As the name suggests, the spring layout "simulates" the action of springs between your nodes onto their positions. The node positions are initialised on a circle, and then the force of the springs is applied to your nodes for a certain number of iterations (50 by default). With weak connection weights, your nodes will more or less remain on the circle (first case), with strong weights your nodes will gravitate towards the centre (second case). </p>

<p>In igraph, by default, the unweighted graph is used to compute the layout and you need to give the plotting routine the weights explicitly. I suspect that you might have plotted the graph without specifying the "weights" parameter. </p>

Body:
I am creating a graph from a weighted adjacency matrix the size of 222 x 222 nodes. All of the weights given in the matrix are a floating point numbers between 0.42757498546089029 and 1.6671726002927263. nx.minimum_spanning_tree(G, weight = "weight") method gives me the first picture below, meanwhile if I multiply all matrix values by 100.0 the same method gives me the second picture. This doesn't occur while plotting the same with igraph. Documentation of Networkx is silent about precision issues. Do you know why it might occur?

networkx code:

G=nx.from_numpy_matrix(M)
G1=nx.minimum_spanning_tree(G, weight = "weight")

labels = {i : node_names[i][1] for i in G1.nodes()}
colors = {i : node_attributes[labels[i]] for i in G1.nodes()}
for i in G1.nodes():
    G1.node[i]["color"] = 'white'
    G1.node[i]["style"] = "filled"
    G1.node[i]["fillcolor"] = colors[i]
color=nx.get_node_attributes(G1,'color')
fillcolor=nx.get_node_attributes(G1,'fillcolor')
H=nx.relabel_nodes(G1,labels)
nx.draw(H, scale=30, nodelist=H.nodes(), linewidths=0, with_labels = True, node_size=500,font_size=8)

igraph code:

    g = igraph.Graph.Weighted_Adjacency(M.tolist())
    for i, v in enumerate(g.vs):
        v["color"] = colors[i]
        v["label"] = labels[i]
        v["frame_color"] = colors[i]
        v["label_size"] = 10
        v["size"] = 26
    G = g.spanning_tree(weights='weight', return_tree=True)
    G.to_undirected()
    igraph.plot(G, labels=False, bbox = (900, 900), margin=40, loops=False

)

Body:
What you see is expected behaviour and not a precision issue at all. As the name suggests, the spring layout "simulates" the action of springs between your nodes onto their positions. The node positions are initialised on a circle, and then the force of the springs is applied to your nodes for a certain number of iterations (50 by default). With weak connection weights, your nodes will more or less remain on the circle (first case), with strong weights your nodes will gravitate towards the centre (second case).

In igraph, by default, the unweighted graph is used to compute the layout and you need to give the plotting routine the weights explicitly. I suspect that you might have plotted the graph without specifying the "weights" parameter.


问:
Is it possible to improve converting list to sorted map?
Now I have such method:

```<code>public static Map<String, Long> getSortedMap(List<String> wordsList) {
    Map<String, Long> countedWords = wordsList.stream()
            .collect(
                    Collectors.groupingBy(Function.identity(), Collectors.counting())
            );
    return new TreeMap<>(countedWords);
}
</code>```

which convert list of strings to map, where the key is unique string from the list, and the value - the number of times this string is repeated in the list. Then it sorts the map by key.

Can this be rewritten in one stream operation?

Is it possible to increase speed of execution?

答:
You can use the Collectors.groupingBy variant that takes a mapFactory as an argument:

```<code>public static Map<String, Long> getSortedMap(List<String> wordsList) {
    return wordsList.stream()
            .collect(
                    Collectors.groupingBy(Function.identity(),
                                          TreeMap::new,
                                          Collectors.counting())
            );
}
</code>```

Body:
Now I have such method:

public static Map<String, Long> getSortedMap(List<String> wordsList) {
    Map<String, Long> countedWords = wordsList.stream()
            .collect(
                    Collectors.groupingBy(Function.identity(), Collectors.counting())
            );
    return new TreeMap<>(countedWords);
}

which convert list of strings to map, where the key is unique string from the list, and the value - the number of times this string is repeated in the list. Then it sorts the map by key.

Can this be rewritten in one stream operation?

Is it possible to increase speed of execution?

Body:
You can use the Collectors.groupingBy variant that takes a mapFactory as an argument:

public static Map<String, Long> getSortedMap(List<String> wordsList) {
    return wordsList.stream()
            .collect(
                    Collectors.groupingBy(Function.identity(),
                                          TreeMap::new,
                                          Collectors.counting())
            );
}


问:
Angular - getting ng-bind to work on nested directives
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

```<code>app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("<span ng-bind='depth'/>");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
</code>```

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>```

答:
The compiled part of your template need to refer as child only instead on child.html().

Change your code at 3 places from $element.append(child.html()); to $element.append(child);

This will start printing the depth value you are looking for. Is there anything else you are looking for?

Body:
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>


问:
Redux react immutable setIn element changes whole list
I have this reducer in redux:

```<code>let index = state.items.findIndex(item => item.get('_id') == action.id);
let list = state.items.setIn([index, "selected"], action.selected)

return {
    ...state,
    items: list
}
</code>```

In this case, when Im looking on the redux changes, I see that the whole list is changed, then all my view is reders instead of the specific item.

What am I doing wrong?

UPDATE:
I changed to updateIn, now my state shows that only one element is updated, but still my whole app is renders instead of the specific element:

```<code><Row style={styles.row} key={item.get('_id')} item={item} selected={item.get('selected')}
                        onSelect={this.props.onRowSelect}/>
</code>```

答:
It looks like you are not using reducer composition. I would strongly encourage that as it makes each reducer a lot easier to understand: http://redux.js.org/docs/api/combineReducers.html

Without seeing how your component is mapped to the state it is hard to tell what is happening here, but I believe the root of your problem is that what you return from your reducer will always be a new object.

Returned state will be a new object as you've merged the old state with a new list.

Items will be a new object as part of what immutablejs does is make sure that if you change a child inside it, that change cascades upwards touching all parents.

Finally the individual items you updated will be new objects.

I suspect you need to change a selector or mapStateToProps function to stop it from getting items which as it will always have changed, thus always causing a rerender.

Body:
I have this reducer in redux:

let index = state.items.findIndex(item => item.get('_id') == action.id);
let list = state.items.setIn([index, "selected"], action.selected)

return {
    ...state,
    items: list
}

In this case, when Im looking on the redux changes, I see that the whole list is changed, then all my view is reders instead of the specific item.

What am I doing wrong?

UPDATE:
I changed to updateIn, now my state shows that only one element is updated, but still my whole app is renders instead of the specific element:

<Row style={styles.row} key={item.get('_id')} item={item} selected={item.get('selected')}
                        onSelect={this.props.onRowSelect}/>


问:
How to create dynamic routes in sh-service framework
Please help me, how to create a custom routes in php sh-service framework.</p>

答:
Try this one:

```<code>$app->get('/name/:firstname',function($app,$req,$res){

   $res->json($req->firstname);

}
</code>```

it is working for me.

Body:
Try this one:

$app->get('/name/:firstname',function($app,$req,$res){

   $res->json($req->firstname);

}

it is working for me.


问:
How to change format of a date from dd/mm/yyyy to MM/dd/yyyy where date is already converted from string?
I am getting date from a API which is in string format, I converted that string to date but unable to change it's format. Currently I got string like this -> '20/11/2016' I want to convert this & should look like this
-> 11/20/2016 & then only I can display this in html page using html 5 date input type</p>

```<code>    <input type='date' ng-model='myDate'>

   myApp.controller('myCtrl',['$scope','$filter'],
   function ($scope,$filter)
   {
    //consider this string comes from api...
   var stringDate='20/11/2016';
   var convertedDate=new Date(stringDate);
   $scope.myDate=$filter('date')(convertedDate,'MM/dd/yyyy');
   });
</code>```

答:
```<code>var stringDate1=this.dStartDate;
var splitDate1 = stringDate1.split('-');
var year1  = splitDate1[0];
var month1 = splitDate1[1];
var day1 = splitDate1[2];
this.dStartDate = month1+"-"+day1+"-"+year1;
console.log("date"+this.dStartDate);
</code>```

Body:
I am getting date from a API which is in string format, I converted that string to date but unable to change it's format. Currently I got string like this -> '20/11/2016' I want to convert this & should look like this
-> 11/20/2016 & then only I can display this in html page using html 5 date input type

    <input type='date' ng-model='myDate'>

   myApp.controller('myCtrl',['$scope','$filter'],
   function ($scope,$filter)
   {
    //consider this string comes from api...
   var stringDate='20/11/2016';
   var convertedDate=new Date(stringDate);
   $scope.myDate=$filter('date')(convertedDate,'MM/dd/yyyy');
   });


问:
Convert urb to skbuff
I am trying to write a kernel module which is the combination of the usb driver and a network driver, now whenever the data is recieved by the usb driver it will be in struct urb, but the data that is required by the net driver is sk_buff, now how do i convert a urb to sk_buff, i found something similar is being done in the phonet protocol, but i couldnt understand, howexactly this is being done. Can someone explain this code.

drivers/net/usb/cdc-phonet.c

```<code>static void rx_complete(struct urb *req)
{
struct net_device *dev = req->context;
struct usbpn_dev *pnd = netdev_priv(dev);
struct page *page = virt_to_page(req->transfer_buffer);
struct sk_buff *skb;
unsigned long flags;
int status = req->status;

switch (status) {
case 0:
spin_lock_irqsave(&pnd->rx_lock, flags);
skb = pnd->rx_skb;
if (!skb) {
skb = pnd->rx_skb = netdev_alloc_skb(dev, 12);
if (likely(skb)) {
/* Can't use pskb_pull() on page in IRQ */
memcpy(skb_put(skb, 1), page_address(page), 1);
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
page, 1, req->actual_length);
page = NULL;
}
} else {
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
page, 0, req->actual_length);
page = NULL;
}
if (req->actual_length < PAGE_SIZE)
pnd->rx_skb = NULL; /* Last fragment */
else
skb = NULL;
spin_unlock_irqrestore(&pnd->rx_lock, flags);
if (skb) {
skb->protocol = htons(ETH_P_PHONET);
skb_reset_mac_header(skb);
__skb_pull(skb, 1);
skb->dev = dev;
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;

netif_rx(skb);
}
goto resubmit;

case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
req = NULL;
break;

case -EOVERFLOW:
dev->stats.rx_over_errors++;
dev_dbg(&dev->dev, "RX overflow\n");
break;

case -EILSEQ:
dev->stats.rx_crc_errors++;
break;
}

dev->stats.rx_errors++;
resubmit:
if (page)
netdev_free_page(dev, page);
if (req)
rx_submit(pnd, req, GFP_ATOMIC);
}
</code>```

答:
The URB struct doesn't contain the actual transfered data rather it contains a pointer to the data, the transfer_buffer element.

The code basically copies data from the transfer buffer to the sk buff. The virt_to_page / page_address will return the virtual address of the start of the transfer_buffer page.

Title: Convert urb to skbuff

Body:
I am trying to write a kernel module which is the combination of the usb driver and a network driver, now whenever the data is recieved by the usb driver it will be in struct urb, but the data that is required by the net driver is sk_buff, now how do i convert a urb to sk_buff, i found something similar is being done in the phonet protocol, but i couldnt understand, howexactly this is being done. Can someone explain this code.

drivers/net/usb/cdc-phonet.c

static void rx_complete(struct urb *req)
{
struct net_device *dev = req->context;
struct usbpn_dev *pnd = netdev_priv(dev);
struct page *page = virt_to_page(req->transfer_buffer);
struct sk_buff *skb;
unsigned long flags;
int status = req->status;

switch (status) {
case 0:
spin_lock_irqsave(&pnd->rx_lock, flags);
skb = pnd->rx_skb;
if (!skb) {
skb = pnd->rx_skb = netdev_alloc_skb(dev, 12);
if (likely(skb)) {
/* Can't use pskb_pull() on page in IRQ */
memcpy(skb_put(skb, 1), page_address(page), 1);
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
page, 1, req->actual_length);
page = NULL;
}
} else {
skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
page, 0, req->actual_length);
page = NULL;
}
if (req->actual_length < PAGE_SIZE)
pnd->rx_skb = NULL; /* Last fragment */
else
skb = NULL;
spin_unlock_irqrestore(&pnd->rx_lock, flags);
if (skb) {
skb->protocol = htons(ETH_P_PHONET);
skb_reset_mac_header(skb);
__skb_pull(skb, 1);
skb->dev = dev;
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;

netif_rx(skb);
}
goto resubmit;

case -ENOENT:
case -ECONNRESET:
case -ESHUTDOWN:
req = NULL;
break;

case -EOVERFLOW:
dev->stats.rx_over_errors++;
dev_dbg(&dev->dev, "RX overflow\n");
break;

case -EILSEQ:
dev->stats.rx_crc_errors++;
break;
}

dev->stats.rx_errors++;
resubmit:
if (page)
netdev_free_page(dev, page);
if (req)
rx_submit(pnd, req, GFP_ATOMIC);
}


问:
UILabel Hidden text issue
Well this so weird . I also hesitate to post this question but I haven't got any solution that's why I decided to post it. Here I go.

I have a XIB i have subclassed it in UICollectionView. This is my code in didSelectMethod:

```<code>- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

 CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];

cell.nameLabel.textColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:0.8];

[cell setSelected:NO];

cell.nameLabel.hidden = NO;
cell.nameLabel.text = @"HHHHHHH";
cell.nameLabel.backgroundColor = [UIColor redColor];

}
</code>```

Now when I run my code I get correct Output. But when I select any cell then text of my UILabel is hidden I can only see the background colour.

When I select another one then I get back the text of previously selected UILabel.

I haven't written any other code I not able to figure it OUT.

When I select any cell:

When I select another cell:

When I select Previous Cell:

Here is my code for making cells:

```<code> - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

// Get reusable cell reference
CollectionViewCell *cell = (CollectionViewCell *)[cv dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];

[cell updateText];

return cell;
}
</code>```

This method is in custom Class

```<code> - (void) updateText{

self.nameLabel.text = name;

 }
</code>```

答: Go to your nib/xib file and check the highlighted color weather it is clear or some other color. If it is clear than change as per your requirement.

Title: UILabel Hidden text issue

Body:
Well this so weird . I also hesitate to post this question but I haven't got any solution that's why I decided to post it. Here I go.

I have a XIB i have subclassed it in UICollectionView. This is my code in didSelectMethod:

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

 CollectionViewCell *cell = (CollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];

cell.nameLabel.textColor = [UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:0.8];

[cell setSelected:NO];

cell.nameLabel.hidden = NO;
cell.nameLabel.text = @"HHHHHHH";
cell.nameLabel.backgroundColor = [UIColor redColor];

}

Now when I run my code I get correct Output. But when I select any cell then text of my UILabel is hidden I can only see the background colour.

When I select another one then I get back the text of previously selected UILabel.

I haven't written any other code I not able to figure it OUT.

When I select any cell:

When I select another cell:

When I select Previous Cell:

Here is my code for making cells:

 - (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {

// Get reusable cell reference
CollectionViewCell *cell = (CollectionViewCell *)[cv dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];

[cell updateText];

return cell;
}

This method is in custom Class

 - (void) updateText{

self.nameLabel.text = name;

 }


问:
Android add shortcut icon from a url instead from drawable resources
I have an app where i am adding shortcut. I want to add shortcut icon image from URL path(images are stored on server and can be change) instead of using Drawable but i don't know how to do that. I tried to find a lot on this community. Any help?</p>

答:
If the term used "shortcut icon" is a view or its descendants such as ImageView, then you can set the image, your application receive from the server by doing this :

add dependency to your app.gradle file :

```<code>compile 'com.github.bumptech.glide:glide:3.7.0'
</code>```

and in the activity you can use this method to set the image to the imageview your app receive from the server :

```<code>ImageView imageView = (ImageView) findViewById(R.id.image_view);
Glide.with(imageview.getContext()).load("https://url").error(R.drawable.not_found).centerCrop().into(imageview);
</code>```

Body:
If the term used "shortcut icon" is a view or its descendants such as ImageView, then you can set the image, your application receive from the server by doing this :

add dependency to your app.gradle file :

compile 'com.github.bumptech.glide:glide:3.7.0'

and in the activity you can use this method to set the image to the imageview your app receive from the server :

ImageView imageView = (ImageView) findViewById(R.id.image_view);
Glide.with(imageview.getContext()).load("https://url").error(R.drawable.not_found).centerCrop().into(imageview);


问:
Running multiple instances of the same android service
If I create an android service using startService() followed by bindService(), and I never call stopService().
Now, every time my app calls startService() and bindService(), will it create a new instance of the service or reuse the existing one?

If a new instance is created...is the old instance still running or is it terminated?

答: It will not create another service, but redeliver your start Intent into onNewIntent() method</p>


问:
How to include context variable in a wagtail cms field?
I am looking for a way to render a variable that will be available in the context of the the page where the cms page will be rendered.

Ex:
I have in the context the logged in user and I also have the last transaction he made on the website.

I would like the text in the rich text field in Wagtail to be like this so that the marketing team can tweak the copy.

Hello ||firstname|| thanks for your purchase. ||productname|| will be
  shipped to you soon. The expected delivery date is
  ||expected_delivery_date||

To be less confusing I replace the double brackets by double pipes to show that the templating system does not need to be django templates for those ones. Simple templating is enough maybe using https://docs.python.org/3.4/library/string.html#template-strings
I think I can achieve this by doing:

A stream field that would have blocks of rich text field and a custom block with the possible context variable they can use

A custom render function that would regex and replace the merge tags in the rich text block with the context values

Create a new filter for simple templating. ex: {{ page.body|richtext|simpletemplate }}

Is there any more obvious way or out of the box way to do templating from within a rich text field?

答:
It would be clunky with a separate streamfield block for each inserted context variable. You'd have to override the default rendering which wraps elements in div tags. However I like that it is more foolproof for the editors.

I've done something like the custom rendering before, but with simple TextFields for formatting special offer code messages. Wagtail editors were given the following help_text to illustrate:

```<code>valid_placeholders = ['offer_code', 'month_price']
template_text = models.TextField(
    _('text'),
    help_text="Valid placeholder values are: {all_valid}. Write as {{{example}}}".format(
        all_valid=", ".join(valid_placeholders),
        example=valid_placeholders[0],
    )
)
</code>```

This rendered as Valid placeholder values are: offer_code, month_price. Write as {{offer_code}}.

Then in the view:

```<code>template_keys = [i[1] for i in Formatter().parse(template_text)]
</code>```

…and continued rendering from there. Remember to validate the field appropriately using the above Formatter().parse() function too.

I used Django's template formatting rather than Python's string.format() because it fails silently, but you could go with string.format() if cleaned adequately.

The custom template filter would feel easiest to me, so I'd start with that approach and switch to a custom render function if I ran into hurdles.

Body:
It would be clunky with a separate streamfield block for each inserted context variable. You'd have to override the default rendering which wraps elements in div tags. However I like that it is more foolproof for the editors.

I've done something like the custom rendering before, but with simple TextFields for formatting special offer code messages. Wagtail editors were given the following help_text to illustrate:

valid_placeholders = ['offer_code', 'month_price']
template_text = models.TextField(
    _('text'),
    help_text="Valid placeholder values are: {all_valid}. Write as {{{example}}}".format(
        all_valid=", ".join(valid_placeholders),
        example=valid_placeholders[0],
    )
)

This rendered as Valid placeholder values are: offer_code, month_price. Write as {{offer_code}}.

Then in the view:

template_keys = [i[1] for i in Formatter().parse(template_text)]

…and continued rendering from there. Remember to validate the field appropriately using the above Formatter().parse() function too.

I used Django's template formatting rather than Python's string.format() because it fails silently, but you could go with string.format() if cleaned adequately.

The custom template filter would feel easiest to me, so I'd start with that approach and switch to a custom render function if I ran into hurdles.


问:
Processing Symbol Files in Xcode
I was wondering if anyone could tell me what Xcode is actually doing when it says: "Processing Symbol Files" after plugging in your device?

答: In my case symbolicating was take forever. I force restart my phone with both of on/off and home button. Now quickly finished symbolicating and I am starting run my app via xcode.</p>

Title: Processing Symbol Files in Xcode


问:
Multiple Custom UIPickerViews in the same UIView in swift
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

```<code> @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }
</code>```

答:
```<code>class ViewController: UIViewController {

    @IBOutlet var txtDuration: UITextField!
    @IBOutlet var txtEventType: UITextField!

    var pickerView = UIPickerView()

    var arrEventType : [String] = []
    var arrDuration : [String] = []

    var currentTextField : UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        arrEventType = ["Birthday" , "Marriage" , "Get together", "Conference"]
        arrDuration  = ["6-8","1-5","7-9","10-12"]
    }
}

extension ViewController : UIPickerViewDelegate , UIPickerViewDataSource {

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if currentTextField == txtEventType {
            return arrEventType.count
        } else if currentTextField == txtDuration {
            return arrDuration.count
        } else {
            return 0
        }
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if currentTextField == txtEventType {
            return arrEventType[row]
        } else if currentTextField == txtDuration {
            return arrDuration[row]
        } else {
            return ""
        }
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if currentTextField == txtEventType {
            txtEventType.text = arrEventType[row]
        } else if currentTextField == txtDuration {
            txtDuration.text = arrDuration[row]
        }
    }
}

extension ViewController : UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.pickerView.delegate   = self
        self.pickerView.dataSource = self
        currentTextField = textField
        if currentTextField == txtEventType {
            currentTextField?.inputView = pickerView
        } else if currentTextField == txtDuration {
            currentTextField?.inputView  = pickerView
        }

    }
}
</code>```

Above lines of code may solve your issue with just one UIPickerView and without tags

Body:
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

 @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }

Body:
class ViewController: UIViewController {

    @IBOutlet var txtDuration: UITextField!
    @IBOutlet var txtEventType: UITextField!

    var pickerView = UIPickerView()

    var arrEventType : [String] = []
    var arrDuration : [String] = []

    var currentTextField : UITextField?

    override func viewDidLoad() {
        super.viewDidLoad()

        arrEventType = ["Birthday" , "Marriage" , "Get together", "Conference"]
        arrDuration  = ["6-8","1-5","7-9","10-12"]
    }
}

extension ViewController : UIPickerViewDelegate , UIPickerViewDataSource {

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if currentTextField == txtEventType {
            return arrEventType.count
        } else if currentTextField == txtDuration {
            return arrDuration.count
        } else {
            return 0
        }
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if currentTextField == txtEventType {
            return arrEventType[row]
        } else if currentTextField == txtDuration {
            return arrDuration[row]
        } else {
            return ""
        }
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if currentTextField == txtEventType {
            txtEventType.text = arrEventType[row]
        } else if currentTextField == txtDuration {
            txtDuration.text = arrDuration[row]
        }
    }
}

extension ViewController : UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.pickerView.delegate   = self
        self.pickerView.dataSource = self
        currentTextField = textField
        if currentTextField == txtEventType {
            currentTextField?.inputView = pickerView
        } else if currentTextField == txtDuration {
            currentTextField?.inputView  = pickerView
        }

    }
}

Above lines of code may solve your issue with just one UIPickerView and without tags