问:
livedata list - adapter doesn't update with DiffUtil method
I'm new to Android and I'm trying to implement a Barcode reader scenario with the new architecture components.

Every time a barcode is read, I want to update a list in the ViewModel adding a new element if the barcode is not present on the list or increasing the quantity otherwise.

The following solution is working, but it's not satisfying me about calling "notifyDataSetChanged" on the adapter in order to update UI. That's because ViewModel list and adapter internal list contain references to same objects so DiffUtil won't catch any changes.

Is there a better way to update UI? Beside adapter, are there any improvement I should consider to handle architecture components?

ViewModel

```<code>public class ScannerViewModel extends ViewModel {

    private MutableLiveData<List<ProductScan>> scanListLD;

    public ScannerViewModel() {
        scanListLD = new MutableLiveData<>();
        scanListLD.setValue(new ArrayList<ProductScan>());
    }

    public LiveData<List<ProductScan>> getScanList() {
        return scanListLD;
    }

    public void addBarcode(String barcode) {
        List<ProductScan> list = scanListLD.getValue();
        ProductScan scan = null;
        for (ProductScan item : list) {
            if (item.barcode.equals(barcode)) {
                scan = item;
                break;
            }
        }
        if (scan == null) {
            scan = new ProductScan();
            scan.barcode = barcode;
            scan.qt = 0;
            list.add(scan);
        }
        scan.qt += 1;

        scanListLD.postValue(list);
    }
}
</code>```

Adapter

```<code>public class ScannerAdapter extends RecyclerView.Adapter<ScannerAdapter.ViewHolder> {

    private List<ProductScan> scans;

    public interface OnItemClickListener {
        void onItemClick();
    }

    public ScannerAdapter(List<ProductScan> scans) {
        this.scans = scans;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_scan, parent, false);
        ScannerAdapter.ViewHolder viewHolder = new ScannerAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bindData(scans.get(position), position);
    }

    @Override
    public int getItemCount() {
        return scans != null ? scans.size() : 0;
    }

    //Not used since scans and newScans contain same objects
    public void setScans(final List<ProductScan> newScans) {
        if (scans == null) {
            scans = new ArrayList<ProductScan>();
            scans.addAll(newScans);
            notifyItemRangeInserted(0, newScans.size());
        } else {
            DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
                @Override
                public int getOldListSize() {
                    return scans != null ? scans.size() : 0;
                }

                @Override
                public int getNewListSize() {
                    return newScans != null ? newScans.size() : 0;
                }

                @Override
                public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
                    ProductScan oldScan = scans.get(oldItemPosition);
                    ProductScan newScan = newScans.get(newItemPosition);
                    return Utils.equals(oldScan.barcode,newScan.barcode);
                }

                @Override
                public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
                    ProductScan oldScan = scans.get(oldItemPosition);
                    ProductScan newScan = newScans.get(newItemPosition);
                    return Utils.equals(newScan.barcode, oldScan.barcode)
                            && Utils.equals(newScan.productId, oldScan.productId)
                            && Utils.equals(newScan.productDescription, oldScan.productDescription)
                            && Utils.equals(newScan.qt, oldScan.qt);
                }
            });
            scans.clear();
            scans.addAll(newScans);
            result.dispatchUpdatesTo(this);
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TemplateScanBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public void bindData(ProductScan scan, int position) {
            binding.setScan(scan);
            binding.setBtnIncreaseQtListener(() -> {
                scan.qt += 1;
                notifyItemChanged(position);
            });
            binding.setBtnDecreaseQtListener(() -> {
                scan.qt = Math.max(1, scan.qt - 1);
                notifyItemChanged(position);
            });
            binding.edtQt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                    if (i == EditorInfo.IME_ACTION_DONE) {
                        binding.edtQt.clearFocus();
                    }
                    return false;
                }
            });
            binding.edtQt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    if (scan.qt == null || scan.qt < 1) {
                        scan.qt = 1;
                        notifyItemChanged(position);
                    }
                    InputMethodManager imm = (InputMethodManager) binding.getRoot().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            });
        }
    }
}
</code>```

Activity

```<code>public class ScannerActivity extends ScannerBaseActivity {

    @Inject
    ViewModelFactory viewModelFactory;
    private ScannerViewModel viewModel;

    private ActivityScannerBinding binding;
    private ScannerAdapter adapter;

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

        ((MyApplication) getApplication()).getComponent().inject(this);
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(ScannerViewModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_scanner);

        adapter = new ScannerAdapter(viewModel.getScanList().getValue());
        binding.recvScans.setLayoutManager(new LinearLayoutManager(this));
        binding.recvScans.setAdapter(adapter);
        viewModel.getScanList().observe(this, (list) -> {
            adapter.notifyDataSetChanged();
        });

        binding.btnScan.setOnClickListener((v) -> {
             //calls viewModel.addBarcode(String barcode)
              readBarcode(readBarcodeCallback);
        });

    }
}
</code>```

答:
You can use PagedListAdapterHelper in your existing adapter as shown below

```<code>class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
     private final PagedListAdapterHelper<User> mHelper;
     public UserAdapter(PagedListAdapterHelper.Builder<User> builder) {
         mHelper = new PagedListAdapterHelper(this, DIFF_CALLBACK);
     }
     @Override
     public int getItemCount() {
         return mHelper.getItemCount();
     }
     public void setList(PagedList<User> pagedList) {
         mHelper.setList(pagedList);
     }
     @Override
     public void onBindViewHolder(UserViewHolder holder, int position) {
         User user = mHelper.getItem(position);
         if (user != null) {
             holder.bindTo(user);
         } else {
             // Null defines a placeholder item - PagedListAdapterHelper will automatically
             // invalidate this row when the actual object is loaded from the database
             holder.clear();
         }
     }
     public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
          @Override
          public boolean areItemsTheSame(
                  @NonNull User oldUser, @NonNull User newUser) {
              // User properties may have changed if reloaded from the DB, but ID is fixed
              return oldUser.getId() == newUser.getId();
          }
          @Override
          public boolean areContentsTheSame(
                  @NonNull User oldUser, @NonNull User newUser) {
              // NOTE: if you use equals, your object must properly override Object#equals()
              // Incorrectly returning false here will result in too many animations.
              return oldUser.equals(newUser);
          }
      }
</code>```

OR

User PageListAdapter

```<code>class UserAdapter extends PagedListAdapter<User, UserViewHolder> {
     public UserAdapter() {
         super(DIFF_CALLBACK);
     }
     @Override
     public void onBindViewHolder(UserViewHolder holder, int position) {
         User user = getItem(position);
         if (user != null) {
             holder.bindTo(user);
         } else {
             // Null defines a placeholder item - PagedListAdapter will automatically invalidate
             // this row when the actual object is loaded from the database
             holder.clear();
         }
     }
     public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
         @Override
         public boolean areItemsTheSame(
                 @NonNull User oldUser, @NonNull User newUser) {
             // User properties may have changed if reloaded from the DB, but ID is fixed
             return oldUser.getId() == newUser.getId();
         }
         @Override
         public boolean areContentsTheSame(
                 @NonNull User oldUser, @NonNull User newUser) {
             // NOTE: if you use equals, your object must properly override Object#equals()
             // Incorrectly returning false here will result in too many animations.
             return oldUser.equals(newUser);
         }
     }
</code>```

Body:
I'm new to Android and I'm trying to implement a Barcode reader scenario with the new architecture components.

Every time a barcode is read, I want to update a list in the ViewModel adding a new element if the barcode is not present on the list or increasing the quantity otherwise.

The following solution is working, but it's not satisfying me about calling "notifyDataSetChanged" on the adapter in order to update UI. That's because ViewModel list and adapter internal list contain references to same objects so DiffUtil won't catch any changes.

Is there a better way to update UI? Beside adapter, are there any improvement I should consider to handle architecture components?

ViewModel

public class ScannerViewModel extends ViewModel {

    private MutableLiveData<List<ProductScan>> scanListLD;

    public ScannerViewModel() {
        scanListLD = new MutableLiveData<>();
        scanListLD.setValue(new ArrayList<ProductScan>());
    }

    public LiveData<List<ProductScan>> getScanList() {
        return scanListLD;
    }

