问:
Customized circular checkbox in Android
I am trying to get the Google apps photo select UI .. Am using Appcompat checkbox to achieve that with out success. The steps I am working on ,
 1. Set the checkbox background to custom circular shape
 2. define custom shape in xml

This is my check box xml looks like ,

```<code> <android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:button="@drawable/custom_checkbox"
            android:background="@drawable/checkbox_drawable"
            />
</code>```

My custom checkbox background,

```<code>   <shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval">
    <stroke
       android:width="1dp"
       android:color="#78d9ff"/>
    <solid
    android:color="#79bfea"/>
   </shape>
</code>```

My checkbox button ,

```<code><selector>
<item android:drawable="@drawable/checkbox_drawable"
      android:state_checked="false"/>
    <item android:drawable="@drawable/selected_check"
      android:state_checked="true"/>
 </selector>
</code>```

I even changed from android:background to android:button .. nothing gives me the circular check box .. Any help is appreciated ? Should I use floating action bar ? or a view ? Any suggestions ?

答:
Custom Checkbox with two drawable image.

1. In .xml file

```<code><android.support.v7.widget.AppCompatCheckBox
   android:id="@+id/checkBox"
   android:layout_width="40dp"
   android:layout_height="40dp"
   android:layout_gravity="center"
   android:background="@drawable/checkbox_selector"
   android:button="@color/white"
   android:checked="true" />
</code>```

2. Create checkbox_selector.xml  in drawable folder.

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/cancel"
       android:state_checked="false"/>
   <item android:drawable="@drawable/checked"
       android:state_checked="true"/>
</selector>
</code>```

3. Add checked.png and cansel.phd image in drawable folder from the below link

https://icons8.com/icon/set/yes/all

And

https://icons8.com/icon/set/cross/all

4. Checkbox click event

```<code>AppCompatCheckBox checkBox = (AppCompatCheckBox) view.findViewById(R.id.checkBox);

checkBox.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

       if (checkBox.isChecked()){
      checkBox.setChecked(false);
       }else {
         checkBox.setChecked(true);
       }
         }
});
</code>```

Title: Customized circular checkbox in Android

Body:
I am trying to get the Google apps photo select UI .. Am using Appcompat checkbox to achieve that with out success. The steps I am working on ,
 1. Set the checkbox background to custom circular shape
 2. define custom shape in xml

This is my check box xml looks like ,

 <android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/checkBox"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:button="@drawable/custom_checkbox"
            android:background="@drawable/checkbox_drawable"
            />

My custom checkbox background,

   <shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="oval">
    <stroke
       android:width="1dp"
       android:color="#78d9ff"/>
    <solid
    android:color="#79bfea"/>
   </shape>

My checkbox button ,

<selector>
<item android:drawable="@drawable/checkbox_drawable"
      android:state_checked="false"/>
    <item android:drawable="@drawable/selected_check"
      android:state_checked="true"/>
 </selector>

I even changed from android:background to android:button .. nothing gives me the circular check box .. Any help is appreciated ? Should I use floating action bar ? or a view ? Any suggestions ?

Body:
Custom Checkbox with two drawable image.

1. In .xml file

<android.support.v7.widget.AppCompatCheckBox
   android:id="@+id/checkBox"
   android:layout_width="40dp"
   android:layout_height="40dp"
   android:layout_gravity="center"
   android:background="@drawable/checkbox_selector"
   android:button="@color/white"
   android:checked="true" />

2. Create checkbox_selector.xml  in drawable folder.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/cancel"
       android:state_checked="false"/>
   <item android:drawable="@drawable/checked"
       android:state_checked="true"/>
</selector>

3. Add checked.png and cansel.phd image in drawable folder from the below link

https://icons8.com/icon/set/yes/all

And

https://icons8.com/icon/set/cross/all

4. Checkbox click event

AppCompatCheckBox checkBox = (AppCompatCheckBox) view.findViewById(R.id.checkBox);

checkBox.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {

       if (checkBox.isChecked()){
      checkBox.setChecked(false);
       }else {
         checkBox.setChecked(true);
       }
         }
});


来源: stackexchange

问:
Setting a decimal value on a form doesnt always work - Dynamics CRM 2013
Hope someone can help with this. I know how to set a field value on a form and it works in a way. My query is around the fact that it only works if I put this line below into the form load event as a line by itself.

Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

However, in reality I need to have some conditional checks before I set this value and when I put this line into those conditional checks, then what I notice is that the textbox is blank but if I look at the value in the data entity it does indicate it has the value of 1.01.

alert("No. in entity:" + Xrm.Page.data.entity.attributes.get('cal_entrynumber').getValue());

So I wanted to know if anyone can pinpoint me to anything that potentially might be the cause for this ... here is the code in which the line sits (and doesnt work).

```<code>var queryString = "?$select=cal_EntryNumber&$filter=cal_SafetyProgrammeNo eq '" + spNo + "'&top=1&$orderby=cal_EntryNumber desc";
SDK.REST.retrieveMultipleRecords(
    "cal_operation",
    queryString,
    function (results) {
        //alert(results.length);
        if (results.length == 0) {
            //var entry = 1.01;
            //alert("Entry No:" + Number(entry));
            Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

        }
        else {
            // Code to go here.
        }
    },
    errorHandler,
    function () {
        // OnComplete handler
    }
    );
</code>```

答:
I've found out why this doesnt work (even though the code is correct) and I'm posting my answer here to help anyone else who might have the same issue.

The Entry Number field gets focus when the form loads and this was emptying the field of its (javascript set) value. I fixed this by putting another textbox field as the first field on the form and now the field is showing the javascript set value (no code changes were required).

I suspect this worked when I put the code into the form load event by itself as it gets run synchronously but when I put the same line of code into retrieveMultipleRecords success callback function, as this runs Asynchronously, it presents this issue. Hope this helps anyone else with this problem.

ContentLicense: CC BY-SA 3.0

Body:
Hope someone can help with this. I know how to set a field value on a form and it works in a way. My query is around the fact that it only works if I put this line below into the form load event as a line by itself.

Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

However, in reality I need to have some conditional checks before I set this value and when I put this line into those conditional checks, then what I notice is that the textbox is blank but if I look at the value in the data entity it does indicate it has the value of 1.01.

alert("No. in entity:" + Xrm.Page.data.entity.attributes.get('cal_entrynumber').getValue());

So I wanted to know if anyone can pinpoint me to anything that potentially might be the cause for this ... here is the code in which the line sits (and doesnt work).

var queryString = "?$select=cal_EntryNumber&$filter=cal_SafetyProgrammeNo eq '" + spNo + "'&top=1&$orderby=cal_EntryNumber desc";
SDK.REST.retrieveMultipleRecords(
    "cal_operation",
    queryString,
    function (results) {
        //alert(results.length);
        if (results.length == 0) {
            //var entry = 1.01;
            //alert("Entry No:" + Number(entry));
            Xrm.Page.getAttribute('cal_entrynumber').setValue(1.01);

        }
        else {
            // Code to go here.
        }
    },
    errorHandler,
    function () {
        // OnComplete handler
    }
    );


问:
What is the recommended native JavaScript equivalent to a jQuery delegated event?
I'd like to know what is the best native js practice for a jQuery delegated event handler like this:

```<code>$('body').on('click','.my-class', event => {
  // perform action
});
</code>```

Event delegation like this allows you add click events to dynamically added HTMLElements as you are listening to all clicks on the body or document.

Right now I'm doing something like this, which feels a little messy and sometimes it breaks if the user clicks an svg for instance. Also, it becomes difficult when you want to target multiple classes in a rather long HTMLElement.classList eg '.my-main-class.my-temp-class'.

```<code>document.body.addEventListener('click', event => {
  if (event.target.classList.contains('my-class')) {
    // perform action
  }
});
</code>```

Even an NPM dom helper library that I could import would be appreciated.

答:
This is a demo javascript function to check if element has multiple classes using the class attribute and not the classList

document.body.addEventListener('click', function(e){

  console.log('Does element have classes my-class and svg - ' + e.target.hasClasses('my-class svg'));

  console.log('Does element have class my-class - ' + e.target.hasClasses('my-class'));

});

Element.prototype.hasClasses = function(classes) {
    // get element classses string
    var elementClass = this.getAttribute('class');

    // return false if class is not set at all
    if(elementClass == null) return false;

    // check if this class is found in elementClass string
    return classes.split(' ').reduce(function(acc, current){
      return Boolean(acc && ~elementClass.indexOf(current));
    }, true);

};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="my-class">I have my-class</button>
<br/>
<p class="not-valid some-other">I have not-valid and some-other classes</p>
<br/>
<svg width="100" height="100" style="background-color:blue;" class="my-class svg">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" class="circle class"/>
</svg></code>```

NOTE

Take care with the svg. Try to click on the blue background and inside the circle to see the difference

Body:
I'd like to know what is the best native js practice for a jQuery delegated event handler like this:

$('body').on('click','.my-class', event => {
  // perform action
});

Event delegation like this allows you add click events to dynamically added HTMLElements as you are listening to all clicks on the body or document.

Right now I'm doing something like this, which feels a little messy and sometimes it breaks if the user clicks an svg for instance. Also, it becomes difficult when you want to target multiple classes in a rather long HTMLElement.classList eg '.my-main-class.my-temp-class'.

document.body.addEventListener('click', event => {
  if (event.target.classList.contains('my-class')) {
    // perform action
  }
});

Even an NPM dom helper library that I could import would be appreciated.

Body:
This is a demo javascript function to check if element has multiple classes using the class attribute and not the classList

document.body.addEventListener('click', function(e){

  console.log('Does element have classes my-class and svg - ' + e.target.hasClasses('my-class svg'));

  console.log('Does element have class my-class - ' + e.target.hasClasses('my-class'));

});