    public void addBarcode(String barcode) {
        List<ProductScan> list = scanListLD.getValue();
        ProductScan scan = null;
        for (ProductScan item : list) {
            if (item.barcode.equals(barcode)) {
                scan = item;
                break;
            }
        }
        if (scan == null) {
            scan = new ProductScan();
            scan.barcode = barcode;
            scan.qt = 0;
            list.add(scan);
        }
        scan.qt += 1;

        scanListLD.postValue(list);
    }
}

Adapter

public class ScannerAdapter extends RecyclerView.Adapter<ScannerAdapter.ViewHolder> {

    private List<ProductScan> scans;

    public interface OnItemClickListener {
        void onItemClick();
    }

    public ScannerAdapter(List<ProductScan> scans) {
        this.scans = scans;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_scan, parent, false);
        ScannerAdapter.ViewHolder viewHolder = new ScannerAdapter.ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.bindData(scans.get(position), position);
    }

    @Override
    public int getItemCount() {
        return scans != null ? scans.size() : 0;
    }

    //Not used since scans and newScans contain same objects
    public void setScans(final List<ProductScan> newScans) {
        if (scans == null) {
            scans = new ArrayList<ProductScan>();
            scans.addAll(newScans);
            notifyItemRangeInserted(0, newScans.size());
        } else {
            DiffUtil.DiffResult result = DiffUtil.calculateDiff(new DiffUtil.Callback() {
                @Override
                public int getOldListSize() {
                    return scans != null ? scans.size() : 0;
                }

                @Override
                public int getNewListSize() {
                    return newScans != null ? newScans.size() : 0;
                }

                @Override
                public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
                    ProductScan oldScan = scans.get(oldItemPosition);
                    ProductScan newScan = newScans.get(newItemPosition);
                    return Utils.equals(oldScan.barcode,newScan.barcode);
                }

                @Override
                public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
                    ProductScan oldScan = scans.get(oldItemPosition);
                    ProductScan newScan = newScans.get(newItemPosition);
                    return Utils.equals(newScan.barcode, oldScan.barcode)
                            && Utils.equals(newScan.productId, oldScan.productId)
                            && Utils.equals(newScan.productDescription, oldScan.productDescription)
                            && Utils.equals(newScan.qt, oldScan.qt);
                }
            });
            scans.clear();
            scans.addAll(newScans);
            result.dispatchUpdatesTo(this);
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private TemplateScanBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
            binding = DataBindingUtil.bind(itemView);
        }

        public void bindData(ProductScan scan, int position) {
            binding.setScan(scan);
            binding.setBtnIncreaseQtListener(() -> {
                scan.qt += 1;
                notifyItemChanged(position);
            });
            binding.setBtnDecreaseQtListener(() -> {
                scan.qt = Math.max(1, scan.qt - 1);
                notifyItemChanged(position);
            });
            binding.edtQt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                    if (i == EditorInfo.IME_ACTION_DONE) {
                        binding.edtQt.clearFocus();
                    }
                    return false;
                }
            });
            binding.edtQt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    if (scan.qt == null || scan.qt < 1) {
                        scan.qt = 1;
                        notifyItemChanged(position);
                    }
                    InputMethodManager imm = (InputMethodManager) binding.getRoot().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            });
        }
    }
}

Activity

public class ScannerActivity extends ScannerBaseActivity {

    @Inject
    ViewModelFactory viewModelFactory;
    private ScannerViewModel viewModel;

    private ActivityScannerBinding binding;
    private ScannerAdapter adapter;

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

        ((MyApplication) getApplication()).getComponent().inject(this);
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(ScannerViewModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_scanner);

        adapter = new ScannerAdapter(viewModel.getScanList().getValue());
        binding.recvScans.setLayoutManager(new LinearLayoutManager(this));
        binding.recvScans.setAdapter(adapter);
        viewModel.getScanList().observe(this, (list) -> {
            adapter.notifyDataSetChanged();
        });

        binding.btnScan.setOnClickListener((v) -> {
             //calls viewModel.addBarcode(String barcode)
              readBarcode(readBarcodeCallback);
        });

    }
}

Body:
You can use PagedListAdapterHelper in your existing adapter as shown below

class UserAdapter extends RecyclerView.Adapter<UserViewHolder> {
     private final PagedListAdapterHelper<User> mHelper;
     public UserAdapter(PagedListAdapterHelper.Builder<User> builder) {
         mHelper = new PagedListAdapterHelper(this, DIFF_CALLBACK);
     }
     @Override
     public int getItemCount() {
         return mHelper.getItemCount();
     }
     public void setList(PagedList<User> pagedList) {
         mHelper.setList(pagedList);
     }
     @Override
     public void onBindViewHolder(UserViewHolder holder, int position) {
         User user = mHelper.getItem(position);
         if (user != null) {
             holder.bindTo(user);
         } else {
             // Null defines a placeholder item - PagedListAdapterHelper will automatically
             // invalidate this row when the actual object is loaded from the database
             holder.clear();
         }
     }
     public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
          @Override
          public boolean areItemsTheSame(
                  @NonNull User oldUser, @NonNull User newUser) {
              // User properties may have changed if reloaded from the DB, but ID is fixed
              return oldUser.getId() == newUser.getId();
          }
          @Override
          public boolean areContentsTheSame(
                  @NonNull User oldUser, @NonNull User newUser) {
              // NOTE: if you use equals, your object must properly override Object#equals()
              // Incorrectly returning false here will result in too many animations.
              return oldUser.equals(newUser);
          }
      }

OR

User PageListAdapter

class UserAdapter extends PagedListAdapter<User, UserViewHolder> {
     public UserAdapter() {
         super(DIFF_CALLBACK);
     }
     @Override
     public void onBindViewHolder(UserViewHolder holder, int position) {
         User user = getItem(position);
         if (user != null) {
             holder.bindTo(user);
         } else {
             // Null defines a placeholder item - PagedListAdapter will automatically invalidate
             // this row when the actual object is loaded from the database
             holder.clear();
         }
     }
     public static final DiffCallback<User> DIFF_CALLBACK = new DiffCallback<User>() {
         @Override
         public boolean areItemsTheSame(
                 @NonNull User oldUser, @NonNull User newUser) {
             // User properties may have changed if reloaded from the DB, but ID is fixed
             return oldUser.getId() == newUser.getId();
         }
         @Override
         public boolean areContentsTheSame(
                 @NonNull User oldUser, @NonNull User newUser) {
             // NOTE: if you use equals, your object must properly override Object#equals()
             // Incorrectly returning false here will result in too many animations.
             return oldUser.equals(newUser);
         }
     }


来源: stackexchange

问:
BackgroundWorker progressBar - Problem implementing ReportProgress when loop occurs in another class
Hi
I am trying to integrate a background worker with a progress bar but cannot get it right.

I am processing some files and all the processing is done in an external class.

My difficulty is that the looping is inside this class,where usually  I do the talking to the backgroundworker.

The good thing is that when processing a file,an event is fired whenever each file has completed processing.

This is my code any suggestions how could this be achieved

```<code>    BackgroundWorker _bw = new BackgroundWorker

    private void RunLongProcess()
    {
        _bw.WorkerReportsProgress = true;
        _bw.WorkerSupportsCancellation = true;
        _bw.DoWork += DoWork;
        _bw.ProgressChanged += ProgressChanged;
        _bw.RunWorkerCompleted += RunWorkerCompleted;

        _bw.RunWorkerAsync();//start the process

        if (_bw.IsBusy)
           _bw.CancelAsync();
    }

     static void DoWork (object sender, DoWorkEventArgs e)
      {

        var files=GetFiles();
        int fileCount=files.Count;

        //usually I do a loop here but all the processing is done inside this class so

        var fileProcessor=new FileProcesser();
        fileProcessor.ProcessFiles(files);

      }
    private void OnFileProcessCompleted(object sender, FileEventArgs e)
    {
        //Event Fired when a file has been processed
        //How do I update progressBar.Problem cross threading here.

                        //What do I do here?????
        _bw.ReportProgress(e.FileProcessedCount, e);
    }

    ProgressChanged (object sender, ProgressChangedEventArgs e)
    {
          // Update the UI
        labelProgress.Text = e.UserState;
        progressBar.Value = e.ProgressPercentage;
    }

    private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
           // Console.WriteLine("You canceled!");
        else if (e.Error != null)
            //Console.WriteLine("Worker exception: " + e.Error.ToString());
        else
           // Console.WriteLine("Complete: " + e.Result);
    }
</code>```

答: In that case, one solution is to make a derived class from BackgroundWorker, make it subscribe to the event, and have it send the progress event to the UI thread in the event handler.

ContentLicense: CC BY-SA 2.5

Body:
Hi
I am trying to integrate a background worker with a progress bar but cannot get it right.

I am processing some files and all the processing is done in an external class.

My difficulty is that the looping is inside this class,where usually  I do the talking to the backgroundworker.

The good thing is that when processing a file,an event is fired whenever each file has completed processing.

This is my code any suggestions how could this be achieved