Element.prototype.hasClasses = function(classes) {
    // get element classses string
    var elementClass = this.getAttribute('class');

    // return false if class is not set at all
    if(elementClass == null) return false;

    // check if this class is found in elementClass string
    return classes.split(' ').reduce(function(acc, current){
      return Boolean(acc && ~elementClass.indexOf(current));
    }, true);

};

<button class="my-class">I have my-class</button>
<br/>
<p class="not-valid some-other">I have not-valid and some-other classes</p>
<br/>
<svg width="100" height="100" style="background-color:blue;" class="my-class svg">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" class="circle class"/>
</svg>

NOTE

Take care with the svg. Try to click on the blue background and inside the circle to see the difference


问:
SQL complex query- ORDER BY and GROUP BY in the same query did not work properly
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

```<code>SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn
</code>```

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.

答:
Try this

```<code>SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1
group by msisdn
order by max(msisdn) or Min(msisdn)
</code>```

Try ordering by Max or min Which ever you want

Body:
I have a table like that,

Now, I want to find out the winner, who gave the correct answer most in early. I tried something like that,

SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1 group by msisdn

And output is-

Now, When I try to ORDER BY creation_time , it did not give expected out but error. What should be the query to find out the winner.

Body:
Try this

SELECT COUNT(is_correct), msisdn
FROM [robi_contest].[dbo].[tbl_quiz_reply]
WHERE is_correct = 1
group by msisdn
order by max(msisdn) or Min(msisdn)

Try ordering by Max or min Which ever you want


问:
how to handle adapter in MVP pattern
I'm going to create my first real MVP app. the problem that i have is with adapter. i have a button on my recyclerview card which i implement the onclick method in adapter and now the problem is with adapter. i don't know why when i implement the view interface that i made it in the presenter part of my app. i get error while i want to pass view to presenter.
this is my error

this is what everything that i did:
in my fragment:

```<code>public class FavoritFragment extends Fragment implements FavoritePresenter.View{
    View rootView;

    FavoritePresenter favoritePresenter;
    public FavoritFragment() {
        // Required empty public constructor
    }

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

        favoritePresenter.getAddressSearchModel();

    return view;
    }

    @Override
    public void updateFavoriteRecycler(ArrayList<AddressSearchModel> info) {

        RecyclerView recyclerView=(RecyclerView)rootView.findViewById(R.id.address_recyclerview);
        FavoriteAdapter adapterClass;
        adapterClass=new FavoriteAdapter(info,getActivity(),rootView);
        RecyclerView.LayoutManager LayoutManager= new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(LayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new
                DividerItemDecoration(rootView.getContext(),LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapterClass);
        adapterClass.notifyDataSetChanged();
    }

    @Override
    public void deleteFavorite(ArrayList<AddressSearchModel> id) {

    }

}
</code>```

in my presenter

```<code>public class FavoritePresenter {
    // use this class to make networkCall Catch data and so on
    View view;

    ArrayList<AddressSearchModel> addressSearchModel;
    public FavoritePresenter(View view){
        this.view=view;
        addressSearchModel=new ArrayList<>();
    }

    public void getAddressSearchModel()
    {
        addressSearchModel=PreparData();
        view.updateFavoriteRecycler(this.addressSearchModel);
    }
    /**
     *   do the network call and delete favorite and then do another network call to update it.
     *      The better ways is to catch data and sort it base on update field and then send update field
     *   to ruby part and in ruby take the rest of field base on update_at field (better performance)
     */
    public void deleteFavorite(AddressSearchModel favoriteId){
        addressSearchModel=deleteData();
        view.deleteFavorite(this.addressSearchModel);
    }
    private ArrayList<AddressSearchModel> deleteData() {
        ArrayList<AddressSearchModel> lst_SearchResult=new ArrayList<>();;
        AddressSearchModel model=new AddressSearchModel();
        model.setName("sasd");
        model.setAddress("sdsaqweqweqwds");
        model.setRegions("asdfdgdfgqweqwedfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");

        lst_SearchResult.add(model);
        model=new AddressSearchModel();
        model.setName("sas21312dqweqwe");
        model.setAddress("sdsaderers");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        return lst_SearchResult;
    }
    //call network call using this method to update recyclerview
    private ArrayList<AddressSearchModel> PreparData() {
        ArrayList<AddressSearchModel> lst_SearchResult=new ArrayList<>();;
        AddressSearchModel model=new AddressSearchModel();
        model.setName("sasd");
        model.setAddress("sdsads");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");

        lst_SearchResult.add(model);
        model=new AddressSearchModel();
        model.setName("sas21312d");
        model.setAddress("sdsaderers");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        model=new AddressSearchModel();
        model.setName("saweresd");
        model.setAddress("sdsererads");
        model.setRegions("asdfdgererdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        return lst_SearchResult;
    }
    public interface  View
    {
        void updateFavoriteRecycler(ArrayList<AddressSearchModel>  info);

        //i get String as id because of UUID type format in ruby on rails
        void deleteFavorite(ArrayList<AddressSearchModel> id);
    }
}
</code>```

and in my adapter:

```<code>public class FavoriteAdapter extends RecyclerView.Adapter<FavoriteAdapter.MyHolder> implements FavoritePresenter.View {
    private List<AddressSearchModel> doctorList;
    public Activity activity;
    public View rootView;
    public FavoriteAdapter(List<AddressSearchModel> doctorList, Activity activity,View view)
    {
        rootView=view;
        this.activity=activity;
        this.doctorList=doctorList;
    }

    class MyHolder extends RecyclerView.ViewHolder{
        public ImageView mArticleImage;
        public TextView drugstore_desc;
        public Button DeleteFavorite;
        public MyHolder(View itemView) {
            super(itemView);
            mArticleImage=(ImageView)itemView.findViewById(R.id.im_article);
            drugstore_desc=(TextView)itemView.findViewById(R.id.drugstore_desc);
            DeleteFavorite=(Button)itemView.findViewById(R.id.DeleteFavorite);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cardview_address_montakhab,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(final MyHolder holder, final int position) {
        final AddressSearchModel addressSearchModel =doctorList.get(position);
        Log.d("Doctore_Size", String.valueOf(doctorList.size()));
        //holder.ImageView.setText(addressSearchModel.getName());
        holder.drugstore_desc.setText(addressSearchModel.getRegions());

        holder.DeleteFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fav_GetAddress(addressSearchModel.getName(), addressSearchModel.getRegions());
                FavoritePresenter favoritePresenter=new FavoritePresenter(v);
                favoritePresenter.deleteFavorite(addressSearchModel);
            }
        });
    }

    @Override
    public void deleteFavorite(ArrayList<AddressSearchModel> id) {

    }
    @Override
    public void updateFavoriteRecycler(ArrayList<AddressSearchModel> info) {
        RecyclerView recyclerView=(RecyclerView)activity.findViewById(R.id.address_recyclerview);
        FavoriteAdapter adapterClass;
        adapterClass=new FavoriteAdapter(info,activity,rootView);
        RecyclerView.LayoutManager LayoutManager= new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(LayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new
                DividerItemDecoration(activity,LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapterClass);
        adapterClass.notifyDataSetChanged();
    }

    public  void fav_GetAddress(String place,String PlaceAddress){
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(R.layout.dialog_add_address);
        dialog.getWindow().setBackgroundDrawableResource(R.drawable.draw_radius_cost_info);
        // set the custom dialog components - text, image and draw_button
        EditText placeName=(EditText)dialog.findViewById(R.id.placeName);
        EditText StreetAddress=(EditText)dialog.findViewById(R.id.StreetAddress);

        placeName.setText(place);
        StreetAddress.setText(PlaceAddress);

        TextView dialogButton = (TextView) dialog.findViewById(R.id.dialogOK);
        // if draw_button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
// custom dialog

    }

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

答:
View v inside onClick is of type android.view.View, while your FavoritePresenter is expecting a FavoritePresenter.View. To fix, create FavoritePresenter instance passing along FavoritePresenter.View type:

```<code>    holder.DeleteFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fav_GetAddress(addressSearchModel.getName(), addressSearchModel.getRegions());
            FavoritePresenter favoritePresenter=new FavoritePresenter(FavoriteAdapter.this);
            favoritePresenter.deleteFavorite(addressSearchModel);
        }
    });
</code>```

Title: how to handle adapter in MVP pattern

Body:
I'm going to create my first real MVP app. the problem that i have is with adapter. i have a button on my recyclerview card which i implement the onclick method in adapter and now the problem is with adapter. i don't know why when i implement the view interface that i made it in the presenter part of my app. i get error while i want to pass view to presenter.
this is my error

this is what everything that i did:
in my fragment:

public class FavoritFragment extends Fragment implements FavoritePresenter.View{
    View rootView;

    FavoritePresenter favoritePresenter;
    public FavoritFragment() {
        // Required empty public constructor
    }

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

        favoritePresenter.getAddressSearchModel();

    return view;
    }

    @Override
    public void updateFavoriteRecycler(ArrayList<AddressSearchModel> info) {

        RecyclerView recyclerView=(RecyclerView)rootView.findViewById(R.id.address_recyclerview);
        FavoriteAdapter adapterClass;
        adapterClass=new FavoriteAdapter(info,getActivity(),rootView);
        RecyclerView.LayoutManager LayoutManager= new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(LayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new
                DividerItemDecoration(rootView.getContext(),LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapterClass);
        adapterClass.notifyDataSetChanged();
    }

    @Override
    public void deleteFavorite(ArrayList<AddressSearchModel> id) {

    }

}

in my presenter

public class FavoritePresenter {
    // use this class to make networkCall Catch data and so on
    View view;

    ArrayList<AddressSearchModel> addressSearchModel;
    public FavoritePresenter(View view){
        this.view=view;
        addressSearchModel=new ArrayList<>();
    }

    public void getAddressSearchModel()
    {
        addressSearchModel=PreparData();
        view.updateFavoriteRecycler(this.addressSearchModel);
    }
    /**
     *   do the network call and delete favorite and then do another network call to update it.
     *      The better ways is to catch data and sort it base on update field and then send update field
     *   to ruby part and in ruby take the rest of field base on update_at field (better performance)
     */
    public void deleteFavorite(AddressSearchModel favoriteId){
        addressSearchModel=deleteData();
        view.deleteFavorite(this.addressSearchModel);
    }
    private ArrayList<AddressSearchModel> deleteData() {
        ArrayList<AddressSearchModel> lst_SearchResult=new ArrayList<>();;
        AddressSearchModel model=new AddressSearchModel();
        model.setName("sasd");
        model.setAddress("sdsaqweqweqwds");
        model.setRegions("asdfdgdfgqweqwedfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");

        lst_SearchResult.add(model);
        model=new AddressSearchModel();
        model.setName("sas21312dqweqwe");
        model.setAddress("sdsaderers");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        return lst_SearchResult;
    }
    //call network call using this method to update recyclerview
    private ArrayList<AddressSearchModel> PreparData() {
        ArrayList<AddressSearchModel> lst_SearchResult=new ArrayList<>();;
        AddressSearchModel model=new AddressSearchModel();
        model.setName("sasd");
        model.setAddress("sdsads");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");

        lst_SearchResult.add(model);
        model=new AddressSearchModel();
        model.setName("sas21312d");
        model.setAddress("sdsaderers");
        model.setRegions("asdfdgdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        model=new AddressSearchModel();
        model.setName("saweresd");
        model.setAddress("sdsererads");
        model.setRegions("asdfdgererdfgdfasgfad");
        model.setWorkingHours("2412312312");
        model.setTelephone("22211111");
        lst_SearchResult.add(model);

        return lst_SearchResult;
    }
    public interface  View
    {
        void updateFavoriteRecycler(ArrayList<AddressSearchModel>  info);

        //i get String as id because of UUID type format in ruby on rails
        void deleteFavorite(ArrayList<AddressSearchModel> id);
    }
}

and in my adapter:

public class FavoriteAdapter extends RecyclerView.Adapter<FavoriteAdapter.MyHolder> implements FavoritePresenter.View {
    private List<AddressSearchModel> doctorList;
    public Activity activity;
    public View rootView;
    public FavoriteAdapter(List<AddressSearchModel> doctorList, Activity activity,View view)
    {
        rootView=view;
        this.activity=activity;
        this.doctorList=doctorList;
    }

    class MyHolder extends RecyclerView.ViewHolder{
        public ImageView mArticleImage;
        public TextView drugstore_desc;
        public Button DeleteFavorite;
        public MyHolder(View itemView) {
            super(itemView);
            mArticleImage=(ImageView)itemView.findViewById(R.id.im_article);
            drugstore_desc=(TextView)itemView.findViewById(R.id.drugstore_desc);
            DeleteFavorite=(Button)itemView.findViewById(R.id.DeleteFavorite);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cardview_address_montakhab,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(final MyHolder holder, final int position) {
        final AddressSearchModel addressSearchModel =doctorList.get(position);
        Log.d("Doctore_Size", String.valueOf(doctorList.size()));
        //holder.ImageView.setText(addressSearchModel.getName());
        holder.drugstore_desc.setText(addressSearchModel.getRegions());

        holder.DeleteFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fav_GetAddress(addressSearchModel.getName(), addressSearchModel.getRegions());
                FavoritePresenter favoritePresenter=new FavoritePresenter(v);
                favoritePresenter.deleteFavorite(addressSearchModel);
            }
        });
    }

    @Override
    public void deleteFavorite(ArrayList<AddressSearchModel> id) {

    }
    @Override
    public void updateFavoriteRecycler(ArrayList<AddressSearchModel> info) {
        RecyclerView recyclerView=(RecyclerView)activity.findViewById(R.id.address_recyclerview);
        FavoriteAdapter adapterClass;
        adapterClass=new FavoriteAdapter(info,activity,rootView);
        RecyclerView.LayoutManager LayoutManager= new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(LayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new
                DividerItemDecoration(activity,LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(adapterClass);
        adapterClass.notifyDataSetChanged();
    }

    public  void fav_GetAddress(String place,String PlaceAddress){
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(R.layout.dialog_add_address);
        dialog.getWindow().setBackgroundDrawableResource(R.drawable.draw_radius_cost_info);
        // set the custom dialog components - text, image and draw_button
        EditText placeName=(EditText)dialog.findViewById(R.id.placeName);
        EditText StreetAddress=(EditText)dialog.findViewById(R.id.StreetAddress);

        placeName.setText(place);
        StreetAddress.setText(PlaceAddress);

        TextView dialogButton = (TextView) dialog.findViewById(R.id.dialogOK);
        // if draw_button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
// custom dialog

    }

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

Body:
View v inside onClick is of type android.view.View, while your FavoritePresenter is expecting a FavoritePresenter.View. To fix, create FavoritePresenter instance passing along FavoritePresenter.View type:

    holder.DeleteFavorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fav_GetAddress(addressSearchModel.getName(), addressSearchModel.getRegions());
            FavoritePresenter favoritePresenter=new FavoritePresenter(FavoriteAdapter.this);
            favoritePresenter.deleteFavorite(addressSearchModel);
        }
    });


问:
How can I delete a Vertex in Gremlin Server Titan 1.0
I'm using Titan 1.0 Version and Gremlin Server with REST Api for creating and updating Vertex details.
How can I delete the vertex using vertexId?</p>

答:
You can use :

```<code> g.V().hasId(vertexId).drop()
</code>```

In the hasId method pass the id of the vertex you want to delete

Body:
You can use :

 g.V().hasId(vertexId).drop()

In the hasId method pass the id of the vertex you want to delete


问:
How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

答:
By tweaking just a little your positionTop and positionLeft variable, I managed to keep the square inside. You just need to change the maximum % that it needs to have to not exceed the container. I found that 75% for the top and 80% for the left seems to be the max!

```<code>var positionTop = Math.floor(Math.random() * 75)   ;
var positionLeft = Math.random() * 80;
</code>```

Here's a fiddle

Body:
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

Body:
By tweaking just a little your positionTop and positionLeft variable, I managed to keep the square inside. You just need to change the maximum % that it needs to have to not exceed the container. I found that 75% for the top and 80% for the left seems to be the max!

var positionTop = Math.floor(Math.random() * 75)   ;
var positionLeft = Math.random() * 80;

Here's a fiddle


问:
Android - Importing contacts through vCards via ADB
I am currently trying to automate some Android actions through ADB and getting stuck with the contact import through vCards. There are 2 ways of doing this :

automate the exact "tappings" of the user, which supposes you have to determine the position of each "button" according to the screen resolution, etc. It is what I have done right now but it really seem hard to maintain, since there are too much parameters to take into account (custom roms, wierd resolutions, portrait/landscape mod, etc).

find what's happening when you click on "import contact from vCards" and do this action through ADB

Basically, I would like to apply the 2nd option, but I don't know what is happening when you click on "import contacts from vCard", which I would need to call the same action/intent from ADB. Any idea on the ADB command I should execute ?

答:
Selected answer didn't work for me. I needed that functionality for several specific tests. So what I did is added Override BeforeSuite to test class inside which I called methods from the below classes and called super class method after.

```<code>public class AdbUtils {
private static final String CH_DIR = "cd ";
private static final String LOCATE_ADB = "locate -r ~/\".*platform-tools/adb\"";

public static void createContacts(List<Contact> contacts) throws Exception {
    for (int i = 0; i < contacts.size(); i++) {
        if (i < contacts.size() - 1) {
            System.out.println(executeCommand(AdbCommands.CREATE_AND_SAVE_CONTACT
                    .getCommand(new String[]{contacts.get(i).getName(), contacts.get(i).getPhoneNumber()})));
        } else {
            System.out.println(executeCommand(AdbCommands.CREATE_AND_SAVE_CONTACT
                    .getCommand(new String[]{contacts.get(i).getName(), contacts.get(i).getPhoneNumber()})));
            System.out.println(executeCommand(AdbCommands.START_CONTACTS_APP_LIST_STATE.getCommand(null)
                    + " && " + AdbCommands.SLEEP.getCommand(new String[]{"3"})
                    + " && " + AdbCommands.PRESS_BACK_BUTTON.getCommand(null)));
        }
    }
}

public static void removeAllContacts() {
   System.out.println("DEBUG - Delete all contacts: " + executeCommand(new String[]{AdbCommands.DELETE_ALL_CONTACTS_CMD.getCommand(null)}));
}

private static String executeCommand(String command) {
    return executeCommand(new String[]{command});
}

private static String executeCommand(String[] commandLines) {
    String adbDir = locatePlatformToolsAdb();
    adbDir = adbDir.substring(0, adbDir.length() - 4);

    String[] command = new String[commandLines.length + 2];
    command[0] = "bash";
    command[1] = "-c";
    commandLines[0] = CH_DIR + adbDir + " && " + commandLines[0];
    System.arraycopy(commandLines, 0, command, 2, commandLines.length + 2 - 2);

    String input;
    String errorInput = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(command);
        proc.waitFor();

        input = parseInputStream(proc.getInputStream());
        errorInput = parseInputStream(proc.getErrorStream());
        proc.destroy();
        return input;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return errorInput;
}

private static String locatePlatformToolsAdb() {
    String path = null;
    String error = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(new String[]{"bash", "-c", LOCATE_ADB});
        proc.waitFor();

        path = parseInputStream(proc.getInputStream());
        error = parseInputStream(proc.getErrorStream());
        proc.destroy();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    if(null != path){
        System.out.println("DEBUG - Located platform tools: " + path);
        return path;
    }
    else throw new IllegalStateException("DEBUG - error locating adb: " + error);
}

private static String parseInputStream(InputStream input) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        StringBuilder resultBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            resultBuilder.append(line);
        }

        return resultBuilder.toString();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}