    BackgroundWorker _bw = new BackgroundWorker

    private void RunLongProcess()
    {
        _bw.WorkerReportsProgress = true;
        _bw.WorkerSupportsCancellation = true;
        _bw.DoWork += DoWork;
        _bw.ProgressChanged += ProgressChanged;
        _bw.RunWorkerCompleted += RunWorkerCompleted;

        _bw.RunWorkerAsync();//start the process

        if (_bw.IsBusy)
           _bw.CancelAsync();
    }

     static void DoWork (object sender, DoWorkEventArgs e)
      {

        var files=GetFiles();
        int fileCount=files.Count;

        //usually I do a loop here but all the processing is done inside this class so

        var fileProcessor=new FileProcesser();
        fileProcessor.ProcessFiles(files);

      }
    private void OnFileProcessCompleted(object sender, FileEventArgs e)
    {
        //Event Fired when a file has been processed
        //How do I update progressBar.Problem cross threading here.

                        //What do I do here?????
        _bw.ReportProgress(e.FileProcessedCount, e);
    }

    ProgressChanged (object sender, ProgressChangedEventArgs e)
    {
          // Update the UI
        labelProgress.Text = e.UserState;
        progressBar.Value = e.ProgressPercentage;
    }

    private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
           // Console.WriteLine("You canceled!");
        else if (e.Error != null)
            //Console.WriteLine("Worker exception: " + e.Error.ToString());
        else
           // Console.WriteLine("Complete: " + e.Result);
    }


问:
Ajax doesn't post data
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

```<code>$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
</code>```

should have been that:

```<code>$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
</code>```

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

```<code>$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('<p>Success</p>');
                }
                else {
                    $('#errors'+bUID).append('<p>' + js_errors + '</p>');
                    $('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('<li>' + v + '</li>');
                        }
                    });
                }
            }
        }
    });
}
</code>```

here's the action in view.php:

```<code><?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?><br />
    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.
</code>```

and here's the controller.php:

```<code>public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}
</code>```

it gets all data and shows it in alert but then trows the following error in the console:

```<code>Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)
</code>```

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

答:
Have you tried adding return false; to prevent your form from submitting to its desired action?

```<code>$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    //e.preventDefault();
    //e.stopPropagation();
    submitForm(bUID);
    alert(bUID);
    return false;
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Ajax doesn't post data

Body:
[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

$('#errors'+bUID).append('

');

should have been that:

$('#errors'+bUID).append('

');

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))

Here's the js:

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);

    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('
Success
');
                }
                else {
                    $('#errors'+bUID).append('
' + js_errors + '
');
                    $('#errors'+bUID).append('

');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('
' + v + '
');
                        }
                    });
                }
            }
        }
    });
}

here's the action in view.php:

<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>"
    class="contact-form"
    enctype="multipart/form-data"
    action="<?php echo $formAction?>"
    method="post"
    accept-charset="utf-8">

    <?php echo $bUID; ?>

    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.

and here's the controller.php:

public function action_submit($token = false, $bID = false)
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}

it gets all data and shows it in alert but then trows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

Body:
Have you tried adding return false; to prevent your form from submitting to its desired action?

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    //e.preventDefault();
    //e.stopPropagation();
    submitForm(bUID);
    alert(bUID);
    return false;
});


问:
protoc object_detection/protos/*.proto: No such file or directory
I am following the example found here.
But whenever I enter the command "C:/Program Files/protoc/bin/protoc" object_detection/protos/.proto --python_out=.
I get an error that says object_detection/protos/.proto: No such file or directory.
I can't create a directory called *.proto. So I'm missing some fundamental information on how to do this. Since I can't find anyone else complaining about this issue it must be pretty simple.
I am using a windows OS.

答:
sometimes windows Cmd doesn't accept wildcard '*'. that's why it shows error. you can use loop to solve this problam.
to create Loop in Cmd checkout this link. https://ss64.com/nt/for.html
ref:
protoc cannot find files in windows 7</p>


问:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Servlet
I am writing servlet to connect with mysql database using mysqlconnector java but it is giving error

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I have tried same with core java using the same driver it is connecting to mysql and query is also running but using servlet it is not working.

my code is for servlet is:

```<code>import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String n = request.getParameter("userName");
        String p = request.getParameter("password");
        String e = request.getParameter("email");
        String c = request.getParameter("course");

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/phpmyadmin/saiiff","root", "");
            PreparedStatement ps =  conn
                    .prepareStatement("insert into eemeze values(?,?,?,?)");

            ps.setString(1, n);
            ps.setString(2, p);
            ps.setString(3, e);
            ps.setString(4, c);

            int i = ps.executeUpdate();
            if (i > 0)
                out.print("You are successfully registered...");

        } catch (Exception e2) {
            System.out.println(e2);
        }

        out.close();
    }
}
</code>```

答:
Download the mysql jar from http://www.java2s.com/Code/JarDownload/com.mysql/com.mysql.jdbc_5.1.5.jar.zip

And Build on classpath

Body:
I am writing servlet to connect with mysql database using mysqlconnector java but it is giving error

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I have tried same with core java using the same driver it is connecting to mysql and query is also running but using servlet it is not working.

my code is for servlet is:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String n = request.getParameter("userName");
        String p = request.getParameter("password");
        String e = request.getParameter("email");
        String c = request.getParameter("course");

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/phpmyadmin/saiiff","root", "");
            PreparedStatement ps =  conn
                    .prepareStatement("insert into eemeze values(?,?,?,?)");

            ps.setString(1, n);
            ps.setString(2, p);
            ps.setString(3, e);
            ps.setString(4, c);

            int i = ps.executeUpdate();
            if (i > 0)
                out.print("You are successfully registered...");

        } catch (Exception e2) {
            System.out.println(e2);
        }

        out.close();
    }
}


问:
Eclipse importing files
I'm a student and I got java files which I should work with.
I tried to import throw importing "File system".
My problem is with this line: "package bgu.spl.a2;".
How can I fix it without changing the files structure?

答:
You created a standard eclipse java project. In this project, java packages are stored in the folder src.

But the code is provided as a maven project following the Maven Standard Directory Layout where the java sources are in src/main/java.

Most likely there was a file called pom.xml along with the source file.

You have two options:

recreate the project as Maven project

remove the project from the workspace.

open the import dialog

select maven -> existing maven project

navigate to the folder containing the pom.xml

or

change the "source folders"

in the project explorer:

right click on src

select remove from build path

navigate to src/main/java

right click on java

select add to build path

Title: Eclipse importing files


问:
Fast forward merge failing in git
I will preface this by saying that I am pretty new to git. However, this seems like a pretty straightforward scenario, and I can't see where the problem is coming from. Here is the scenario:

I am on the master branch with some uncommitted changes that I don't want. I need to make a separate simple change to be packaged into a patch.  So I do this:

I find the hash # for the last commit to the master branch which is  ffdd99afc89211e9ddc3efa3415b0adaf0076b4b.

So from the root of my repository I do:

```<code>git branch my_patch ffdd99afc89211e9ddc3efa3415b0adaf0076b4b
git checkout -f my_patch
</code>```

Now I edit three files and add a fourth after which I do:

```<code>git add [path to the added file]
git status
</code>```

this lists the three updated and one added file

```<code>git commit -a
git status
</code>```

no changes found

```<code>git format-patch master --stdout > my_patch.patch
</code>```

All is good to this point. Now I want to merge this branch back into master.

```<code>git checkout master
git status
</code>```

No changes found

```<code>git merge my_patch
</code>```

The output from which is:

```<code>Updating ffdd99a..e2754ca
error: Your local changes to 'Blah.cs' would be overwritten by merge.
Aborting. Please, commit your changes
or stash them before you can merge.
</code>```

And now if I do git status I get a boat load of changes listed.  Does this make any sense to anyone?

答:
if you don't want the changes when you start, do a git reset --hard. And if there are untracked files there that you don't want do a git clean -df as well.

As for your error message at the end, you may have an issue with casing in the path. Is this on Windows w/ msysgit?

If you are on windows, ensure you have autocrlf set to false.

Title: Fast forward merge failing in git

Body:
I will preface this by saying that I am pretty new to git. However, this seems like a pretty straightforward scenario, and I can't see where the problem is coming from. Here is the scenario:

I am on the master branch with some uncommitted changes that I don't want. I need to make a separate simple change to be packaged into a patch.  So I do this:

I find the hash # for the last commit to the master branch which is  ffdd99afc89211e9ddc3efa3415b0adaf0076b4b.

So from the root of my repository I do:

git branch my_patch ffdd99afc89211e9ddc3efa3415b0adaf0076b4b
git checkout -f my_patch

Now I edit three files and add a fourth after which I do:

git add [path to the added file]
git status

this lists the three updated and one added file

git commit -a
git status

no changes found

git format-patch master --stdout > my_patch.patch

All is good to this point. Now I want to merge this branch back into master.

git checkout master
git status

No changes found

git merge my_patch

The output from which is:

Updating ffdd99a..e2754ca
error: Your local changes to 'Blah.cs' would be overwritten by merge.
Aborting. Please, commit your changes
or stash them before you can merge.

And now if I do git status I get a boat load of changes listed.  Does this make any sense to anyone?


问:
Geolocation coords not passing from javascript to php
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

```<code>var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};
</code>```

it should send the data to template-userslocation.phpwhere I have this code:

```<code><?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
</code>```

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

答:
there is no data. Nothing in the page and in the console.

Your PHP code copies the POSTed data into a couple of variables. That is all.

It doesn't output anything. It doesn't use the variables for anything.

It just stores in the data in variables, then exits (which destroys the variables because they only exist for the lifetime of the program execution).

You need to do something with the data.

You could just output it straight back:

```<code><?php header("Content-Type: text/plain"); echo $lat; echo $lng; ?>
</code>```

… which isn't very useful, but serves as a demonstration.

Your JavaScript does nothing with the response.

(The response, as mentioned above, doesn't contain anything, so you need to fix the PHP first).

You have no success handler in your JavaScript, so when the browser gets the response, your code doesn't do anything with it. This is why nothing is shown in the browser.

```<code>    url: '/wp-content/themes/atripby/template-userslocation.php'
}).done(function(data) { console.log(data); });
</code>```

… would show the results in the browser's developer tools console.

Body:
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};

it should send the data to template-userslocation.phpwhere I have this code:

<?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

Body:
there is no data. Nothing in the page and in the console.

Your PHP code copies the POSTed data into a couple of variables. That is all.

It doesn't output anything. It doesn't use the variables for anything.

It just stores in the data in variables, then exits (which destroys the variables because they only exist for the lifetime of the program execution).

You need to do something with the data.

You could just output it straight back:

<?php header("Content-Type: text/plain"); echo $lat; echo $lng; ?>

… which isn't very useful, but serves as a demonstration.

Your JavaScript does nothing with the response.

(The response, as mentioned above, doesn't contain anything, so you need to fix the PHP first).

You have no success handler in your JavaScript, so when the browser gets the response, your code doesn't do anything with it. This is why nothing is shown in the browser.

    url: '/wp-content/themes/atripby/template-userslocation.php'
}).done(function(data) { console.log(data); });

… would show the results in the browser's developer tools console.


问:
Ansible: How to increment IP address?
I am passing a variable to Ansible with --extra-vars "lan=10.10.10.1".

I now need to increment this IPaddress so that the last octet is .2 so it will equal 10.10.10.2.

How would this be achieved in Ansible?

答:
Before Ansible 2.7

Using the ipaddr filter:

```<code>{{ ((lan | ipaddr('int')) + 1) | ipaddr }}
</code>```

Be careful with the operator precedence of Jinja2, it's quite funky.

Ansible 2.7+

Use ipmath() filter. See the answer by Lars Francke.

ContentLicense: CC BY-SA 4.0

Title: Ansible: How to increment IP address?

Body:
Before Ansible 2.7

Using the ipaddr filter:

{{ ((lan | ipaddr('int')) + 1) | ipaddr }}

Be careful with the operator precedence of Jinja2, it's quite funky.

Ansible 2.7+

Use ipmath() filter. See the answer by Lars Francke.


问:
Standard TableView Cell - label text overlaps with uiimage
This is happening but I don't know why. It is a standard tableviewcell with a label and an image on it

Here is the code:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = patientsTableView.dequeueReusableCell(withIdentifier: "patientTableViewCell", for: indexPath)
    let text = "Bob Marley"
    cell.textLabel?.text = text
    return cell
}
</code>```