</code>```

}

and

```<code>public enum AdbCommands {

WAIT("./adb shell wait"),
SLEEP("./adb shell sleep %s"),
DELETE_ALL_CONTACTS_CMD("./adb shell pm clear com.android.providers.contacts"),
START_CONTACTS_APP_LIST_STATE("./adb shell am start com.android.contacts"),
PRESS_RECENT_BUTTON("./adb shell input keyevent 187"),
PRESS_HOME_BUTTON("./adb shell input keyevent 3"),
PRESS_BACK_BUTTON("./adb shell input keyevent 4"),
CREATE_CONTACT("./adb shell am start -a android.intent.action.INSERT -t vnd.android.cursor.dir/contact " + "-e name '%s' -e phone %s"),
CREATE_AND_SAVE_CONTACT(CREATE_CONTACT.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_RECENT_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_RECENT_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_BACK_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"}));

private String command;
private static final String arg = "%s";

AdbCommands(String command){ this.command = command; }

public String getCommand(@Nullable String[] args){
    String command = this.command;
    if(null == args) {
        return this.command;
    }
    else{
        if(countSubstring(this.command, arg) != args.length) throw new IllegalArgumentException("wrong args count!");
        for (String arg : args) {
            command = command.replaceFirst(AdbCommands.arg, arg);
        }
        return command;
    }
}

private int countSubstring(String str, final String subStr){
    int lastIndex = 0;
    int count = 0;

    while(lastIndex != -1){
        lastIndex = str.indexOf(subStr,lastIndex);
        if(lastIndex != -1){
            count ++;
            lastIndex += subStr.length();
        }
    }
    return count;
}
</code>```

}

Body:
Selected answer didn't work for me. I needed that functionality for several specific tests. So what I did is added Override BeforeSuite to test class inside which I called methods from the below classes and called super class method after.

public class AdbUtils {
private static final String CH_DIR = "cd ";
private static final String LOCATE_ADB = "locate -r ~/\".*platform-tools/adb\"";

public static void createContacts(List<Contact> contacts) throws Exception {
    for (int i = 0; i < contacts.size(); i++) {
        if (i < contacts.size() - 1) {
            System.out.println(executeCommand(AdbCommands.CREATE_AND_SAVE_CONTACT
                    .getCommand(new String[]{contacts.get(i).getName(), contacts.get(i).getPhoneNumber()})));
        } else {
            System.out.println(executeCommand(AdbCommands.CREATE_AND_SAVE_CONTACT
                    .getCommand(new String[]{contacts.get(i).getName(), contacts.get(i).getPhoneNumber()})));
            System.out.println(executeCommand(AdbCommands.START_CONTACTS_APP_LIST_STATE.getCommand(null)
                    + " && " + AdbCommands.SLEEP.getCommand(new String[]{"3"})
                    + " && " + AdbCommands.PRESS_BACK_BUTTON.getCommand(null)));
        }
    }
}

public static void removeAllContacts() {
   System.out.println("DEBUG - Delete all contacts: " + executeCommand(new String[]{AdbCommands.DELETE_ALL_CONTACTS_CMD.getCommand(null)}));
}

private static String executeCommand(String command) {
    return executeCommand(new String[]{command});
}

private static String executeCommand(String[] commandLines) {
    String adbDir = locatePlatformToolsAdb();
    adbDir = adbDir.substring(0, adbDir.length() - 4);

    String[] command = new String[commandLines.length + 2];
    command[0] = "bash";
    command[1] = "-c";
    commandLines[0] = CH_DIR + adbDir + " && " + commandLines[0];
    System.arraycopy(commandLines, 0, command, 2, commandLines.length + 2 - 2);

    String input;
    String errorInput = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(command);
        proc.waitFor();

        input = parseInputStream(proc.getInputStream());
        errorInput = parseInputStream(proc.getErrorStream());
        proc.destroy();
        return input;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return errorInput;
}

private static String locatePlatformToolsAdb() {
    String path = null;
    String error = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec(new String[]{"bash", "-c", LOCATE_ADB});
        proc.waitFor();

        path = parseInputStream(proc.getInputStream());
        error = parseInputStream(proc.getErrorStream());
        proc.destroy();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    if(null != path){
        System.out.println("DEBUG - Located platform tools: " + path);
        return path;
    }
    else throw new IllegalStateException("DEBUG - error locating adb: " + error);
}

private static String parseInputStream(InputStream input) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        StringBuilder resultBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            resultBuilder.append(line);
        }

        return resultBuilder.toString();
    }
    catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

}

and

public enum AdbCommands {

WAIT("./adb shell wait"),
SLEEP("./adb shell sleep %s"),
DELETE_ALL_CONTACTS_CMD("./adb shell pm clear com.android.providers.contacts"),
START_CONTACTS_APP_LIST_STATE("./adb shell am start com.android.contacts"),
PRESS_RECENT_BUTTON("./adb shell input keyevent 187"),
PRESS_HOME_BUTTON("./adb shell input keyevent 3"),
PRESS_BACK_BUTTON("./adb shell input keyevent 4"),
CREATE_CONTACT("./adb shell am start -a android.intent.action.INSERT -t vnd.android.cursor.dir/contact " + "-e name '%s' -e phone %s"),
CREATE_AND_SAVE_CONTACT(CREATE_CONTACT.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_RECENT_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_RECENT_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"})
        + " && ./" + PRESS_BACK_BUTTON.getCommand(null) + " && ./" + SLEEP.getCommand(new String[]{"3"}));

private String command;
private static final String arg = "%s";

AdbCommands(String command){ this.command = command; }

public String getCommand(@Nullable String[] args){
    String command = this.command;
    if(null == args) {
        return this.command;
    }
    else{
        if(countSubstring(this.command, arg) != args.length) throw new IllegalArgumentException("wrong args count!");
        for (String arg : args) {
            command = command.replaceFirst(AdbCommands.arg, arg);
        }
        return command;
    }
}

private int countSubstring(String str, final String subStr){
    int lastIndex = 0;
    int count = 0;

    while(lastIndex != -1){
        lastIndex = str.indexOf(subStr,lastIndex);
        if(lastIndex != -1){
            count ++;
            lastIndex += subStr.length();
        }
    }
    return count;
}

}


问:
How to add syntax highlighting for custom methods in Atom for Ruby
For example, in the following class, I want syntax highlighting for
helper_method(@x, @y) (line 1 in the main method.)

```<code>class test
  def new(x, y)
    @x = x
    @y = y
  end

  def main
    result = helper_method(@x, @y)
    puts result
  end

  def helper_method(x, y)
    // do stuff with x, y
  end
end
</code>```

I wonder why the current highlighting scheme doesn't do that as it seems valuable to me to see where I call my methods and where I just use baked-in commands and expressions. Can I change that, for Atom?

Here some screenshots to further illustrate my problem:

In the first screenshot I expect get_time_limit_for_source(order_source) to be highlighted:

It is a method that is defined in the same class:

Interestingly, in my example code, the highlighting is exactly as I want it:

The highlighting in the test class is as I want it, but in this case is due to the use of the helper word which triggers highlighting when language-ruby-on-rails is installed/activated.

答:
Atom is an Electron app, based on Chrome. Feel free to press Ctrl+Shift+I and examine whatever you want with Chrome Developer Tools:

As you can see, the local method call is not granted with any class, therefore it is impossible to style it without patching the syntax highlighter. For those elements having the class[es], one might simply Edit ⇒ Stylesheet in the main menu and update the CSS.

Body:
For example, in the following class, I want syntax highlighting for
helper_method(@x, @y) (line 1 in the main method.)

class test
  def new(x, y)
    @x = x
    @y = y
  end

  def main
    result = helper_method(@x, @y)
    puts result
  end

  def helper_method(x, y)
    // do stuff with x, y
  end
end

I wonder why the current highlighting scheme doesn't do that as it seems valuable to me to see where I call my methods and where I just use baked-in commands and expressions. Can I change that, for Atom?

Here some screenshots to further illustrate my problem:

In the first screenshot I expect get_time_limit_for_source(order_source) to be highlighted:

It is a method that is defined in the same class:

Interestingly, in my example code, the highlighting is exactly as I want it:

The highlighting in the test class is as I want it, but in this case is due to the use of the helper word which triggers highlighting when language-ruby-on-rails is installed/activated.


问:
How are 3D games so efficient?
There is something I have never understood. How can a great big PC game like GTA IV use 50% of my CPU and run at 60fps while a DX demo of a rotating Teapot @ 60fps uses a whopping 30% ? </p>

答:
I think you should take a look to GPU utilisation rather than CPU... I bet the graphic card is much busier in GTA IV than in the Teapot sample (it should be practically idle).

Maybe you could use something like this monitor to check that:

http://downloads.guru3d.com/Rivatuner-GPU-Monitor-Vista-Sidebar-Gadget-download-2185.html

Also the framerate is something to consider, maybe the teapot sample is running at full speed (maybe 1000fps) and most games are limited to the refresh frequency of the monitor (about 60fps).

Title: How are 3D games so efficient?

ContentLicense: CC BY-SA 2.5


问:
Binary Partitioning n sorted data points in to b Buckets in `O(b.log(n))`
Given sorted randomly accessible input data (a sorted array) of size n, I'd like to partition this in to buckets using a parameterised partitioning function. I want the result back as an array of indexes to the bucket edges.

The partitioning function returns a bool to indicate if too values should be in the same partition or not.

Note that prior to partitioning, we don't know how many buckets will be required:

It is possible that all the input should be placed in a single bucket.

It may be the case that every input needs its own bucket.

Perhaps the first value needs one bucket and the whole remainder of the array is in a second bucket.

… this is not know before running the partitioning algorithm.

As a concrete example, lets say we have the partitioning function:

```<code>sameBucket(a, b) = (a/10 == b/10)
</code>```

Where / is integer division (it rounds down). So

```<code>sameBucket(0,1) == yes
sameBucket(1,2) == yes
sameBucket(0,9) == yes
sameBucket(0,10) == no
</code>```

The partition function tells us 0 and 10 should not be placed in to the same bucket.

Consider this input array shown with its indexes underneath for clarity (I assume a "past the end" index called end):

```<code>[1, 3, 7, 14, 90, 91, 92, 93, 95, 99]
 0  1  2  3   4   5   6   7   8   9   end
</code>```

For this data, the elements that are members of a new bucket are indicated with a ^:

```<code>[1, 3, 7, 14, 90, 91, 92, 93, 95, 99]
 0  1  2  3   4   5   6   7   8   9   end
 ^        ^   ^                       ^
</code>```

If I use the partition function above, I'd get back just the indexes that begin a new bucket:

```<code>[0, 3, 4, end]
</code>```

Each index in the result array represents the first element that the bucket function says is not in the same bucket as the element before it.

The whole data is represented by the range 0…<end.

The range 0…<3 are the numbers [1, 3, 7], which are all 0, when divided by 10.

The range 3…<4 is the single number 14, which is 1 when divided by 10.

The range 4…<end are the numbers [90, 91, 92, 93, 95, 99], which are all 0 when divided by 10.

I believe a modified binary search should be able to perform this partitioning efficiently. For n input values, and b output buckets, the run time should be at worst O(b.log(n)). Does any one have an algorithm for it, even just the name, so I can look it up?

答:
Thanks to dasblinkenlight for their answer.

I was pretty sure that there was an algorithm for this with better big O performance than the approach they gave (which does have the asymtotic complexity I mentioned in the OP). I wrote it last night, and it goes like this.

```<code>bucket_starts(in_inclusive_range: r)
{
  if r.count is 0 or 1 elements
  {
    // There are no bucket starts in this range.
    // Return an empty array.
    return []
  }
  else
  {
    // If `r`'s start & end elements are in the same bucket
    // then `r` contains no bucket starts.
    if same_bucket(element_at[r.first_index], element_at[r.last_index])
    {
      // There are no buckets in this range.
      return []
    }
    else
    {
      // `r` has 1 or more buckets in it. Subdivide and find them.
      // Note that `midpoint` is in both lower & upper ranges.
      let first_subrange = range(from: r.first_index to: r.mid_index)
      let second_subrange = range(from: r.mid_index to: r.last_index)
      return bucket_starts(in_inclusive_range: first_subrange) +
             bucket_starts(in_inclusive_range: second_subrange)
    }
  }
}
</code>```

Time Complexity

If the input has n elements, and contains b different buckets, then (I believe) the runtime complexity of the algorithm is worst case O(b.log(n/b)).

In the limiting case that every input element falls in a different bucket, b == n and the cost becomes linear in n.

For a given b, the worst case complexity occurs when all the bucket have uniform size. If most of the buckets are small and a few are large, the run time complexity will be reduced.

For a sequence of output bucket sizes B, where sum(B) == n, the complexity will be something like: O(sum_of_logs_of_B).

In the extreme case of b-1 buckets of size 1, and a 1 larger bucket size n-b, this will approach O(b + log(n))

This seems like a nice complexity behaviour. It adapts to the specifics of the content and has absolute worst case time performance linear in input size.

I don't know if there's a name for this – I very much doubt it is original! If you know the name, I'd like to know what it is.

Space complexity

The space complexity needed for the algorithm (not it's input or output) is O(log(n)), so is overwhelmed by the linear storage for input and output.

Body:
Given sorted randomly accessible input data (a sorted array) of size n, I'd like to partition this in to buckets using a parameterised partitioning function. I want the result back as an array of indexes to the bucket edges.

The partitioning function returns a bool to indicate if too values should be in the same partition or not.

Note that prior to partitioning, we don't know how many buckets will be required:

It is possible that all the input should be placed in a single bucket.

It may be the case that every input needs its own bucket.

Perhaps the first value needs one bucket and the whole remainder of the array is in a second bucket.

… this is not know before running the partitioning algorithm.

As a concrete example, lets say we have the partitioning function:

sameBucket(a, b) = (a/10 == b/10)

Where / is integer division (it rounds down). So

sameBucket(0,1) == yes
sameBucket(1,2) == yes
sameBucket(0,9) == yes
sameBucket(0,10) == no

The partition function tells us 0 and 10 should not be placed in to the same bucket.

Consider this input array shown with its indexes underneath for clarity (I assume a "past the end" index called end):

[1, 3, 7, 14, 90, 91, 92, 93, 95, 99]
 0  1  2  3   4   5   6   7   8   9   end

For this data, the elements that are members of a new bucket are indicated with a ^:

[1, 3, 7, 14, 90, 91, 92, 93, 95, 99]
 0  1  2  3   4   5   6   7   8   9   end
 ^        ^   ^                       ^

If I use the partition function above, I'd get back just the indexes that begin a new bucket:

[0, 3, 4, end]

Each index in the result array represents the first element that the bucket function says is not in the same bucket as the element before it.

The whole data is represented by the range 0…<end.

The range 0…<3 are the numbers [1, 3, 7], which are all 0, when divided by 10.

The range 3…<4 is the single number 14, which is 1 when divided by 10.

The range 4…<end are the numbers [90, 91, 92, 93, 95, 99], which are all 0 when divided by 10.

I believe a modified binary search should be able to perform this partitioning efficiently. For n input values, and b output buckets, the run time should be at worst O(b.log(n)). Does any one have an algorithm for it, even just the name, so I can look it up?

Body:
Thanks to dasblinkenlight for their answer.

I was pretty sure that there was an algorithm for this with better big O performance than the approach they gave (which does have the asymtotic complexity I mentioned in the OP). I wrote it last night, and it goes like this.

bucket_starts(in_inclusive_range: r)
{
  if r.count is 0 or 1 elements
  {
    // There are no bucket starts in this range.
    // Return an empty array.
    return []
  }
  else
  {
    // If `r`'s start & end elements are in the same bucket
    // then `r` contains no bucket starts.
    if same_bucket(element_at[r.first_index], element_at[r.last_index])
    {
      // There are no buckets in this range.
      return []
    }
    else
    {
      // `r` has 1 or more buckets in it. Subdivide and find them.
      // Note that `midpoint` is in both lower & upper ranges.
      let first_subrange = range(from: r.first_index to: r.mid_index)
      let second_subrange = range(from: r.mid_index to: r.last_index)
      return bucket_starts(in_inclusive_range: first_subrange) +
             bucket_starts(in_inclusive_range: second_subrange)
    }
  }
}

Time Complexity

If the input has n elements, and contains b different buckets, then (I believe) the runtime complexity of the algorithm is worst case O(b.log(n/b)).

In the limiting case that every input element falls in a different bucket, b == n and the cost becomes linear in n.

For a given b, the worst case complexity occurs when all the bucket have uniform size. If most of the buckets are small and a few are large, the run time complexity will be reduced.

For a sequence of output bucket sizes B, where sum(B) == n, the complexity will be something like: O(sum_of_logs_of_B).

In the extreme case of b-1 buckets of size 1, and a 1 larger bucket size n-b, this will approach O(b + log(n))

This seems like a nice complexity behaviour. It adapts to the specifics of the content and has absolute worst case time performance linear in input size.

I don't know if there's a name for this – I very much doubt it is original! If you know the name, I'd like to know what it is.

Space complexity

The space complexity needed for the algorithm (not it's input or output) is O(log(n)), so is overwhelmed by the linear storage for input and output.


问:
Delphi Protocol Buffers?
Does anyone know of a project to do a Google Protocol Buffers implementation in Delphi?</p>

答:
I found another one on the github. (developped from Feb.2014 to Jul.2016, as of June 2017)

It seems to have preliminary proto3 support.

I didn't test yet, but it may be the best as of today.

https://github.com/stijnsanders/DelphiProtocolBuffer

EDIT:
I tested this but it seems to be written in old delphi and not unicode ready.

I could compile the generator (using 10 Seattle), but compiled exe couldn't generate pas file :-(

EDIT2:

The code generator works just replacing TStream to TStreamReader/Writer.
I confirmed generator can convert recent address book sample.

```<code>diff --git a/ProtBufParse.pas b/ProtBufParse.pas
index f29d7c7..cdd734d 100644
--- a/ProtBufParse.pas
+++ b/ProtBufParse.pas
@@ -236,16 +236,13 @@ var

   procedure LoadCode;
   var
-    f:TFileStream;
+    sr:TStreamReader;
   begin
-    f:=TFileStream.Create(FilePath,fmOpenRead or fmShareDenyWrite);
+    sr:=TStreamReader.Create(FilePath, True{DetectBOM});
     try
-      //TODO: UTF-8? UTF-16?
-      CodeL:=f.Size;
-      SetLength(Code,CodeL);
-      if f.Read(Code[1],CodeL)<>CodeL then RaiseLastOSError;
+      Code := sr.ReadToEnd;
     finally
-      f.Free;
+      sr.Free;
     end;
   end;

diff --git a/dpbp.dpr b/dpbp.dpr
index 4049480..b6dab90 100644
--- a/dpbp.dpr
+++ b/dpbp.dpr
@@ -22,7 +22,7 @@ var
   p:TProtocolBufferParser;
   s,t,InputFN,OutputFN,RelPath:string;
   i,j,l,l1:integer;
-  f:TFileStream;
+  sw:TStreamWriter;
   fv:TProtocolBufferParserValue;
   ff:TProtocolBufferParserFlag;
   Flags:TProtocolBufferParserFlags;
@@ -134,11 +134,12 @@ begin

         writeln('Writing '+OutputFN);
         s:=p.GenerateUnit(Flags);
-        f:=TFileStream.Create(OutputFN,fmCreate);
+
+        sw:=TStreamWriter.Create(OutputFN,False,TEncoding.UTF8);
         try
-          f.Write(s[1],Length(s));
+          sw.Write(s);
         finally
-          f.Free;
+          sw.Free;
         end;

       finally
</code>```

Title: Delphi Protocol Buffers?

Body:
I found another one on the github. (developped from Feb.2014 to Jul.2016, as of June 2017)

It seems to have preliminary proto3 support.

I didn't test yet, but it may be the best as of today.

https://github.com/stijnsanders/DelphiProtocolBuffer

EDIT:
I tested this but it seems to be written in old delphi and not unicode ready.

I could compile the generator (using 10 Seattle), but compiled exe couldn't generate pas file :-(

EDIT2:

The code generator works just replacing TStream to TStreamReader/Writer.
I confirmed generator can convert recent address book sample.

diff --git a/ProtBufParse.pas b/ProtBufParse.pas
index f29d7c7..cdd734d 100644
--- a/ProtBufParse.pas
+++ b/ProtBufParse.pas
@@ -236,16 +236,13 @@ var

   procedure LoadCode;
   var
-    f:TFileStream;
+    sr:TStreamReader;
   begin
-    f:=TFileStream.Create(FilePath,fmOpenRead or fmShareDenyWrite);
+    sr:=TStreamReader.Create(FilePath, True{DetectBOM});
     try
-      //TODO: UTF-8? UTF-16?
-      CodeL:=f.Size;
-      SetLength(Code,CodeL);
-      if f.Read(Code[1],CodeL)<>CodeL then RaiseLastOSError;
+      Code := sr.ReadToEnd;
     finally
-      f.Free;
+      sr.Free;
     end;
   end;

diff --git a/dpbp.dpr b/dpbp.dpr
index 4049480..b6dab90 100644
--- a/dpbp.dpr
+++ b/dpbp.dpr
@@ -22,7 +22,7 @@ var
   p:TProtocolBufferParser;
   s,t,InputFN,OutputFN,RelPath:string;
   i,j,l,l1:integer;
-  f:TFileStream;
+  sw:TStreamWriter;
   fv:TProtocolBufferParserValue;
   ff:TProtocolBufferParserFlag;
   Flags:TProtocolBufferParserFlags;
@@ -134,11 +134,12 @@ begin

         writeln('Writing '+OutputFN);
         s:=p.GenerateUnit(Flags);
-        f:=TFileStream.Create(OutputFN,fmCreate);
+
+        sw:=TStreamWriter.Create(OutputFN,False,TEncoding.UTF8);
         try
-          f.Write(s[1],Length(s));
+          sw.Write(s);
         finally
-          f.Free;
+          sw.Free;
         end;

       finally


问:
How to add a byte array resource from DB to a KieFileSystem and build a KieBuilder?
I am using drools 6.2. I am getting a Run time exception when I try to write it as </p>

```<code>kFile = kService.newKieFileSystem();
resource = kService.getResources().newByteArrayResource(drlFileData)
    .setResourceType(ResourceType.DRL);
kFile.write(resource);
</code>```

答:
It is difficult for the KieFileSystem to determine a path name from a mere byte array. Therefore, provide a path name:</p>

```<code>kfs.write( "src/main/resources/whatever.drl", resource );
</code>```

Body:
I am using drools 6.2. I am getting a Run time exception when I try to write it as

kFile = kService.newKieFileSystem();
resource = kService.getResources().newByteArrayResource(drlFileData)
    .setResourceType(ResourceType.DRL);
kFile.write(resource);

Body:
It is difficult for the KieFileSystem to determine a path name from a mere byte array. Therefore, provide a path name:

kfs.write( "src/main/resources/whatever.drl", resource );


问:
C# writeline cap
I am writing a program that writes to a file that requires specific positions:

it looks something like:

```<code>writer.WriteLine("{0,-3}{1,-5}{2,-30}", data1, data2, data3);
</code>```

The positions that it starts is correct however, if data1 exceeds 3 character, it pushes the format by the exceeded amount,

Is there a way to make data1 cap at 3 characters and ignore any excess characters using the writeline format?

答:
Use string.Substring. This code trims the string if it's longer than 3 characters:

```<code>Console.WriteLine("{0,-3}{1,-5}{2,-30}",
                  data1.Substring(0,data1.Length > 3 ? 3 : data1.Length),
                  data2, data3);
</code>```

Title: C# writeline cap

Body:
I am writing a program that writes to a file that requires specific positions:

it looks something like:

writer.WriteLine("{0,-3}{1,-5}{2,-30}", data1, data2, data3);

The positions that it starts is correct however, if data1 exceeds 3 character, it pushes the format by the exceeded amount,

Is there a way to make data1 cap at 3 characters and ignore any excess characters using the writeline format?

Body:
Use string.Substring. This code trims the string if it's longer than 3 characters:

Console.WriteLine("{0,-3}{1,-5}{2,-30}",
                  data1.Substring(0,data1.Length > 3 ? 3 : data1.Length),
                  data2, data3);


问:
why it returns empty value but of boolean type when no match is found
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?</p>

```<code>$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);
</code>```

答:
http://php.net/manual/en/function.array-search.php

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

When converting to boolean, the following values are considered FALSE:

```<code>the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
</code>```

Every other value is considered TRUE (including any resource and NAN).

Body:
I am using the following code to search an element inside a multi dimensional array.When a match is found it returns the index.But when no match is found it returns a empty value.Not 0 or 1.But if i print out the type , it says boolean.What does that boolean mean if it returns empty.Does it mean that it will be equal to empty string ?

$arr =Array
(
    0 => Array
        (
            'uid' => '100',
            'name' => 'Sandra Shush'
        ),

    1 => Array
        (
            'uid' => '5465',
            'name' => 'Stefanie Mcmohn'
        ),

    2 => Array
        (
            'uid' => '40489',
            'name' => 'Michael'
        )
);

$match = array_search('546',array_column($arr, 'uid'));

echo gettype($match);

Body:
http://php.net/manual/en/function.array-search.php

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer 0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
the special type NULL (including unset variables)
SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource and NAN).


问:
Change route shape by dragging it
I'm looking for an example of a draggable route using the HERE Maps V3 API. I want to be able to add waypoints anywhere on the route, not only drag it's start and end points.

On the API Reference, there is a RouteRepresentationModeType called dragNDrop, but I have no idea where to start.

Thanks in advance.

答:
You can handle click events on the route line to :

add a new waypoint where the user has clicked

recompute the route

hide the old route and display the new one

Then you can handle drag/drop events on the waypoint and do the recompute on "dragend" event.

Title: Change route shape by dragging it


问:
What does this 'static' mean and why is it like that
```<code>public class tt {
static{
    System.out.println("class tt");
    }
}
</code>```

It the first time ive come across it and im wondering what it is and what it's used for

答:
here is the static initializer  tutorial http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

It runs when the class is loaded before the initialization.

```<code>public class A {

    static {
        System.out.println("A from static initializer"); // first
    }

    public A(){
        System.out.println("A"); // second
    }

    public static void main(String[] args){
        new A();
    }
}
</code>```

Body:
public class tt {
static{
    System.out.println("class tt");
    }
}

It the first time ive come across it and im wondering what it is and what it's used for

Body:
here is the static initializer  tutorial http://download.oracle.com/javase/tutorial/java/javaOO/initial.html

It runs when the class is loaded before the initialization.

public class A {

    static {
        System.out.println("A from static initializer"); // first
    }

    public A(){
        System.out.println("A"); // second
    }

    public static void main(String[] args){
        new A();
    }
}


问:
requirejs + django_select2
I'm building a wagtail / django app using requirejs as js assets combiner, for the site front end.

I'm using it because I've ever been in a kind of JS dependencies hell, where nothing works because of multiple versions of same libs loaded, from different django apps... (I don't even know if it is a good solution)

I've to tell that I'm not a JS expert, and I've none arround me :(
I'm using the good old templates to render the pages, not using angular, react, riot nor vue : I'm a pretty old school dev :)

I've already adapted some scripts to use require, but I'm stuck for now...

I've installed the django_select2 application, and I'm trying to adapt the django_select2.js asset.

I've loaded select2 through bower, and I've updaetd my config.js:

```<code>"shim": {
    select2: {
            deps: ["jquery"],
            exports: "$.fn.select2"
    }
},
paths: {
    ...
    select2: "select2/dist/js/select2"
}
</code>```

Then I'm trying to adapt the django_select2.js:

```<code>require(['jquery', 'select2'], function ($, select2) {
   return (function ($) {
        var init = function ($element, options) {
            $element.select2(options);
        };

        var initHeavy = function ($element, options) {
            var settings = $.extend({
                ajax: {
                    data: function (params) {
                        var result = {
                            term: params.term,
                            page: params.page,
                            field_id: $element.data('field_id')
                        }

                        var dependentFields = $element.data('select2-dependent-fields')
                        if (dependentFields) {
                            dependentFields = dependentFields.trim().split(/\s+/)
                            $.each(dependentFields, function (i, dependentField) {
                                result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
                            })
                        }

                        return result
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.results,
                            pagination: {
                                more: data.more
                            }
                        }
                    }
                }
            }, options);

            $element.select2(settings);
        };

        $.fn.djangoSelect2 = function (options) {
            var settings = $.extend({}, options);
            $.each(this, function (i, element) {
                var $element = $(element);
                if ($element.hasClass('django-select2-heavy')) {
                    initHeavy($element, settings);
                } else {
                    init($element, settings);
                }
            });
            return this;
        };

        $(function () {
            $('.django-select2').djangoSelect2();
        });
    }($));
});
</code>```

I'm having a Mismatched anonymous define() when running my page in the browser...

I'me realy not a JS expert, I'm coding by trial and error... Could anyone help me with this ?

Thanks !

答:
OK, I have an auto-response...

I've inherited the mixin:

```<code>class _Select2Mixin(Select2Mixin):
    def _get_media(self):
        """
        Construct Media as a dynamic property.

        .. Note:: For more information visit
            https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
        """
        return forms.Media(js=('django_select2/django_select2.js', ),
                           css={'screen': (settings.SELECT2_CSS,)})

    media = property(_get_media)

class _Select2MultipleWidget(_Select2Mixin, forms.SelectMultiple):
    pass
</code>```

Then I can use the widget:

```<code>    class DocumentationSearchForm(forms.Form):
        ...
        document_domains = forms.ModelMultipleChoiceField(required=False,
                                                      label=_('Document domains'),
                                                      queryset=NotImplemented,
                                                      widget=_Select2MultipleWidget)
</code>```

I've set my config.js file for path:

```<code>requirejs.config({
    paths: {
        jquery: 'jquery/dist/jquery',
        select2: "select2/dist/js"
    },
    shim: {
        "select2/select2": {
            deps: ["jquery"],
            exports: "$.fn.select2"
        }
    }
});
</code>```

Then I've overridden the django_select2.js file, to wrap the content in a require satement:

```<code>require(['jquery', 'select2/select2'], function ($) {
   (function ($) {
        var init = function ($element, options) {
            $element.select2(options);
        };

        var initHeavy = function ($element, options) {
            var settings = $.extend({
                ajax: {
                    data: function (params) {
                        var result = {
                            term: params.term,
                            page: params.page,
                            field_id: $element.data('field_id')
                        }

                        var dependentFields = $element.data('select2-dependent-fields')
                        if (dependentFields) {
                            dependentFields = dependentFields.trim().split(/\s+/)
                            $.each(dependentFields, function (i, dependentField) {
                                result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
                            })
                        }

                        return result
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.results,
                            pagination: {
                                more: data.more
                            }
                        }
                    }
                }
            }, options);

            $element.select2(settings);
        };

        $.fn.djangoSelect2 = function (options) {
            var settings = $.extend({}, options);
            $.each(this, function (i, element) {
                var $element = $(element);
                if ($element.hasClass('django-select2-heavy')) {
                    initHeavy($element, settings);
                } else {
                    init($element, settings);
                }
            });
            return this;
        };

        $(function () {
            $('.django-select2').djangoSelect2();
        });
    }($));
});
</code>```

That's all, folks !

Title: requirejs + django_select2

Body:
I'm building a wagtail / django app using requirejs as js assets combiner, for the site front end.

I'm using it because I've ever been in a kind of JS dependencies hell, where nothing works because of multiple versions of same libs loaded, from different django apps... (I don't even know if it is a good solution)

I've to tell that I'm not a JS expert, and I've none arround me :(
I'm using the good old templates to render the pages, not using angular, react, riot nor vue : I'm a pretty old school dev :)

I've already adapted some scripts to use require, but I'm stuck for now...

I've installed the django_select2 application, and I'm trying to adapt the django_select2.js asset.

I've loaded select2 through bower, and I've updaetd my config.js:

"shim": {
    select2: {
            deps: ["jquery"],
            exports: "$.fn.select2"
    }
},
paths: {
    ...
    select2: "select2/dist/js/select2"
}

Then I'm trying to adapt the django_select2.js:

require(['jquery', 'select2'], function ($, select2) {
   return (function ($) {
        var init = function ($element, options) {
            $element.select2(options);
        };

        var initHeavy = function ($element, options) {
            var settings = $.extend({
                ajax: {
                    data: function (params) {
                        var result = {
                            term: params.term,
                            page: params.page,
                            field_id: $element.data('field_id')
                        }

                        var dependentFields = $element.data('select2-dependent-fields')
                        if (dependentFields) {
                            dependentFields = dependentFields.trim().split(/\s+/)
                            $.each(dependentFields, function (i, dependentField) {
                                result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
                            })
                        }

                        return result
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.results,
                            pagination: {
                                more: data.more
                            }
                        }
                    }
                }
            }, options);

            $element.select2(settings);
        };

        $.fn.djangoSelect2 = function (options) {
            var settings = $.extend({}, options);
            $.each(this, function (i, element) {
                var $element = $(element);
                if ($element.hasClass('django-select2-heavy')) {
                    initHeavy($element, settings);
                } else {
                    init($element, settings);
                }
            });
            return this;
        };

        $(function () {
            $('.django-select2').djangoSelect2();
        });
    }($));
});

I'm having a Mismatched anonymous define() when running my page in the browser...

I'me realy not a JS expert, I'm coding by trial and error... Could anyone help me with this ?

Thanks !

Body:
OK, I have an auto-response...

I've inherited the mixin:

class _Select2Mixin(Select2Mixin):
    def _get_media(self):
        """
        Construct Media as a dynamic property.

        .. Note:: For more information visit
            https://docs.djangoproject.com/en/1.8/topics/forms/media/#media-as-a-dynamic-property
        """
        return forms.Media(js=('django_select2/django_select2.js', ),
                           css={'screen': (settings.SELECT2_CSS,)})

    media = property(_get_media)

class _Select2MultipleWidget(_Select2Mixin, forms.SelectMultiple):
    pass

Then I can use the widget:

    class DocumentationSearchForm(forms.Form):
        ...
        document_domains = forms.ModelMultipleChoiceField(required=False,
                                                      label=_('Document domains'),
                                                      queryset=NotImplemented,
                                                      widget=_Select2MultipleWidget)

I've set my config.js file for path:

requirejs.config({
    paths: {
        jquery: 'jquery/dist/jquery',
        select2: "select2/dist/js"
    },
    shim: {
        "select2/select2": {
            deps: ["jquery"],
            exports: "$.fn.select2"
        }
    }
});

Then I've overridden the django_select2.js file, to wrap the content in a require satement:

require(['jquery', 'select2/select2'], function ($) {
   (function ($) {
        var init = function ($element, options) {
            $element.select2(options);
        };

        var initHeavy = function ($element, options) {
            var settings = $.extend({
                ajax: {
                    data: function (params) {
                        var result = {
                            term: params.term,
                            page: params.page,
                            field_id: $element.data('field_id')
                        }

                        var dependentFields = $element.data('select2-dependent-fields')
                        if (dependentFields) {
                            dependentFields = dependentFields.trim().split(/\s+/)
                            $.each(dependentFields, function (i, dependentField) {
                                result[dependentField] = $('[name=' + dependentField + ']', $element.closest('form')).val()
                            })
                        }

                        return result
                    },
                    processResults: function (data, page) {
                        return {
                            results: data.results,
                            pagination: {
                                more: data.more
                            }
                        }
                    }
                }
            }, options);

            $element.select2(settings);
        };

        $.fn.djangoSelect2 = function (options) {
            var settings = $.extend({}, options);
            $.each(this, function (i, element) {
                var $element = $(element);
                if ($element.hasClass('django-select2-heavy')) {
                    initHeavy($element, settings);
                } else {
                    init($element, settings);
                }
            });
            return this;
        };

        $(function () {
            $('.django-select2').djangoSelect2();
        });
    }($));
});

That's all, folks !


问:
Sliding window on list of lists in Python
I'm trying to use numpy/pandas to constuct a sliding window style comparator. I've got list of lists each of which is a different length. I want to compare each list to to another list as depicted below:

```<code>lists = [[10,15,5],[5,10],[5]]