答:
When I do not put an image view in the object inspector but like below, it solves the problem. I am not sure why though</p>

```<code>cell.imageView?.image = UIImage(named: "patients")
</code>```

Body:
This is happening but I don't know why. It is a standard tableviewcell with a label and an image on it

Here is the code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = patientsTableView.dequeueReusableCell(withIdentifier: "patientTableViewCell", for: indexPath)
    let text = "Bob Marley"
    cell.textLabel?.text = text
    return cell
}

Body:
When I do not put an image view in the object inspector but like below, it solves the problem. I am not sure why though

cell.imageView?.image = UIImage(named: "patients")


问:
How to close $uibModal from a function if modal is attached to the same scope?
I receive close is not a function when trying to close a modal window created by $uibModal.open()

I have reduced the problem to minimal code:

```<code>    var app = angular.module('demoApp', ['ui.bootstrap']);

    app.controller('DemoContrller', function($scope, $uibModal) {
      var vm = this;
      var myModalInstance = null;

      vm.openModal = function() {

        myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              }).result.then(function() {
                  console.log('fully closed with successful validation');
              });

      };

      vm.onApplyModal = function() {

          console.log('doing some validation and closing only if succeeded');

          // ??? close is not a function, myModalInstance is a Promise

          console.log(myModalInstance);
          myModalInstance.close();
      };

    })
</code>```

Please see my Plunk here: Cannot close uibmodal from a function in the same scope

答:
```<code> myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              }).result.then(function() {
                  console.log('fully closed with successful validation');
              });
</code>```

First assign variable, then chain:

```<code> myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              });
myModalInstance .result.then(function() {
                  console.log('fully closed with successful validation');
              });
</code>```

Body:
I receive close is not a function when trying to close a modal window created by $uibModal.open()

I have reduced the problem to minimal code:

    var app = angular.module('demoApp', ['ui.bootstrap']);

    app.controller('DemoContrller', function($scope, $uibModal) {
      var vm = this;
      var myModalInstance = null;

      vm.openModal = function() {

        myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              }).result.then(function() {
                  console.log('fully closed with successful validation');
              });

      };

      vm.onApplyModal = function() {

          console.log('doing some validation and closing only if succeeded');

          // ??? close is not a function, myModalInstance is a Promise

          console.log(myModalInstance);
          myModalInstance.close();
      };

    })

Please see my Plunk here: Cannot close uibmodal from a function in the same scope

Body:
 myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              }).result.then(function() {
                  console.log('fully closed with successful validation');
              });

First assign variable, then chain:

 myModalInstance = $uibModal.open({
                  animation: true,
                  templateUrl: 'modalTemplate.html',
                  scope: $scope // important - want to reuse current scope and controller and not create new
              });
myModalInstance .result.then(function() {
                  console.log('fully closed with successful validation');
              });


问:
$http simultaneous duplicate API call, return promise
In my app, we are using micro services structure, and for that we have aso added caching.

But there is a scenario in which multiple same request gets fired, and the request are fired at the same time, so caching also doesn't seem to work.
I want that for duplicate request it should send promise of previous request.

Also there are lots of services, so adding promise to each service will not work. Is there any place where to handle duplicate request and pass the previous request promise at a common place. might be by using decorator or http interceptor.