window_diff(l[1],l[0]) = 25
</code>```

The window diff for lists[0] and lists[1] would give 25 using the following window sliding technique shown in the image below. Because lists[1] is the shorter path we shift it once to the right, resulting in 2 windows of comparison. If you sum the last row in the image below we get the total difference between the two lists using the two windows of comparison; in this case a total of 25. To note we are taking the absolute difference.

The function should aggregate the total window_diff between each list and the other lists, so in this case

```<code>tot = total_diffs(lists)
tot>>[40, 30, 20]

# where tot[0] represents the sum of lists[0] window_diff with all other lists.
</code>```

I wanted to know if there was a quick route to doing this in pandas or numpy. Currently I am using a very long winded process of for looping through each of the lists and then comparing bitwise by shifting the shorter list in accordance to the longer list.

My approach works fine for short lists, but my dataset is 10,000 lists long and some of these lists contain 60 or so datapoints, so speed is a criteria here. I was wondering if numpy, pandas had some advice on this? Thanks

Sample problem data

```<code>from random import randint
lists = [[random.randint(0,1000) for r in range(random.randint(0,60))] for x in range(100000)]
</code>```

答:
Steps :

Among each pair of lists from the input list of lists create sliding windows for the bigger array  and then get the absolute difference against the smaller one in that pair. We can use NumPy strides to get those sliding windows.

Get the total sum and store this summation as a pair-wise differentiation.

Finally sum along each row and col on the 2D array from previous step and their summation is final output.

Thus, the implementation would look something like this -

```<code>import itertools