Service call

```<code>testService.getTestByIds = function (
                                testIds,
                                contextInfo) {
         var params = {
                 testId: requestDefinitionIds
           };
         params = CommonProvider.apppendContextParams(contextInfo, params,testInfoCache);
          return $http.get(SERVICE_URL + 'tests', {
                                cache: testInfoCache,
                                params: params,
                                transformResponse: CommonProvider.appendTransformer($http.defaults.transformResponse, function (value) {
                                    return transformTestResponse(value);
                                })
                            });
                        };
</code>```

答:
I assume you mean caching on the client, you could try something like this:</p>

```<code>const activeRequest =
  () => {
    const requests = {};
    return (url,params) => {
      const promise = requests[url+JSON.stringify(params)];
      if(promise){
        return promise;
      }
      return requests[url+JSON.stringify(params)] =
        //not sure what you use for angular, maybe $http for angular1
        fetch(url,params)
        .then(
          x=>{
            requests[url+JSON.stringify(params)] = undefined;
            return x;
          }
        )
    }
  }
</code>```

Body:
In my app, we are using micro services structure, and for that we have aso added caching.

But there is a scenario in which multiple same request gets fired, and the request are fired at the same time, so caching also doesn't seem to work.
I want that for duplicate request it should send promise of previous request.

Also there are lots of services, so adding promise to each service will not work. Is there any place where to handle duplicate request and pass the previous request promise at a common place. might be by using decorator or http interceptor.

Service call

testService.getTestByIds = function (
                                testIds,
                                contextInfo) {
         var params = {
                 testId: requestDefinitionIds
           };
         params = CommonProvider.apppendContextParams(contextInfo, params,testInfoCache);
          return $http.get(SERVICE_URL + 'tests', {
                                cache: testInfoCache,
                                params: params,
                                transformResponse: CommonProvider.appendTransformer($http.defaults.transformResponse, function (value) {
                                    return transformTestResponse(value);
                                })
                            });
                        };

Body:
I assume you mean caching on the client, you could try something like this:

const activeRequest =
  () => {
    const requests = {};
    return (url,params) => {
      const promise = requests[url+JSON.stringify(params)];
      if(promise){
        return promise;
      }
      return requests[url+JSON.stringify(params)] =
        //not sure what you use for angular, maybe $http for angular1
        fetch(url,params)
        .then(
          x=>{
            requests[url+JSON.stringify(params)] = undefined;
            return x;
          }
        )
    }
  }


问:
Export to vector graphics fails with large number of data-points
I want to export some MATLAB-plots as vector-graphics for presentations. In the most cases, using print-command, for example:

```<code>set(0,'defaultAxesTickLabelInterpreter','Latex')
set(0,'defaultTextInterpreter','Latex')

t=linspace(0,6,6000);
s=sin(t);

figure
for spl=1:16
    subplot(4,4,spl);
    plot(t,s,'k')
end

print('Sinetest','-dpdf');
</code>```

but as soon as the number of data-points (or the expected file size) turns too big, for example use t=linspace(0,6,7000); the method fails: instead of a scalable vector graphic, an ugly pixel-monster is saved in the .pdf-file. I've tried to use other file-formats, for exampl .emf, .eps, .svg (svg is what I need actually) instead of .pdf, but it's always the same problem. Reducing the number of data points works in this example, but not in general for me.

Is there any option or work around?

答:
The solution is to specify that the painter renderer should be used:

```<code>print('Sinetest','-dpdf', '-painters');
</code>```

If you save to a vector graphics file and if the figure RendererMode
  property is set to 'auto', then print automatically attempts to use
  the Painters renderer. If you want to ensure that your output format
  is a true vector graphics file, then specify the Painters renderer.

Note that this may result in long rendering times as mentioned in the docs:

Sometimes, saving a file with the '-painters' option can cause longer
  rendering times [...]

Body:
I want to export some MATLAB-plots as vector-graphics for presentations. In the most cases, using print-command, for example:

set(0,'defaultAxesTickLabelInterpreter','Latex')
set(0,'defaultTextInterpreter','Latex')

t=linspace(0,6,6000);
s=sin(t);

figure
for spl=1:16
    subplot(4,4,spl);
    plot(t,s,'k')
end

print('Sinetest','-dpdf');

but as soon as the number of data-points (or the expected file size) turns too big, for example use t=linspace(0,6,7000); the method fails: instead of a scalable vector graphic, an ugly pixel-monster is saved in the .pdf-file. I've tried to use other file-formats, for exampl .emf, .eps, .svg (svg is what I need actually) instead of .pdf, but it's always the same problem. Reducing the number of data points works in this example, but not in general for me.

Is there any option or work around?

Body:
The solution is to specify that the painter renderer should be used:

print('Sinetest','-dpdf', '-painters');

If you save to a vector graphics file and if the figure RendererMode
  property is set to 'auto', then print automatically attempts to use
  the Painters renderer. If you want to ensure that your output format
  is a true vector graphics file, then specify the Painters renderer.

Note that this may result in long rendering times as mentioned in the docs:

Sometimes, saving a file with the '-painters' option can cause longer
  rendering times [...]


问:
Sum an array of milliseconds
I'm having an array of milliseconds which I want a total of. I have tried the array.reduce and use a for-loop but all I get is total gibberish when I console it or use on the site. If I get the milliseconds summed up I could convert them to seconds and, if needed, minutes.

Code:

```<code>window.timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418]

let totalTimeSum = 0
for (let i = 0; i < window.timeArray.length; i++) {
  totalTimeSum += parseInt(window.timeArray[i])
}
document.querySelector('#score').innerText += totalTimeSum
// 1866018660, should be 15249 - 15 sec 249 millisec
</code>```

Optional code:

```<code>let totalTime = (sum, value) => sum + value
let totalTimeSum = window.timeArray.reduce(totalTime)
document.querySelector('#score').innerText += totalTimeSum
// 1866018660, should be 15249 - 15 sec 249 millisec
</code>```

答:
In order to accomplish what you need, you can do the following:

You can use Array.prototype.reduce to calculate the sum of the array's elements.

Then, to calculate the number of seconds, round down the quotient of the sum divided by 1000.

The remainder is the number of milliseconds remaining.

Snippet:

var
  /* Define the array. */
  timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418],

  /* Calculate the sum. */
  sum = timeArray.reduce((previous, current) => previous + current, 0),

  /* Calculate the seconds. */
  seconds = Math.floor(sum / 1000),

  /* Calculate the milliseconds. */
  milliseconds = sum % 1000;

/* Set the value as text to the score element. */
document.querySelector("#score").innerText = seconds + "s " + milliseconds + "ms";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id = "score"></div></code>```

Title: Sum an array of milliseconds

Body:
I'm having an array of milliseconds which I want a total of. I have tried the array.reduce and use a for-loop but all I get is total gibberish when I console it or use on the site. If I get the milliseconds summed up I could convert them to seconds and, if needed, minutes.

Code:

window.timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418]

let totalTimeSum = 0
for (let i = 0; i < window.timeArray.length; i++) {
  totalTimeSum += parseInt(window.timeArray[i])
}
document.querySelector('#score').innerText += totalTimeSum
// 1866018660, should be 15249 - 15 sec 249 millisec

Optional code:

let totalTime = (sum, value) => sum + value
let totalTimeSum = window.timeArray.reduce(totalTime)
document.querySelector('#score').innerText += totalTimeSum
// 1866018660, should be 15249 - 15 sec 249 millisec

Body:
In order to accomplish what you need, you can do the following:

You can use Array.prototype.reduce to calculate the sum of the array's elements.

Then, to calculate the number of seconds, round down the quotient of the sum divided by 1000.

The remainder is the number of milliseconds remaining.

Snippet:

var
  /* Define the array. */
  timeArray = [2493, 2109, 4424, 1971, 3411, 1834, 2418],

  /* Calculate the sum. */
  sum = timeArray.reduce((previous, current) => previous + current, 0),

  /* Calculate the seconds. */
  seconds = Math.floor(sum / 1000),

  /* Calculate the milliseconds. */
  milliseconds = sum % 1000;

/* Set the value as text to the score element. */
document.querySelector("#score").innerText = seconds + "s " + milliseconds + "ms";

<div id = "score"></div>


问:
Slow initial webpack build
I'm using React + Redux + Webpack but having an annoying development experience when every time I rerun the node server (using JetBrains WebStorm) it takes 2.5 minutes for webpack to bunde everything together.

I tried every possible technique to make webpack initial build faster but with no success. It takes 2.5 minutes to run this.

I tried:

Babel caching

Webpack module analyzer

excluding node_modules

Here is my webpack.config.js file:

let path = require('path')
let webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

let entry = {
    bundle: './src/index',
    vendor: [
        'react',
        'react-dom',
        'redux',
        'react-redux',
        'react-router',
        'react-router-dom',
        'react-router-redux',
        'redux-thunk',
        'd3',
        'immutable',
        'moment',
        'axios',
        'openlayers',
        'react-table',
        'react-select',
        'reselect'
    ]
}

let plugins = [
    new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify(ENV === 'prod' ? 'production' : 'development'),
            API_URL: JSON.stringify(API_URL),
            BASIC: JSON.stringify(BASIC)
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        beautify: false,
        comments: false,
        compress: {
            sequences   : true,
            booleans    : true,
            loops       : true,
            unused      : true,
            warnings    : false,
            drop_console: true,
            unsafe      : true
        }
    })
]

const config = {
    entry: entry,
    cache: true,
    devtool: 'cheap-module-source-map',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/dist/'
    },
    plugins: plugins,
    module: {
        rules: [
            {
                enforce: "pre",
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "eslint-loader",
            },
            {
                test: /\.js$/,
                loader: 'babel-loader?cacheDirectory',
                query: {
                    plugins: ['transform-runtime']
                },
                include: [path.resolve(__dirname, "src")],
                exclude: /node_modules/
            },
            {
                test: /\.(css|less)$/,
                use: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
                    `image-webpack-loader?${JSON.stringify(query)}`
                ]
            },
            {
                test: /\.(eot|woff|woff2|ttf)$/,
                loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
            }
        ]
    }
}

module.exports = config```
</div>
</div>
</p>

<p>and here is my package.json file:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "Aloha",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "start-debug": "node $NODE_DEBUG_OPTION server.js",
    "build": "webpack",
    "test": "jest --verbose",
    "test:watch": "npm test -- --watch",
    "test-coverage": "jest --coverage",
    "webpack-stats": "webpack --profile",
    "startwatch": "nodemon server.js"
  },
  "author": "Aloha",
  "license": "ISC",
  "devDependencies": {
    "@amcharts/amcharts3-react": "^3.0.0",
    "babel-core": "^6.11.4",
    "babel-eslint": "^8.0.3",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "css-loader": "^0.28.4",
    "eslint": "^4.12.1",
    "eslint-loader": "^1.4.1",
    "eslint-plugin-react": "^7.0.1",
    "file-loader": "^1.1.5",
    "image-webpack-loader": "^3.3.1",
    "less": "^2.7.1",
    "less-loader": "^4.0.5",
    "postcss-loader": "^2.0.9",
    "redux-mock-store": "^1.2.1",
    "style-loader": "^0.19.0",
    "url-loader": "^0.6.2",
    "webpack-bundle-analyzer": "^2.9.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-hot-middleware": "^2.12.1"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-es2017": "^6.24.1",
    "body-parser": "^1.17.2",
    "classnames": "^2.2.5",
    "compression": "^1.6.2",
    "connect-multiparty": "^2.0.0",
    "cookie-parser": "^1.4.3",
    "d3": "^4.3.0",
    "dotenv": "^4.0.0",
    "express": "^4.15.3",
    "history": "^4.7.2",
    "http-proxy-middleware": "^0.17.4",
    "immutable": "^3.8.1",
    "lodash": "^4.17.4",
    "moment": "^2.14.1",
    "moment-timezone": "^0.5.13",
    "nodemon": "^1.12.1",
    "openlayers": "^4.5.0",
    "prop-types": "^15.5.10",
    "querystring": "^0.2.0",
    "rc-collapse": "^1.7.5",
    "react": "^16.2.0",
    "react-block-ui": "^1.1.1",
    "react-datetime": "^2.8.6",
    "react-dom": "^16.2.0",
    "react-imageloader": "^2.1.0",
    "react-notification-system": "^0.2.15",
    "react-redux": "^5.0.5",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^5.0.0-alpha.8",
    "react-select": "^1.0.0-rc.5",
    "react-table": "^6.7.4",
    "react-tabs": "^2.1.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.1.0",
    "request": "^2.74.0",
    "reselect": "^3.0.1",
    "webpack": "^3.9.1"
  }
}</code>```

Help will be deeply appreciated !

答:
It depends a lot on your machine. Make sure you have enough disk space and good processor for your project.
Apart from this, for more improvements you can go through this link.</p>

Title: Slow initial webpack build

Body:
I'm using React + Redux + Webpack but having an annoying development experience when every time I rerun the node server (using JetBrains WebStorm) it takes 2.5 minutes for webpack to bunde everything together.

I tried every possible technique to make webpack initial build faster but with no success. It takes 2.5 minutes to run this.

I tried:

Babel caching

Webpack module analyzer

excluding node_modules

Here is my webpack.config.js file:

let path = require('path')
let webpack = require('webpack')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

let entry = {
    bundle: './src/index',
    vendor: [
        'react',
        'react-dom',
        'redux',
        'react-redux',
        'react-router',
        'react-router-dom',
        'react-router-redux',
        'redux-thunk',
        'd3',
        'immutable',
        'moment',
        'axios',
        'openlayers',
        'react-table',
        'react-select',
        'reselect'
    ]
}

let plugins = [
    new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify(ENV === 'prod' ? 'production' : 'development'),
            API_URL: JSON.stringify(API_URL),
            BASIC: JSON.stringify(BASIC)
        }
    }),
    new webpack.optimize.UglifyJsPlugin({
        beautify: false,
        comments: false,
        compress: {
            sequences   : true,
            booleans    : true,
            loops       : true,
            unused      : true,
            warnings    : false,
            drop_console: true,
            unsafe      : true
        }
    })
]

const config = {
    entry: entry,
    cache: true,
    devtool: 'cheap-module-source-map',
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/dist/'
    },
    plugins: plugins,
    module: {
        rules: [
            {
                enforce: "pre",
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "eslint-loader",
            },
            {
                test: /\.js$/,
                loader: 'babel-loader?cacheDirectory',
                query: {
                    plugins: ['transform-runtime']
                },
                include: [path.resolve(__dirname, "src")],
                exclude: /node_modules/
            },
            {
                test: /\.(css|less)$/,
                use: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
                    `image-webpack-loader?${JSON.stringify(query)}`
                ]
            },
            {
                test: /\.(eot|woff|woff2|ttf)$/,
                loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
            }
        ]
    }
}

module.exports = config

and here is my package.json file:

{
  "name": "Aloha",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "start-debug": "node $NODE_DEBUG_OPTION server.js",
    "build": "webpack",
    "test": "jest --verbose",
    "test:watch": "npm test -- --watch",
    "test-coverage": "jest --coverage",
    "webpack-stats": "webpack --profile",
    "startwatch": "nodemon server.js"
  },
  "author": "Aloha",
  "license": "ISC",
  "devDependencies": {
    "@amcharts/amcharts3-react": "^3.0.0",
    "babel-core": "^6.11.4",
    "babel-eslint": "^8.0.3",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "babel-preset-stage-0": "^6.5.0",
    "css-loader": "^0.28.4",
    "eslint": "^4.12.1",
    "eslint-loader": "^1.4.1",
    "eslint-plugin-react": "^7.0.1",
    "file-loader": "^1.1.5",
    "image-webpack-loader": "^3.3.1",
    "less": "^2.7.1",
    "less-loader": "^4.0.5",
    "postcss-loader": "^2.0.9",
    "redux-mock-store": "^1.2.1",
    "style-loader": "^0.19.0",
    "url-loader": "^0.6.2",
    "webpack-bundle-analyzer": "^2.9.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-hot-middleware": "^2.12.1"
  },
  "dependencies": {
    "axios": "^0.17.1",
    "babel-preset-es2017": "^6.24.1",
    "body-parser": "^1.17.2",
    "classnames": "^2.2.5",
    "compression": "^1.6.2",
    "connect-multiparty": "^2.0.0",
    "cookie-parser": "^1.4.3",
    "d3": "^4.3.0",
    "dotenv": "^4.0.0",
    "express": "^4.15.3",
    "history": "^4.7.2",
    "http-proxy-middleware": "^0.17.4",
    "immutable": "^3.8.1",
    "lodash": "^4.17.4",
    "moment": "^2.14.1",
    "moment-timezone": "^0.5.13",
    "nodemon": "^1.12.1",
    "openlayers": "^4.5.0",
    "prop-types": "^15.5.10",
    "querystring": "^0.2.0",
    "rc-collapse": "^1.7.5",
    "react": "^16.2.0",
    "react-block-ui": "^1.1.1",
    "react-datetime": "^2.8.6",
    "react-dom": "^16.2.0",
    "react-imageloader": "^2.1.0",
    "react-notification-system": "^0.2.15",
    "react-redux": "^5.0.5",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^5.0.0-alpha.8",
    "react-select": "^1.0.0-rc.5",
    "react-table": "^6.7.4",
    "react-tabs": "^2.1.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.1.0",
    "request": "^2.74.0",
    "reselect": "^3.0.1",
    "webpack": "^3.9.1"
  }
}

Help will be deeply appreciated !


问:
PHP Remove Domain Name Extension from String
I was wondering of the best way of removing certain things from a domain using PHP.

For example:

"http://mydomain.com/" into "mydomain"

or

"http://mydomain.co.uk/" into "mydomain"

I'm looking for a quick function that will allow me to remove such things as:

"http://", "www.", ".com", ".co.uk", ".net", ".org", "/" etc

Thanks in advance :)

答:
To get the host part of a URL use parse_url:

```<code>$host = parse_url($url, PHP_URL_HOST);
</code>```

And for the rest see my answer to Remove domain extension.

Body:
To get the host part of a URL use parse_url:

$host = parse_url($url, PHP_URL_HOST);

And for the rest see my answer to Remove domain extension.


问:
Error Terrier Java in eclipse with java sample code
Hi everyone,

I went through the terrier quickstart tutorial corpus and then I run the code below:

```<code>import java.util.Arrays;
import org.terrier.indexing.Collection;
import org.terrier.indexing.SimpleFileCollection;
import org.terrier.structures.indexing.Indexer;
import org.terrier.structures.indexing.classical.BasicIndexer;
import org.terrier.utility.ApplicationSetup;