def strided_app(a, L, S=1 ):  # Window len = L, Stride len/stepsize = S
    a = np.asarray(a)
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))

N = len(lists)
pair_diff_sums = np.zeros((N,N),dtype=type(lists[0][0]))
for i, j in itertools.combinations(range(N), 2):
    A, B = lists[i], lists[j]
    if len(A)>len(B):
        pair_diff_sums[i,j] = np.abs(strided_app(A,L=len(B)) - B).sum()
    else:
        pair_diff_sums[i,j] = np.abs(strided_app(B,L=len(A)) - A).sum()

out = pair_diff_sums.sum(1) + pair_diff_sums.sum(0)
</code>```

For really heavy datasets, here's one method using one more level of looping -

```<code>N = len(lists)
out = np.zeros((N),dtype=type(lists[0][0]))
for k,i in enumerate(lists):
    for j in lists:
        if len(i)>len(j):
            out[k] += np.abs(strided_app(i,L=len(j)) - j).sum()
        else:
            out[k] += np.abs(strided_app(j,L=len(i)) - i).sum()
</code>```

strided_app is inspired from here.

Sample input, output -

```<code>In [77]: lists
Out[77]: [[10, 15, 5], [5, 10], [5]]

In [78]: pair_diff_sums
Out[78]:
array([[ 0, 25, 15],
       [25,  0,  5],
       [15,  5,  0]])