public class IndexingExample {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        // Directory containing files to index
            String aDirectoryToIndex = "/home/nadhem/PFE/terrier-core-4.2/share/vaswani_npl/corpus/";

        // Configure Terrier
            ApplicationSetup.setProperty("terrier.home", "/home/nadhem/PFE/terrier-core-4.2");

            Indexer indexer = new BasicIndexer("/home/nadhem/PFE/terrier-core-4.2/var/index", "data");
            Collection coll = new SimpleFileCollection(Arrays.asList(aDirectoryToIndex), true);
            indexer.index(new Collection[]{coll});
    }

}
</code>```

I got the following error:

WARNING: The file terrier.properties was not found at location /etc/terrier.properties Assuming the value of terrier.home from the corresponding system property.
Please ensure that the property terrier.home is specified in the file terrier.properties, or as a system property in the command line.

I didn't understand why the properties file was not found despite having checked it...there is another

Any help would be most appreciated.

thanks,
Nadhmanovic

答:
I solved the issue by supplying terrier.home as VM argument.

Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

```<code>-Dterrier.home=/home/nadhem/PFE/terrier-core-4.2
</code>```

I hope this will solve your issue.

Body:
Hi everyone,

I went through the terrier quickstart tutorial corpus and then I run the code below:

import java.util.Arrays;
import org.terrier.indexing.Collection;
import org.terrier.indexing.SimpleFileCollection;
import org.terrier.structures.indexing.Indexer;
import org.terrier.structures.indexing.classical.BasicIndexer;
import org.terrier.utility.ApplicationSetup;

public class IndexingExample {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        // Directory containing files to index
            String aDirectoryToIndex = "/home/nadhem/PFE/terrier-core-4.2/share/vaswani_npl/corpus/";

        // Configure Terrier
            ApplicationSetup.setProperty("terrier.home", "/home/nadhem/PFE/terrier-core-4.2");

            Indexer indexer = new BasicIndexer("/home/nadhem/PFE/terrier-core-4.2/var/index", "data");
            Collection coll = new SimpleFileCollection(Arrays.asList(aDirectoryToIndex), true);
            indexer.index(new Collection[]{coll});
    }

}

I got the following error:

WARNING: The file terrier.properties was not found at location /etc/terrier.properties Assuming the value of terrier.home from the corresponding system property.
Please ensure that the property terrier.home is specified in the file terrier.properties, or as a system property in the command line.

I didn't understand why the properties file was not found despite having checked it...there is another

Any help would be most appreciated.

thanks,
Nadhmanovic

Body:
I solved the issue by supplying terrier.home as VM argument.

Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

-Dterrier.home=/home/nadhem/PFE/terrier-core-4.2

I hope this will solve your issue.


问:
Downloading via SVN for MAC
I have to download a repository via SVN by using Mac. And I have some troubles with it. I, actually, past the URL and stuff. And put my password and log in right there but it still gives some strange errors and mb some of you can help me and tell how to do deals with it.

Here is my error:

```<code>svn: E170013: Unable to connect to a repository at URL 'https://svn.pathomation.com:****/!/%23QA_PMA.view.2_trunk'
svn: E175009: The XML response contains invalid XML
svn: E130003: Malformed XML: no element found
</code>```

What does it mean and how to avoid this error?

答: You use incorrect URL with the Subversion client. Read the article KB102: Subversion client errors caused by inappropriate repository URL.</p>

Title: Downloading via SVN for MAC

Body:
I have to download a repository via SVN by using Mac. And I have some troubles with it. I, actually, past the URL and stuff. And put my password and log in right there but it still gives some strange errors and mb some of you can help me and tell how to do deals with it.

Here is my error:

svn: E170013: Unable to connect to a repository at URL 'https://svn.pathomation.com:****/!/%23QA_PMA.view.2_trunk'
svn: E175009: The XML response contains invalid XML
svn: E130003: Malformed XML: no element found

What does it mean and how to avoid this error?


问:
Add data to list and compare
How can I join list and compare with another list

```<code>List list = new ArrayList();
List mList = getGroupById(date, id); // have 2 data
List tList = getSummary(date, id); // have 5 data
tList.addAll(create(tlog));

for (Rev m : (List<Rev>) mList) {
    Detail x = new Detail();
    for (Object[] s : (List<Object[]>) tList) {
        if (s[1].toString().equals(m.getMid())) {
            System.out.println("dddd " + s[1]);
        }
    }
}
</code>```

Query

```<code>public List create(List<Alog> tlog) {
    List list = new ArrayList<>();
    ...

    Detail x = new Detail();
    ...
    x.setAbc(abc);
    list.add(x);

    return list;
}