In [79]: out
Out[79]: array([40, 30, 20])
</code>```

Body:
I'm trying to use numpy/pandas to constuct a sliding window style comparator. I've got list of lists each of which is a different length. I want to compare each list to to another list as depicted below:

lists = [[10,15,5],[5,10],[5]]

window_diff(l[1],l[0]) = 25

The window diff for lists[0] and lists[1] would give 25 using the following window sliding technique shown in the image below. Because lists[1] is the shorter path we shift it once to the right, resulting in 2 windows of comparison. If you sum the last row in the image below we get the total difference between the two lists using the two windows of comparison; in this case a total of 25. To note we are taking the absolute difference.

The function should aggregate the total window_diff between each list and the other lists, so in this case

tot = total_diffs(lists)
tot>>[40, 30, 20]

# where tot[0] represents the sum of lists[0] window_diff with all other lists.

I wanted to know if there was a quick route to doing this in pandas or numpy. Currently I am using a very long winded process of for looping through each of the lists and then comparing bitwise by shifting the shorter list in accordance to the longer list.

My approach works fine for short lists, but my dataset is 10,000 lists long and some of these lists contain 60 or so datapoints, so speed is a criteria here. I was wondering if numpy, pandas had some advice on this? Thanks

Sample problem data

from random import randint
lists = [[random.randint(0,1000) for r in range(random.randint(0,60))] for x in range(100000)]

Body:
Steps :

Among each pair of lists from the input list of lists create sliding windows for the bigger array  and then get the absolute difference against the smaller one in that pair. We can use NumPy strides to get those sliding windows.

Get the total sum and store this summation as a pair-wise differentiation.

Finally sum along each row and col on the 2D array from previous step and their summation is final output.

Thus, the implementation would look something like this -

import itertools

def strided_app(a, L, S=1 ):  # Window len = L, Stride len/stepsize = S
    a = np.asarray(a)
    nrows = ((a.size-L)//S)+1
    n = a.strides[0]
    return np.lib.stride_tricks.as_strided(a, shape=(nrows,L), strides=(S*n,n))

N = len(lists)
pair_diff_sums = np.zeros((N,N),dtype=type(lists[0][0]))
for i, j in itertools.combinations(range(N), 2):
    A, B = lists[i], lists[j]
    if len(A)>len(B):
        pair_diff_sums[i,j] = np.abs(strided_app(A,L=len(B)) - B).sum()
    else:
        pair_diff_sums[i,j] = np.abs(strided_app(B,L=len(A)) - A).sum()

out = pair_diff_sums.sum(1) + pair_diff_sums.sum(0)

For really heavy datasets, here's one method using one more level of looping -

N = len(lists)
out = np.zeros((N),dtype=type(lists[0][0]))
for k,i in enumerate(lists):
    for j in lists:
        if len(i)>len(j):
            out[k] += np.abs(strided_app(i,L=len(j)) - j).sum()
        else:
            out[k] += np.abs(strided_app(j,L=len(i)) - i).sum()

strided_app is inspired from here.

Sample input, output -

In [77]: lists
Out[77]: [[10, 15, 5], [5, 10], [5]]

In [78]: pair_diff_sums
Out[78]:
array([[ 0, 25, 15],
       [25,  0,  5],
       [15,  5,  0]])

In [79]: out
Out[79]: array([40, 30, 20])


问:
Deleting objects in memory using Python
I am trying this approach to delete an object in python. I read the documentation of Python stating that garbage collector will automatically delete the object that is not referenced.

```<code>def check():
    class newOb():
        def __init__(self,value):
            self.value = value
            print self.value
            return None

    class ob:
        ins = {}
        def cr(self,someuniqueid,value) :
            newV = newOb(value)
            ob.ins[someuniqueid] = newV ## saving this object refernce to the ob class ins dictionary
            return newV

    #### Accessing Object ###
    someuniqueid  = 12
    c = ob()
    d = c.cr(someuniqueid,123)
    print d.value ## will print 123
    # now deleting the associated object
    del c.ins[someuniqueid]

check()
</code>```

At the last step, I am removing the object reference from the memory
is using above procedure will delete the object from memory

If not then what is wrong with code and how to correct it

答:
I don't know what do you mean by writing:

If not then what is wrong with code and how to correct it

When you use del statement you delete a reference to an object. It will use up memory untill garbage collector is invoked. Remember that this can be a time-consuming process and not necessary if the process has enough memory to continue executing.

Generally speaking Python does not perform C++-like destructor bahaviour.

A quote from "Expert Python Programming":

The approach of such a memory manager is roughly based on a simple
statement: If a given object is not referenced anymore, it is removed.
In other words, all local references in a function are removed after
the interpreter:

• Leaves the function

• Makes sure the object is not being used anymore.

Under normal conditions, the collector will do a
nice job. But a del call can be used to help the garbage collector by
manually removing the references to an object manually.

So you don't manage memory by hand. You can help garbage collector, but it's better to leave memory managment behind the scenes.

Title: Deleting objects in memory using Python

Body:
I am trying this approach to delete an object in python. I read the documentation of Python stating that garbage collector will automatically delete the object that is not referenced.

def check():
    class newOb():
        def __init__(self,value):
            self.value = value
            print self.value
            return None

    class ob:
        ins = {}
        def cr(self,someuniqueid,value) :
            newV = newOb(value)
            ob.ins[someuniqueid] = newV ## saving this object refernce to the ob class ins dictionary
            return newV

    #### Accessing Object ###
    someuniqueid  = 12
    c = ob()
    d = c.cr(someuniqueid,123)
    print d.value ## will print 123
    # now deleting the associated object
    del c.ins[someuniqueid]

check()

At the last step, I am removing the object reference from the memory
is using above procedure will delete the object from memory

If not then what is wrong with code and how to correct it


答:
If I understood correctly, you should "safely substring" (Substring throws an exception if you choose a length greater than the string length) your strings to the desidered lenght.

```<code>public static string SafeSubstring(this string text, int start, int length)
{
    return text.Length <= start ? string.Empty
        : text.Length - start <= length ? text.Substring(start)
        : text.Substring(start, length);
}
</code>```

Then, for example:

```<code>writer.WriteLine("{0,-3}{1,-5}{2,-30}",
    data1.SafeSubstring(0, 3),
    data2.SafeSubstring(0, 3),
    data3.SafeSubstring(0, 3));
</code>```

Title: C# writeline cap

Body:
If I understood correctly, you should "safely substring" (Substring throws an exception if you choose a length greater than the string length) your strings to the desidered lenght.

public static string SafeSubstring(this string text, int start, int length)
{
    return text.Length <= start ? string.Empty
        : text.Length - start <= length ? text.Substring(start)
        : text.Substring(start, length);
}

Then, for example:

writer.WriteLine("{0,-3}{1,-5}{2,-30}",
    data1.SafeSubstring(0, 3),
    data2.SafeSubstring(0, 3),
    data3.SafeSubstring(0, 3));


问:
How to access session variable in asp.net mvc using a javascript variable as a key?
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

```<code>success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }
</code>```

Any help would be appreciated.

Thanks.

答:
You cannot use a client side variable in server side code. You must post this client value to server (this is how Client-Server Architecture works basically).

May be you can get sessionId from a controller with using ajax, somethig like following;

jquery

```<code>$.get("SomeController/GetSessionId?userId=" + user.Id, function(result)
{
    var sessionUserId = result.SessionId;
});
</code>```

SomeController.cs

```<code>public ActionResult GetSessionId(string userId)
{
    return Json(new JsonResult { SessionId = Session[userId] });
}
</code>```

Above code is just example how to achive what you want. There may be syntax errors.

OR

You can add your existing ajax result a field that named SessionUserId and define it's value at server side.

Body:
I want to access a Session variable in ASP.NET MVC, but using a JavaScript variable as a key.

Here is an example in the success bloc of an ajax call :

success: function (data) {
    $.each(data, function (idx, user) {

        var sessionUserId = '@Session[" ' + user.Id + ' "]'; //this doesn't seem to work

    }

Any help would be appreciated.

Thanks.

Body:
You cannot use a client side variable in server side code. You must post this client value to server (this is how Client-Server Architecture works basically).

May be you can get sessionId from a controller with using ajax, somethig like following;

jquery

$.get("SomeController/GetSessionId?userId=" + user.Id, function(result)
{
    var sessionUserId = result.SessionId;
});

SomeController.cs

public ActionResult GetSessionId(string userId)
{
    return Json(new JsonResult { SessionId = Session[userId] });
}

Above code is just example how to achive what you want. There may be syntax errors.

OR

You can add your existing ajax result a field that named SessionUserId and define it's value at server side.


答: array_search() function returns the key for needle if it is found in the array, FALSE otherwise. So when you are using gettype() on the return value, then it will return the type of FALSE i.e. BOOLEAN for unsuccessful search, otherwise INT index value.

Title: why it returns empty value but of boolean type when no match is found