public List getSummary(String date, String id)
{
    StringBuilder bf = new StringBuilder();
    bf.append("SELECT ");
    bf.append("'ABC', ");
    ...
    return em.createQuery(bf.toString())
            .setParameter("date", date, TemporalType.DATE)
            .setParameter("id", id)
            .getResultList();
}
</code>```

Error

```<code> cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
</code>```

pointed to

```<code>for (Object[] s : (List<Object[]>) tList)
</code>```

答:
The Ljava.lang.Object is the name for Object[].class, the java.lang.Class representing the class of array of Object.

I.e you are trying to cast to Object[] that is not compatible with the real Object you have.

Obviously the result of your query is a List as usual, so you should try with iterators.

Instead of for (Object[] s : (List<Object[]>) tList) use:

```<code>Iterator itr = tList.iterator();
while(itr.hasNext()){
   Object[] s= (Object[]) itr.next();

   //now you have one array of Object for each row
   if (String.valueOf(s[1]).equals(m.getMid())) {
       System.out.println("dddd " + String.valueOf(s[1]));
   }
}
</code>```

Title: Add data to list and compare

Body:
How can I join list and compare with another list

List list = new ArrayList();
List mList = getGroupById(date, id); // have 2 data
List tList = getSummary(date, id); // have 5 data
tList.addAll(create(tlog));

for (Rev m : (List<Rev>) mList) {
    Detail x = new Detail();
    for (Object[] s : (List<Object[]>) tList) {
        if (s[1].toString().equals(m.getMid())) {
            System.out.println("dddd " + s[1]);
        }
    }
}

Query

public List create(List<Alog> tlog) {
    List list = new ArrayList<>();
    ...

    Detail x = new Detail();
    ...
    x.setAbc(abc);
    list.add(x);

    return list;
}

public List getSummary(String date, String id)
{
    StringBuilder bf = new StringBuilder();
    bf.append("SELECT ");
    bf.append("'ABC', ");
    ...
    return em.createQuery(bf.toString())
            .setParameter("date", date, TemporalType.DATE)
            .setParameter("id", id)
            .getResultList();
}

Error

 cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) cannot be cast to [Ljava.lang.Object;
    at com.rh.app.service.reader.SummaryReader.read(SummaryReader.java:182)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)

pointed to

for (Object[] s : (List<Object[]>) tList)

Body:
The Ljava.lang.Object is the name for Object[].class, the java.lang.Class representing the class of array of Object.

I.e you are trying to cast to Object[] that is not compatible with the real Object you have.

Obviously the result of your query is a List as usual, so you should try with iterators.

Instead of for (Object[] s : (List<Object[]>) tList) use:

Iterator itr = tList.iterator();
while(itr.hasNext()){
   Object[] s= (Object[]) itr.next();

   //now you have one array of Object for each row
   if (String.valueOf(s[1]).equals(m.getMid())) {
       System.out.println("dddd " + String.valueOf(s[1]));
   }
}


问:
Export Highchart to Excel using PHPExcel
I'm using codeigniter and some highchart on one report. And I need to export that report to excel using PHPExcel, but right now I still can't find any solution for this case

Is there's any information How To Export multiple highcharts on one excel file ?

答:
You cannot directly export a chart from Highchart to Excel. I know 2 solutions:

Use the Highchart data to make a chart using PHPExcel.

Use same JSON to generate a Highchart chart and a chart generated by PHPExcel.

Anothe possibility is to export the Highchart chart as an image and then uploading that image to the server and add it to Excel.


问:
Set Dynemic index value in multidimesnsion array
My html page like this (View)

```<code>  foreach ($va as $key=>$value) {

?>
<td>
    <?= $value->id; ?> <input type="hidden" name="mark[1][sid]" value="<?= $value->id; ?>" >
    <input type="text" name=" mark[1][maths]"  >
    <input type="text"  name="mark[1][ss]">
    <input type="text"  name="mark[1][science]">
    <input type="text"  name="mark[1][english]">
    </td>
</code>```

MY Controller like this

```<code> $data=$this->input->post();
            echo "```";
print_r($data);
```

Display Scrrenshot Like this
Html Page (View)

And my output is like Output Display

This output display only last row data but I fill all data into textbox so what is problem to show all details or full array

And second how to set dynamic index in Multidimensional Array mark[$dynamic_index][sid]

i use <input type="text" name=" mark[$key][maths]"  >

But Not Working

I can display all array data and generate dynamic index(key) in array

Thanks Advance

答:
Hello Just use below code </p>

```<code><?php
$count=0;
foreach ($va as $key=>$value) {

?>
<td>
    <?= $value->id; ?> <input type="hidden" name="mark[1][sid]" value="<?= $value->id; ?>" >
    <input type="text" name=" mark[<?php echo $count; ?>][maths]"  >
    <input type="text"  name="mark[<?php echo $count; ?>][ss]">
    <input type="text"  name="mark[<?php echo $count; ?>][science]">
    <input type="text"  name="mark[<?php echo $count; ?>][english]">
</td>
<?php
$count++;
}
?>
</code>```

Body:
My html page like this (View)

  foreach ($va as $key=>$value) {

?>

    <?= $value->id; ?> <input type="hidden" name="mark[1][sid]" value="<?= $value->id; ?>" >
    <input type="text" name=" mark[1][maths]"  >
    <input type="text"  name="mark[1][ss]">
    <input type="text"  name="mark[1][science]">
    <input type="text"  name="mark[1][english]">

MY Controller like this

 $data=$this->input->post();
            echo "
";
print_r($data);

Display Scrrenshot Like this
Html Page (View)

And my output is like Output Display

This output display only last row data but I fill all data into textbox so what is problem to show all details or full array

And second how to set dynamic index in Multidimensional Array mark[$dynamic_index][sid]

i use <input type="text" name=" mark[$key][maths]"  >

But Not Working

I can display all array data and generate dynamic index(key) in array

Thanks Advance

Body:
Hello Just use below code

<?php
$count=0;
foreach ($va as $key=>$value) {

?>
<td>
    <?= $value->id; ?> <input type="hidden" name="mark[1][sid]" value="<?= $value->id; ?>" >
    <input type="text" name=" mark[<?php echo $count; ?>][maths]"  >
    <input type="text"  name="mark[<?php echo $count; ?>][ss]">
    <input type="text"  name="mark[<?php echo $count; ?>][science]">
    <input type="text"  name="mark[<?php echo $count; ?>][english]">
</td>
<?php
$count++;
}
?>


问:
how to connection establish with both database from different database oracle and mysql in yii2
Actually i create a application and
please someone say me. how to establish connection with mysql and different oracle server.
and how to update if update my mysql field so automatic update my oracle erp system.</p>

答:
Follow the link that @Paritosh Mahale has commented up:

Multiple database connections and Yii 2.0

as regards the part of updating the fields in a database you can use migrations in these ways:

```<code>/yiic migrate                 # The default component db
/yiic migrate --db=db1        # Connection db component mysql
/yiic migrate --db=db2        # Connection oracle component db
</code>```

and you need to run the same migration command on both databases with different option --db.

Or you can override the init() method of yii\db\Migration:

```<code><?php

use yii\db\Migration;

class m150101_185401_create_news_table extends Migration
{
    public function init()
    {
        $this->db = 'db2';
        parent::init();
    }
}
</code>```

and use like this: /yiic migrate
This migration will be applied to db2.
If you have multiple migrations that use the same database, it is recommended that you create a base migration class with the above init() code. Then each migration class can extend from this base class.

If you want to have separated path of migrations for each database connections you can do like this:

```<code>yii migrate --migrationPath=@app/migrations/db1 --db=db1
yii migrate --migrationPath=@app/migrations/db2 --db=db2
...
</code>```

For apply migrations "automatic" in each database in one command you can (just an idea) extend yii\console\controllers\MigrateController class and add a property public $dbs. After you can add that property to options() so when you call the migrate command you can pass a param like this:

```<code>/yiic migrate --dbs=db1,db2
</code>```

and so you can manage that parameter for executing a migration for each $dbs;

[Edit]

Some parts of the answer were taken from here: Migrating Multiple Databases

Body:
Follow the link that @Paritosh Mahale has commented up:

Multiple database connections and Yii 2.0

as regards the part of updating the fields in a database you can use migrations in these ways:

/yiic migrate                 # The default component db
/yiic migrate --db=db1        # Connection db component mysql
/yiic migrate --db=db2        # Connection oracle component db

and you need to run the same migration command on both databases with different option --db.

Or you can override the init() method of yii\db\Migration:

<?php

use yii\db\Migration;

class m150101_185401_create_news_table extends Migration
{
    public function init()
    {
        $this->db = 'db2';
        parent::init();
    }
}

and use like this: /yiic migrate
This migration will be applied to db2.
If you have multiple migrations that use the same database, it is recommended that you create a base migration class with the above init() code. Then each migration class can extend from this base class.

If you want to have separated path of migrations for each database connections you can do like this:

yii migrate --migrationPath=@app/migrations/db1 --db=db1
yii migrate --migrationPath=@app/migrations/db2 --db=db2
...

For apply migrations "automatic" in each database in one command you can (just an idea) extend yii\console\controllers\MigrateController class and add a property public $dbs. After you can add that property to options() so when you call the migrate command you can pass a param like this:

/yiic migrate --dbs=db1,db2

and so you can manage that parameter for executing a migration for each $dbs;

[Edit]

Some parts of the answer were taken from here: Migrating Multiple Databases