问:
Can you update items in a transaction in enhanced analytics?
I am using the enhanced ecommerce plugin for Google Analytics in my store.

I am using analytics.js to send transaction information in the checkout success page.

After completing the transaction, I want to update some custom metrics associated with products in the transaction which are not available in the checkout success page.

I was wondering if it is possible to do this via the measurement protocol and if so how?

Thanks

答:
My answer is a year old, but i think i should update an answer. Updating item is possible, but there would a side effect to it. If you call your script again, this will update the transaction in google enhanced eCommerce.

 For e.g if a customer has purchased a red shirt from your e-commerce site, and the customer called you that he want green shirt also, you add green shirt to his item to the customer order from the admin control panel side, now you want to update the google analytics, do following code.

```<code>ga("create", "UA-XXXXX-Y");
ga("require", "ec");
ga("ec:addProduct", {
  "id": "bc823",
  "name": "Fuelworks T-Shirt",
  "price": "92.00",
  "brand": "Fuelworks",
  "category": "T-Shirts",
  "variant": "green",
  "dimension1": "M",
  "position": 0,
  "quantity": 1
});
ga("ec:setAction", "purchase", {
  "id": "d811e9a6-82d5-4145-8f59-9f040cc18fdd", // keep this same to the customer order id.
  "affiliation": "Online Store",
  "revenue": 194, //calculate net total revenue i.e. only new product added revenue
  "tax": 0,//calculate net total tax i.e. only new product added tax
  "shipping": 5 // //calculate net total shipping i.e. only new product added shipping
});
ga("send", "pageview")
</code>```

$194 revenue will be added to your google eCommerce transaction. $5 shipping cost will be added in your google eCommerce transaction.

Now lets talk about side effect,  if you update your transaction a day
  after the original transaction date, google will also update your
  transaction date. Google enhanced e-commerce script does not support
  any purchase date parameter, which they should.

Body:
My answer is a year old, but i think i should update an answer. Updating item is possible, but there would a side effect to it. If you call your script again, this will update the transaction in google enhanced eCommerce.

 For e.g if a customer has purchased a red shirt from your e-commerce site, and the customer called you that he want green shirt also, you add green shirt to his item to the customer order from the admin control panel side, now you want to update the google analytics, do following code.

ga("create", "UA-XXXXX-Y");
ga("require", "ec");
ga("ec:addProduct", {
  "id": "bc823",
  "name": "Fuelworks T-Shirt",
  "price": "92.00",
  "brand": "Fuelworks",
  "category": "T-Shirts",
  "variant": "green",
  "dimension1": "M",
  "position": 0,
  "quantity": 1
});
ga("ec:setAction", "purchase", {
  "id": "d811e9a6-82d5-4145-8f59-9f040cc18fdd", // keep this same to the customer order id.
  "affiliation": "Online Store",
  "revenue": 194, //calculate net total revenue i.e. only new product added revenue
  "tax": 0,//calculate net total tax i.e. only new product added tax
  "shipping": 5 // //calculate net total shipping i.e. only new product added shipping
});
ga("send", "pageview")

$194 revenue will be added to your google eCommerce transaction. $5 shipping cost will be added in your google eCommerce transaction.

Now lets talk about side effect,  if you update your transaction a day
  after the original transaction date, google will also update your
  transaction date. Google enhanced e-commerce script does not support
  any purchase date parameter, which they should.


来源: stackexchange

问:
can I create Buttons on status bar of internet explorer?
I want to create 3 buttons on the status bar of IE.
Any idead how can i do that using C++?</p>

答: You can't.  IE does not support extensions in the status bar.  </p>

ContentLicense: CC BY-SA 2.5


问:
Filter in SearchView not working in Android
I am developing a search function, in which if I enter a search keyword in a searchview in android, i should get the list of the students matching my search word. I have written a code but getting an error. plaese let me know if i am using the adapter in a correct way.  my onCreateOptionsMenu function

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.options_menu, menu);
    SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            StudentAdapter.getFilter().filter(newText);
            return true;

        }
    });

    return true;
}
</code>```

My studentAdapter class:

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

public List<StudentModel> new_list;
private List<StudentModel> original_list;

@Override
public Filter getFilter() {
    return new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            new_list = (List<StudentModel>) results.values;
            StudentAdapter.this.notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults initial_results = new FilterResults();

            if (constraint == null || constraint.length() == 0) {
                initial_results.values = original_list;
                initial_results.count = original_list.size();
            } else {

                // We perform filtering operation
                List<StudentModel> filteredList = new ArrayList<StudentModel>();

                // breaking string into words algorithm
                String str = constraint.toString();
                ArrayList<String> arrayOfWords = new ArrayList<String>();
                int i = 0;
                for (String word : str.split(" ")) {
                    arrayOfWords.add(word);
                    i++;
                }

                for (StudentModel model : original_list) {
                    boolean matched = false;

                    for (String element : arrayOfWords) {

                        if ((null != model.getName() && model
                                .getName().toUpperCase()
                                .contains(element.toString().toUpperCase()))

                                || ((null != model.getClass() && model
                                .getClass()
                                .toUpperCase()
                                .contains(
                                        element.toString()
                                                .toUpperCase())))) {
                            matched = true;
                        } else {
                            matched = false;
                            break;
                        }

                    }

                }

                initial_results.values = filteredList;
                initial_results.count = filteredList.size();

            }

            return initial_results;
        }
    };
    // return null;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView name, class;

    public MyViewHolder(View view) {
        super(view);
        name = (TextView) view.findViewById(R.id.name);
        class = (TextView) view.findViewById(R.id.class);

    }
}

public StudentAdapter(List<StudentModel> original_list) {

    this.original_list = original_list;
}

public List<StudentModel> getStudentlist() {
    return original_list;
}

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

    return new StudentAdapter.MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(StudentAdapter.MyViewHolder holder,
                             int position) {
    StudentModel original_list_vo = original_list.get(position);

    holder.name.setText(original_list_vo.getName());
    holder.class.setText(original_list_vo.getClass());

}

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

}
</code>```

Any help will be appreciated, thanks in advance.

答:
Declare your Search view in onCreate like this.

```<code>sv= (android.widget.SearchView) findViewById(R.id.searchViewid);

sv.setIconifiedByDefault(false);
    sv.setOnQueryTextListener(this);
    sv.setSubmitButtonEnabled(true);
    sv.setQueryHint("Search Here");
</code>```

Now over ride these methods.

```<code>@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText)
{
    android.widget.Filter filter = YourAdapter.getFilter();
    if (TextUtils.isEmpty(newText)) {
        YourListView.clearTextFilter();
        YourAdapter.getFilter().filter("");
    } else {
        YourListView.setFilterText(newText);
    }
    filter.filter(newText);
    return true;
}
</code>```

Try this and tell what output comes.

ContentLicense: CC BY-SA 3.0

Body:
I am developing a search function, in which if I enter a search keyword in a searchview in android, i should get the list of the students matching my search word. I have written a code but getting an error. plaese let me know if i am using the adapter in a correct way.  my onCreateOptionsMenu function

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.options_menu, menu);
    SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            StudentAdapter.getFilter().filter(newText);
            return true;

        }
    });

    return true;
}

My studentAdapter class:

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

public List<StudentModel> new_list;
private List<StudentModel> original_list;

@Override
public Filter getFilter() {
    return new Filter() {
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            new_list = (List<StudentModel>) results.values;
            StudentAdapter.this.notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults initial_results = new FilterResults();

            if (constraint == null || constraint.length() == 0) {
                initial_results.values = original_list;
                initial_results.count = original_list.size();
            } else {

                // We perform filtering operation
                List<StudentModel> filteredList = new ArrayList<StudentModel>();

                // breaking string into words algorithm
                String str = constraint.toString();
                ArrayList<String> arrayOfWords = new ArrayList<String>();
                int i = 0;
                for (String word : str.split(" ")) {
                    arrayOfWords.add(word);
                    i++;
                }

                for (StudentModel model : original_list) {
                    boolean matched = false;

                    for (String element : arrayOfWords) {

                        if ((null != model.getName() && model
                                .getName().toUpperCase()
                                .contains(element.toString().toUpperCase()))

                                || ((null != model.getClass() && model
                                .getClass()
                                .toUpperCase()
                                .contains(
                                        element.toString()
                                                .toUpperCase())))) {
                            matched = true;
                        } else {
                            matched = false;
                            break;
                        }

                    }

                }

                initial_results.values = filteredList;
                initial_results.count = filteredList.size();

            }

            return initial_results;
        }
    };
    // return null;
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView name, class;

    public MyViewHolder(View view) {
        super(view);
        name = (TextView) view.findViewById(R.id.name);
        class = (TextView) view.findViewById(R.id.class);

    }
}

public StudentAdapter(List<StudentModel> original_list) {

    this.original_list = original_list;
}

public List<StudentModel> getStudentlist() {
    return original_list;
}

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

    return new StudentAdapter.MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(StudentAdapter.MyViewHolder holder,
                             int position) {
    StudentModel original_list_vo = original_list.get(position);

    holder.name.setText(original_list_vo.getName());
    holder.class.setText(original_list_vo.getClass());

}

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

}

Any help will be appreciated, thanks in advance.

Body:
Declare your Search view in onCreate like this.

sv= (android.widget.SearchView) findViewById(R.id.searchViewid);

sv.setIconifiedByDefault(false);
    sv.setOnQueryTextListener(this);
    sv.setSubmitButtonEnabled(true);
    sv.setQueryHint("Search Here");

Now over ride these methods.

@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText)
{
    android.widget.Filter filter = YourAdapter.getFilter();
    if (TextUtils.isEmpty(newText)) {
        YourListView.clearTextFilter();
        YourAdapter.getFilter().filter("");
    } else {
        YourListView.setFilterText(newText);
    }
    filter.filter(newText);
    return true;
}

Try this and tell what output comes.


问:
How to set background color to button in table layout programatically?
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

```<code>TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }
</code>```

Please guide me. Thanks in Advance.

答:
You are not giving LayoutParams to your newly created Button. Add this:</p>

```<code>LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);
</code>```

Body:
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }

Please guide me. Thanks in Advance.

Body:
You are not giving LayoutParams to your newly created Button. Add this:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
b.setLayoutParams(params);


问:
CSS displaying one box incorrectly
We have a client whose website which has been working for a few years with no problem. Suddenly we have one block that is not displaying correctly, but only seems to affect Google Chrome: </p>

<p>I guess this is a CSS issue, but we can't figure our what the problem is. Any help would be much appreciated. </p>

答:
Please give a specific height to the div "car-image-grid".

```<code>.car-image-grid{
  /*Height*/
 }
</code>```

I think your image height.

Title: CSS displaying one box incorrectly

Body:
We have a client whose website which has been working for a few years with no problem. Suddenly we have one block that is not displaying correctly, but only seems to affect Google Chrome:

I guess this is a CSS issue, but we can't figure our what the problem is. Any help would be much appreciated.

Body:
Please give a specific height to the div "car-image-grid".

.car-image-grid{
  /*Height*/
 }

I think your image height.


问:
CL_OUT_OF_RESOURCES on Nvidia Quadro M2000M
Yesterday i got to run the unit tests of our current application on the new notebooks and got the CL_OUT_OF_RESOURCES error doing so. The code itself runs without errors on ATI cards or Intel CPU's.

The thing that got me suspicious is that the M2000M supports 'OpenCL 1.2 CUDA'. Is this standard 'OpenCL 1.2' or does it differ and do i need to modify the code?

Here the code:

```<code>__kernel void pointNormals(__global const uint* cellLinkIds, __global const uint* cellLinks,
                                    __global const float3* cellnormals, __global float3* pointnormals,
                                    const uint nrPoints)
{
    const uint gid = get_global_id(0);
    if(gid < nrPoints)
    {
        const uint first = select(cellLinkIds[gid-1], (uint)0, gid==0);
        const uint last = cellLinkIds[gid];

        float3 pointnormal = (float3)0.f;

        for(uint i = first; i < last; ++i)
        {
            pointnormal += cellnormals[cellLinks[i]];
        }

        pointnormals[gid] = normalize(pointnormal);
    }
}
</code>```

/edit:
In the tests i get 6 errors, first at the call of clWaitForEvents the others are from clEnqueueWriteBuffer

答:
found the cause ...

the line with const uint first = select(cellLinkIds[gid-1], (uint)0, gid==0); caused invalid memory access when gid is 0 (first element afaik).

fixed ith with const uint first = gid == 0 ? (uint)0 : cellLinkIds[gid - 1];. but what i dont get is why AMD cards did work with that bug and Nvidia did return an error.

Body:
Yesterday i got to run the unit tests of our current application on the new notebooks and got the CL_OUT_OF_RESOURCES error doing so. The code itself runs without errors on ATI cards or Intel CPU's.

The thing that got me suspicious is that the M2000M supports 'OpenCL 1.2 CUDA'. Is this standard 'OpenCL 1.2' or does it differ and do i need to modify the code?

Here the code:

__kernel void pointNormals(__global const uint* cellLinkIds, __global const uint* cellLinks,
                                    __global const float3* cellnormals, __global float3* pointnormals,
                                    const uint nrPoints)
{
    const uint gid = get_global_id(0);
    if(gid < nrPoints)
    {
        const uint first = select(cellLinkIds[gid-1], (uint)0, gid==0);
        const uint last = cellLinkIds[gid];

        float3 pointnormal = (float3)0.f;

        for(uint i = first; i < last; ++i)
        {
            pointnormal += cellnormals[cellLinks[i]];
        }

        pointnormals[gid] = normalize(pointnormal);
    }
}

/edit:
In the tests i get 6 errors, first at the call of clWaitForEvents the others are from clEnqueueWriteBuffer


问:
Google Play Services on Genymotion emulator with Android 7
I have purchased Genymotion with the goal to have a simulation with Android 7.0 and Google Play.

Android 7.0 runs fine on Genymotion, but I am not able to install Google Play on it.

Google Play works fine for Android 6.0 and below - I was able to find the sources (Flashes) that must be installed additionally for using Google Play in Genymotion.

Does someone know how to install Google Play on an Android 7.0 Device with Genymotion?

答:
UPDATED ANSWER

As @pascal pointing out (kudos to @pascal), since Genymotion 2.10 Google Play Service and Play Store can be automatically installed.

Here is the news from Genymotion 2.10 – Seamlessly install Google Play Services and Play Store:

Genymotion 2.10 is out! And it comes with a 1-click installer for Google Apps

Simply download and install Genymotion 2.10 and a new “Open GApps” widget will be available in your toolbar. Click it and it’ll do the rest!

Now you can have your applications relying on Google Play Services and Google Play Store working perfectly fine. No more fumbling around with random zip files and tutorials found there and there!

OLD ANSWER

Quoting myself from https://stackoverflow.com/a/40712778/4758255:

There is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not
  included by default in Genymotion virtual devices. However, if you
  really need them, you can use the packages provided by OpenGapps.
  Simply follow these steps:

Visit opengapps.org

Select x86 as platform

Choose the Android version corresponding to your virtual device

Select nano as variant

Download the zip file

Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)

Follow the pop-up instructions

    Please note Genymobile Inc. and Genymotion assume no liability
    whatsoever resulting from the download, install and use of Google Play
    Services within your virtual devices. You are solely responsible for
    the use and assume all liability related thereto. Moreover, we
    disclaim any warranties of any kind for a particular purpose regarding
    the compatibility of the OpenGapps packages with any version of
    Genymotion.


问:
mySQL 5.0.45 LAST_INSERT_ID() and values larger than a signed int
I'm attempting to use LAST_INSERT_ID on an auto incremented index that has moved past the signed int value 2147483647. This column is an unsigned int. However, LAST_INSERT_ID() is returning an invalid negative value. Researching this, I've found a couple comments indicating this is the nature of this function. But I cannot find it officially documented. There are some bug reports dating back several years that are still open.

So I need to know if this is in fact a known bug and/or if there's something I can do about this. Do I need to upgrade mySQL to a newer version?

答:
I'm assuming you are using PHP from the comments on the question. (is not currently tagged as "php" related). I'll just add my 2 cents here

I'm attempting to use LAST_INSERT_ID on an auto incremented index that has moved past the signed int value 2147483647. This column is an unsigned int. However, LAST_INSERT_ID() is returning an invalid negative value. Researching this, I've found a couple comments indicating this is the nature of this function. But I cannot find it officially documented. There are some bug reports dating back several years that are still open.

mySQL's LAST_INSERT_ID function will return the ID from the latest INSERT on an AUTO_INCREMENT column (on the current connection) so, if your column is an INTEGER UNSIGNED like you said, it could return values greater than 2147483647. This is the correct behavior.

So I need to know if this is in fact a known bug and/or if there's something I can do about this. Do I need to upgrade mySQL to a newer version?

The mySQL data type has little to do with the representation you chose to use on PHP so the problema is not in the mySQL server. If your PHP installation can't handle numbers so BIG, then you can treat it as a string (Shadow Radiance said).


问:
jquery is not working or angular js nghide show not working in angular routing page
i am using angular 1.6 routing and in ng-view i am showing my routing page data, but in routing pages my jquery code and angular code for hide and show are not working please help me. i am new in angularjs.

```<code><style>
.image-upload > input {
    display:none;
}
.edit-picture {
 position: absolute;
left: 46.5%;
top: 32%;
}
@media only screen and (max-width: 768px){
.edit-picture {
position: absolute;
left: 46.5%;
top: 78%;
 }
 }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#profile-button").click(function(){
    $("#2").show(1000);
    $("#1").hide(1000);
   });
  });
</script>
<div class="col-sm-12 col-lg-10" ng-controller="profile">
   <div class="text-center">
      <div class="col-sm-12">
        <div class="pull-right">
         <a id="profile-button"> <i class="fa fa-pencil fa-2x" style="cursor:pointer;color:#f7972f;"> </i> </a>
        </div>
        <div class="image-upload edit-picture">
            <label for="file-input">
                <i class="fa fa-camera fa-2x" style="cursor:pointer;color:#f7972f;"> </i>
            </label>
            <input id="file-input" type="file"/>
          </div>
          <img src="amit.jpg" class="img img-circle edit-image" style="width:150px;">
             <h3> Amit Singh Chauhan </h3>
        </div>
       <div class="col-sm-12"  id="1">
        <div class="col-sm-1"></div>
        <div class="col-sm-10" >
        This is detail Section
        </div>
        <div class="col-sm-1"></div>
    </div>
    <div class="col-sm-12"  id="2" style="display: none;">
        <div class="col-sm-1"></div>
        <div class="col-sm-10" >
        <form action="" novalidate="novalidate">
            <p><span class="wpcf7-form-control-wrap first-name"><input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name"></span></p>
            <p><span class="wpcf7-form-control-wrap last-name"><input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name"></span></p>
            <p><span class="wpcf7-form-control-wrap email-address"><input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address"></span></p>
            <div><span class="wpcf7-form-control-wrap your-message"><textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea></span></div>
            <div><input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3"><span class="ajax-loader"></span></div>
        </form>
        </div>
        <div class="col-sm-1"></div>
    </div>
</div>
</code>```

答:
Use angular ng-show or ng-hide directive.

If in case you want to hide/show based on some interval/timeout you can use angular built-in services $timeout, $interval

```<code>$timeout(function () {
    $scope.{model_name} = false;
}, timeout_value);
</code>```

Body:
i am using angular 1.6 routing and in ng-view i am showing my routing page data, but in routing pages my jquery code and angular code for hide and show are not working please help me. i am new in angularjs.

            <input id="file-input" type="file"/>

 Amit Singh Chauhan

        This is detail Section

        <form action="" novalidate="novalidate">

<input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="First Name">

<input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name">

<input type="email" name="email-address" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address">

<textarea name="your-message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Comment"></textarea>

<input type="submit" value="Save Profile" class="wpcf7-form-control wpcf7-submit mkd-contact3">

        </form>

Body:
Use angular ng-show or ng-hide directive.

If in case you want to hide/show based on some interval/timeout you can use angular built-in services $timeout, $interval

$timeout(function () {
    $scope.{model_name} = false;
}, timeout_value);


问:
Java multithreading - joining a CPU heavy thread and volatile keyword
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

```<code>public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}
</code>```

答:
Marking a variable as volatile is a hint for the JVM, to flush/sync the related segments of cache between threads/cores when that variable is updated. Marking stop as volatile then has better behaviour (but not perfect, you may have some extra executions on your threads before they see the update).

Marking t as volatile puzzles me as to why it works, it may be that because this is such a small program, t and stop are in the same row in the cache, so when one gets flushed/synced the other does too.

System.out.println is thread safe, so there is some synchronization going on internally. Again, this may be causing some parts of the cache to be synced between the threads.

If anyone can add to this, please do, I also would really like to hear a more detailed answer on this.

Body:
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}


问:
Preflight request fails on Chrome, Safary, Opera
I´m struggling with CORS requests on an Springsecurity backen project + Angulajs frontend.
CORS requests are working fine on IE (also with curl, wget and python requests) but miserably fail on Chrome and Safary because of Preflight bad request.
I know that those Browsers are blocking CORS POSTs, making the request empty as soon as the reach the backend, in fact I don’t see any data when I log out the request from backend. I tried every possible combination of:

Frontend side:

1)  $http(method: POST)

2)  $http.post(

3)  Adding flags: Access-Control-Allow-Origin, Access-Control-Expose, etc.

4)  Adding all possible header combination: ‘Content–Type’:’application/

Browser side:

1)  Start chrome with flag: --disable-web-security

2)  Installing Chrome extension CORS

Backend side:

1)  Spring Security Disable csfr

2)  Spring Security Permit all

3)  Spring Security HttpMethod.OPTION

4)  Set up a CORS Filter that accept all origins: “*”

5)  Activated CORS framework for spring extending WebMvcConfigurerAdapter class.

Nothing, NHOTING worked for me!

I discussed this issue in another post: CORS POST request fails on Chrome, Safari and Firefox
I´m still unable to perform CORS requests, this is now I major issue and I suspect the problem is in LoginFilter:

```<code>    public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

        private TokenAuthenticationService tokenAuthenticationService;

        public JWTLoginFilter(String url, AuthenticationManager

authenticationManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authenticationManager);
        tokenAuthenticationService = new TokenAuthenticationService();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException, ServletException {

        try {
            ServletInputStream inputStream = httpServletRequest.getInputStream();
            httpServletRequest.getCharacterEncoding();
            AccountCredentials credentials = null;
            ObjectMapper mapper = new ObjectMapper();

            credentials = mapper.readValue(inputStream, AccountCredentials.class);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
            return getAuthenticationManager().authenticate(token);
        } catch (JsonMappingException e) {
            e.printStackTrace();
            throw e;
        } catch (JsonParseException e) {
            e.printStackTrace();
            throw e;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
            throws IOException, ServletException {
        AccountCredentials cred = (AccountCredentials) authentication.getPrincipal();
        tokenAuthenticationService.addAuthentication(response, cred);
    }

}
</code>```

EDIT
the exact error on Google Chrome is:

```<code>:8000/#!/login:1 XMLHttpRequest cannot load http://localhost:8080/myApp/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 403.
</code>```

答:
The preflight request is sent AUTOMATICALLY with verb option by browser itself BEFORE the real request is sent.
You must configure your server to send response with some headers when this preflight request is sent. With spring security you can use :

```<code>@Provider
@Component
public class CrossDomainContainerResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext containerRequestContext,
            ContainerResponseContext containerResponseContext) throws IOException {

        containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "YOUR FRONTEND URI");

        containerResponseContext.getHeaders().add("Access-Control-Allow-Headers",
                    "Access-Control-Allow-Origin");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}
</code>```

If you are using XML config, you can also use the <cors /> tag.

The --disable-web-security never worked for me on Chrome. But it worked on Vivaldi Browser.

Body:
I´m struggling with CORS requests on an Springsecurity backen project + Angulajs frontend.
CORS requests are working fine on IE (also with curl, wget and python requests) but miserably fail on Chrome and Safary because of Preflight bad request.
I know that those Browsers are blocking CORS POSTs, making the request empty as soon as the reach the backend, in fact I don’t see any data when I log out the request from backend. I tried every possible combination of:

Frontend side:

1)  $http(method: POST)

2)  $http.post(

3)  Adding flags: Access-Control-Allow-Origin, Access-Control-Expose, etc.

4)  Adding all possible header combination: ‘Content–Type’:’application/

Browser side:

1)  Start chrome with flag: --disable-web-security

2)  Installing Chrome extension CORS

Backend side:

1)  Spring Security Disable csfr

2)  Spring Security Permit all

3)  Spring Security HttpMethod.OPTION

4)  Set up a CORS Filter that accept all origins: “*”

5)  Activated CORS framework for spring extending WebMvcConfigurerAdapter class.

Nothing, NHOTING worked for me!

I discussed this issue in another post: CORS POST request fails on Chrome, Safari and Firefox
I´m still unable to perform CORS requests, this is now I major issue and I suspect the problem is in LoginFilter:

    public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {

        private TokenAuthenticationService tokenAuthenticationService;

        public JWTLoginFilter(String url, AuthenticationManager

authenticationManager) {
        super(new AntPathRequestMatcher(url));
        setAuthenticationManager(authenticationManager);
        tokenAuthenticationService = new TokenAuthenticationService();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws AuthenticationException, IOException, ServletException {

        try {
            ServletInputStream inputStream = httpServletRequest.getInputStream();
            httpServletRequest.getCharacterEncoding();
            AccountCredentials credentials = null;
            ObjectMapper mapper = new ObjectMapper();

            credentials = mapper.readValue(inputStream, AccountCredentials.class);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
            return getAuthenticationManager().authenticate(token);
        } catch (JsonMappingException e) {
            e.printStackTrace();
            throw e;
        } catch (JsonParseException e) {
            e.printStackTrace();
            throw e;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
            throws IOException, ServletException {
        AccountCredentials cred = (AccountCredentials) authentication.getPrincipal();
        tokenAuthenticationService.addAuthentication(response, cred);
    }

}

EDIT
the exact error on Google Chrome is:

:8000/#!/login:1 XMLHttpRequest cannot load http://localhost:8080/myApp/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 403.

Body:
The preflight request is sent AUTOMATICALLY with verb option by browser itself BEFORE the real request is sent.
You must configure your server to send response with some headers when this preflight request is sent. With spring security you can use :

@Provider
@Component
public class CrossDomainContainerResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext containerRequestContext,
            ContainerResponseContext containerResponseContext) throws IOException {

        containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "YOUR FRONTEND URI");

        containerResponseContext.getHeaders().add("Access-Control-Allow-Headers",
                    "Access-Control-Allow-Origin");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        containerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

If you are using XML config, you can also use the <cors /> tag.

The --disable-web-security never worked for me on Chrome. But it worked on Vivaldi Browser.


问:
filling javascript object "on the fly"
HI, i have an object: var myobject = new Object;
and i want to dynamically fill it with properties while looping through jquery input collection in that manner:

```<code>$('.test').each(function(){
    myobject.$(this).attr('name') = $(this).val();
});
</code>```

what i'm doing wrong here?
thanks in advance

答:
Try this:

```<code>$('.test').each(function () {
    var e = $(this);
    myobject[e.attr('name')] = e.val();
});
</code>```

Objects in JavaScript can be accessed using object.property or object['property'] (these two are equivalent). The latter allows you to use expressions (like variables): object[propertyName].

Title: filling javascript object "on the fly"

Body:
HI, i have an object: var myobject = new Object;
and i want to dynamically fill it with properties while looping through jquery input collection in that manner:

$('.test').each(function(){
    myobject.$(this).attr('name') = $(this).val();
});

what i'm doing wrong here?
thanks in advance

Body:
Try this:

$('.test').each(function () {
    var e = $(this);
    myobject[e.attr('name')] = e.val();
});

Objects in JavaScript can be accessed using object.property or object['property'] (these two are equivalent). The latter allows you to use expressions (like variables): object[propertyName].


问:
Linq select from database table where matching property from List
I have a List with records of following class which is something like this

```<code>  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }
</code>```

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

```<code>  var result=from p in _context.Details
</code>```

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

```<code> List<TestRecord> records -- this has let's say 100 records.
</code>```

Doing simply this does not work as linq can't join with generic List

```<code>    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId
</code>```

Any solutions for this using Linq?

答:
You can use Any like this:

```<code>var finalresult = context.details.Where(d => records.Any(r=>r.recordId == d.recordId));
</code>```

Body:
I have a List with records of following class which is something like this

  public class TestRecord
  {
     public int RecordsId{get;set;}
public string Name{get;set;}
-- and more such properties.

  }

Now I have database table which I access from linq which contains RecordId column , values which will match RecordId value from above List.

  var result=from p in _context.Details

however I am thinking I could do where/ contains on this linq query and provide it with a clause to match RecordId from a list

 List<TestRecord> records -- this has let's say 100 records.

Doing simply this does not work as linq can't join with generic List

    var finalresult = from p in context.details
                      join a in records on p.recordId equals a.recordId

Any solutions for this using Linq?

Body:
You can use Any like this:

var finalresult = context.details.Where(d => records.Any(r=>r.recordId == d.recordId));


答:
The boxes height is not equal, try something like this:</p>

```<code>.carContainer .mix {
  min-height: 400px;
}
</code>```

Title: CSS displaying one box incorrectly

Body:
The boxes height is not equal, try something like this:

.carContainer .mix {
  min-height: 400px;
}


问:
Genetic Algorithm: Creating Offspring of Two HashMaps
I need to do create offspring from two arrays, if possible with HashMaps.

Here is my reproduce function:

```<code>public Map<String, Integer> reproduce(Map<String, Integer> x, Map<String, Integer> y, int n){
Random rand = new Random();
int c = rand.nextInt(n);
!!CREATE OFFSPRING from x and y and store it into child!!
return(child);
}
</code>```

For example if the x and y values passed to the function are:

```<code>x = {0=1} {1=0} {2=1}
</code>```

and

```<code>y = {0=2} {1=1} {2=2}
</code>```

I would like to reproduce using these Maps to create a child map like for example:

```<code>child = {0=1} {1=1} {2=2}
</code>```

The child has taken the first tuple from x, and the 2nd and 3rd tuples from y.

The point where it switches from x to y is determined by the random number c.

How can I do this without converting the maps to arrays?

答:
Strictly speaking, the Map interface in java does not have a method for sequential access.
So you can't take "x first elements" from a map - there's no order between them.
Some implementations do have guaranteed ordering - SortedMap (sorted by keys) and LinkedHashMap (sorted by order of insertion).

In these cases, you can use the entryMap() method.

So (assuming n is the size of both maps) if you want to take x element from the first and y elements from the second you could create two iterators and take from them, something like:

```<code>int c = rand.nextInt(n);
Iterator<Entry<String, Integer>> i1 = x.entrySet().iterator();
Iterator<Entry<String, Integer>> i2 = y.entrySet().iterator();
int i = 0;
Map<Integer, String> child = new HashMap<String, Integer>();
Entry<String, Integer> e1, e2;
while (i < n)
{
   if (i < c) {
     e1= i1.next();
     e2 = i2.next();
     child.add(e1.getKey(), e1.getValue());
   }
   else
   {
     e2 = i2.next();
     child.add(e2.getKey(), e2.getValue());
   }
   i++;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to do create offspring from two arrays, if possible with HashMaps.

Here is my reproduce function:

public Map<String, Integer> reproduce(Map<String, Integer> x, Map<String, Integer> y, int n){
Random rand = new Random();
int c = rand.nextInt(n);
!!CREATE OFFSPRING from x and y and store it into child!!
return(child);
}

For example if the x and y values passed to the function are:

x = {0=1} {1=0} {2=1}

and

y = {0=2} {1=1} {2=2}

I would like to reproduce using these Maps to create a child map like for example:

child = {0=1} {1=1} {2=2}

The child has taken the first tuple from x, and the 2nd and 3rd tuples from y.

The point where it switches from x to y is determined by the random number c.

How can I do this without converting the maps to arrays?

Body:
Strictly speaking, the Map interface in java does not have a method for sequential access.
So you can't take "x first elements" from a map - there's no order between them.
Some implementations do have guaranteed ordering - SortedMap (sorted by keys) and LinkedHashMap (sorted by order of insertion).

In these cases, you can use the entryMap() method.

So (assuming n is the size of both maps) if you want to take x element from the first and y elements from the second you could create two iterators and take from them, something like:

int c = rand.nextInt(n);
Iterator<Entry<String, Integer>> i1 = x.entrySet().iterator();
Iterator<Entry<String, Integer>> i2 = y.entrySet().iterator();
int i = 0;
Map<Integer, String> child = new HashMap<String, Integer>();
Entry<String, Integer> e1, e2;
while (i < n)
{
   if (i < c) {
     e1= i1.next();
     e2 = i2.next();
     child.add(e1.getKey(), e1.getValue());
   }
   else
   {
     e2 = i2.next();
     child.add(e2.getKey(), e2.getValue());
   }
   i++;
}


问:
How to copy and paste text in MongoDB shell
How to copy and paste text in MongoDB shell?

I tried Ctrl+C and Ctrl+V but it didn't work.

Thanks, Michael.

答:
For Windows:

Copy: Right-click anywhere in the command prompt window, then click Mark. Click the beginning of the text you want to copy. Press and hold down the SHIFT key, and then click the end of the text you want to copy (or you can click and drag the cursor to select the text). Either right-click the title bar, point to Edit, and then click Copy OR press Enter.

Paste: Position the cursor where you want the text to be inserted: Right-click and then click Paste.


问:
No enums generated by jax-ws ri 2.2.1 for amazon ecs wsdl file
I'm attempting to generate artifacts for the following amazon wsdl:

http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

using the following ant task:

```<code><taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
    <classpath>
        <pathelement location="${BUILD_LIBS}/jaxws-ri/lib/jaxws-tools.jar"/>
    </classpath>
</taskdef>

<target name="wsimport" depends="init">
    <delete dir="${generated.src}" />
    <mkdir dir="${generated.src}"/>
    <wsimport
        debug="true"
    keep="true"
    verbose="true"
    destdir="${generated.src}"
    package="com.amazon.webservices.ecs"
    wsdl="wsdl/AWSECommerceService.wsdl"/>
</target>
</code>```

but no java artifacts are generated for the following element which look like this:

```<code><xs:element name="Condition">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:enumeration value="All"/>
            <xs:enumeration value="New"/>
            <xs:enumeration value="Used"/>
            <xs:enumeration value="Collectible"/>
            <xs:enumeration value="Refurbished"/>
       </xs:restriction>
   </xs:simpleType>
</xs:element>
</code>```

Basically no enums are generated even though all other elements are generated. Has anyone seen this problem before? I'm using jax-ws ri 2.2.1 http://jax-ws.java.net/2.2.1/

Thanks

答:
Use typesafeEnumMember in JAXB-Binding

Ref: http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html#wp148439

Or

Something like this[ added name="ConditionType" ]:

```<code><xs:simpleType name="ConditionType">
            <xs:restriction base="xs:string">
                <xs:enumeration value="All"/>
                <xs:enumeration value="New"/>
                <xs:enumeration value="Used"/>
                <xs:enumeration value="Collectible"/>
                <xs:enumeration value="Refurbished"/>
            </xs:restriction>
        </xs:simpleType>
</code>```

Body:
I'm attempting to generate artifacts for the following amazon wsdl:

http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

using the following ant task:

<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
    <classpath>
        <pathelement location="${BUILD_LIBS}/jaxws-ri/lib/jaxws-tools.jar"/>
    </classpath>
</taskdef>

<target name="wsimport" depends="init">
    <delete dir="${generated.src}" />
    <mkdir dir="${generated.src}"/>
    <wsimport
        debug="true"
    keep="true"
    verbose="true"
    destdir="${generated.src}"
    package="com.amazon.webservices.ecs"
    wsdl="wsdl/AWSECommerceService.wsdl"/>
</target>

but no java artifacts are generated for the following element which look like this:

<xs:element name="Condition">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:enumeration value="All"/>
            <xs:enumeration value="New"/>
            <xs:enumeration value="Used"/>
            <xs:enumeration value="Collectible"/>
            <xs:enumeration value="Refurbished"/>
       </xs:restriction>
   </xs:simpleType>
</xs:element>

Basically no enums are generated even though all other elements are generated. Has anyone seen this problem before? I'm using jax-ws ri 2.2.1 http://jax-ws.java.net/2.2.1/

Thanks

Body:
Use typesafeEnumMember in JAXB-Binding

Ref: http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBUsing4.html#wp148439

Or

Something like this[ added name="ConditionType" ]:

<xs:simpleType name="ConditionType">
            <xs:restriction base="xs:string">
                <xs:enumeration value="All"/>
                <xs:enumeration value="New"/>
                <xs:enumeration value="Used"/>
                <xs:enumeration value="Collectible"/>
                <xs:enumeration value="Refurbished"/>
            </xs:restriction>
        </xs:simpleType>


问:
When is it ever appropriate to place Javascript inside the body of a document?
The client has a bunch of Javascript that calls Microsoft Ajax etc. Aside from web page analytics which make sense to load at the same time static resources are loaded, wouldn't it make sense to load any AJAX scripts in the head instead of the body?

Ultimately the result is a bloated load time for the page since all the Javascript is being loaded at time of render.

What is your ideal placement of certain Javascript in a web page?

答:
you can place javascript anywhere you like.

you usually wanna put external JS in the header section.

Other than that. you can put them anywhere.


问:
Using chrome.tabs.executeScript to execute an async function
I have a function I want to execute in the page using chrome.tabs.executeScript, running from a browser action popup. The permissions are set up correctly and it works fine with a synchronous callback:

```<code>chrome.tabs.executeScript(
    tab.id,
    { code: `(function() {
        // Do lots of things
        return true;
    })()` },
    r => console.log(r[0])); // Logs true
</code>```

The problem is that the function I want to call goes through several callbacks, so I want to use async and await:

```<code>chrome.tabs.executeScript(
    tab.id,
    { code: `(async function() {
        // Do lots of things with await
        return true;
    })()` },
    async r => {
        console.log(r); // Logs array with single value [Object]
        console.log(await r[0]); // Logs empty Object {}
    });
</code>```

The problem is that the callback result r. It should be an array of script results, so I expect r[0] to be a promise that resolves when the script finishes.

Promise syntax (using .then()) doesn't work either.

If I execute the exact same function in the page it returns a promise as expected and can be awaited.

Any idea what I'm doing wrong and is there any way around it?

答:
The problem is that events and native objects are not directly available between the page and the extension. Essentially you get a serialised copy, something like you will if you do JSON.parse(JSON.stringify(obj)).

This means some native objects (for instance new Error or new Promise) will be emptied (become {}), events are lost and no implementation of promise can work across the boundary.

The solution is to use chrome.runtime.sendMessage to return the message in the script, and chrome.runtime.onMessage.addListener in popup.js to listen for it:

```<code>chrome.tabs.executeScript(
    tab.id,
    { code: `(async function() {
        // Do lots of things with await
        let result = true;
        chrome.runtime.sendMessage(result, function (response) {
            console.log(response); // Logs 'true'
        });
    })()` },
    async emptyPromise => {

        // Create a promise that resolves when chrome.runtime.onMessage fires
        const message = new Promise(resolve => {
            const listener = request => {
                chrome.runtime.onMessage.removeListener(listener);
                resolve(request);
            };
            chrome.runtime.onMessage.addListener(listener);
        });

        const result = await message;
        console.log(result); // Logs true
    });
</code>```

I've extended this into a function chrome.tabs.executeAsyncFunction (as part of chrome-extension-async, which 'promisifies' the whole API):

```<code>function setupDetails(action, id) {
    // Wrap the async function in an await and a runtime.sendMessage with the result
    // This should always call runtime.sendMessage, even if an error is thrown
    const wrapAsyncSendMessage = action =>
        `(async function () {
    const result = { asyncFuncID: '${id}' };
    try {
        result.content = await (${action})();
    }
    catch(x) {
        // Make an explicit copy of the Error properties
        result.error = {
            message: x.message,
            arguments: x.arguments,
            type: x.type,
            name: x.name,
            stack: x.stack
        };
    }
    finally {
        // Always call sendMessage, as without it this might loop forever
        chrome.runtime.sendMessage(result);
    }
})()`;

    // Apply this wrapper to the code passed
    let execArgs = {};
    if (typeof action === 'function' || typeof action === 'string')
        // Passed a function or string, wrap it directly
        execArgs.code = wrapAsyncSendMessage(action);
    else if (action.code) {
        // Passed details object https://developer.chrome.com/extensions/tabs#method-executeScript
        execArgs = action;
        execArgs.code = wrapAsyncSendMessage(action.code);
    }
    else if (action.file)
        throw new Error(`Cannot execute ${action.file}. File based execute scripts are not supported.`);
    else
        throw new Error(`Cannot execute ${JSON.stringify(action)}, it must be a function, string, or have a code property.`);

    return execArgs;
}

function promisifyRuntimeMessage(id) {
    // We don't have a reject because the finally in the script wrapper should ensure this always gets called.
    return new Promise(resolve => {
        const listener = request => {
            // Check that the message sent is intended for this listener
            if (request && request.asyncFuncID === id) {

                // Remove this listener
                chrome.runtime.onMessage.removeListener(listener);
                resolve(request);
            }

            // Return false as we don't want to keep this channel open https://developer.chrome.com/extensions/runtime#event-onMessage
            return false;
        };

        chrome.runtime.onMessage.addListener(listener);
    });
}

chrome.tabs.executeAsyncFunction = async function (tab, action) {

    // Generate a random 4-char key to avoid clashes if called multiple times
    const id = Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);

    const details = setupDetails(action, id);
    const message = promisifyRuntimeMessage(id);

    // This will return a serialised promise, which will be broken
    await chrome.tabs.executeScript(tab, details);

    // Wait until we have the result message
    const { content, error } = await message;

    if (error)
        throw new Error(`Error thrown in execution script: ${error.message}.
Stack: ${error.stack}`)

    return content;
}
</code>```

This executeAsyncFunction can then be called like this:

```<code>const result = await chrome.tabs.executeAsyncFunction(
    tab.id,
    // Async function to execute in the page
    async function() {
        // Do lots of things with await
        return true;
    });
</code>```

This wraps the chrome.tabs.executeScript and chrome.runtime.onMessage.addListener, and wraps the script in a try-finally before calling chrome.runtime.sendMessage to resolve the promise.

Body:
I have a function I want to execute in the page using chrome.tabs.executeScript, running from a browser action popup. The permissions are set up correctly and it works fine with a synchronous callback:

chrome.tabs.executeScript(
    tab.id,
    { code: `(function() {
        // Do lots of things
        return true;
    })()` },
    r => console.log(r[0])); // Logs true

The problem is that the function I want to call goes through several callbacks, so I want to use async and await:

chrome.tabs.executeScript(
    tab.id,
    { code: `(async function() {
        // Do lots of things with await
        return true;
    })()` },
    async r => {
        console.log(r); // Logs array with single value [Object]
        console.log(await r[0]); // Logs empty Object {}
    });

The problem is that the callback result r. It should be an array of script results, so I expect r[0] to be a promise that resolves when the script finishes.

Promise syntax (using .then()) doesn't work either.

If I execute the exact same function in the page it returns a promise as expected and can be awaited.

Any idea what I'm doing wrong and is there any way around it?

Body:
The problem is that events and native objects are not directly available between the page and the extension. Essentially you get a serialised copy, something like you will if you do JSON.parse(JSON.stringify(obj)).

This means some native objects (for instance new Error or new Promise) will be emptied (become {}), events are lost and no implementation of promise can work across the boundary.

The solution is to use chrome.runtime.sendMessage to return the message in the script, and chrome.runtime.onMessage.addListener in popup.js to listen for it:

chrome.tabs.executeScript(
    tab.id,
    { code: `(async function() {
        // Do lots of things with await
        let result = true;
        chrome.runtime.sendMessage(result, function (response) {
            console.log(response); // Logs 'true'
        });
    })()` },
    async emptyPromise => {

        // Create a promise that resolves when chrome.runtime.onMessage fires
        const message = new Promise(resolve => {
            const listener = request => {
                chrome.runtime.onMessage.removeListener(listener);
                resolve(request);
            };
            chrome.runtime.onMessage.addListener(listener);
        });

        const result = await message;
        console.log(result); // Logs true
    });

I've extended this into a function chrome.tabs.executeAsyncFunction (as part of chrome-extension-async, which 'promisifies' the whole API):

function setupDetails(action, id) {
    // Wrap the async function in an await and a runtime.sendMessage with the result
    // This should always call runtime.sendMessage, even if an error is thrown
    const wrapAsyncSendMessage = action =>
        `(async function () {
    const result = { asyncFuncID: '${id}' };
    try {
        result.content = await (${action})();
    }
    catch(x) {
        // Make an explicit copy of the Error properties
        result.error = {
            message: x.message,
            arguments: x.arguments,
            type: x.type,
            name: x.name,
            stack: x.stack
        };
    }
    finally {
        // Always call sendMessage, as without it this might loop forever
        chrome.runtime.sendMessage(result);
    }
})()`;

    // Apply this wrapper to the code passed
    let execArgs = {};
    if (typeof action === 'function' || typeof action === 'string')
        // Passed a function or string, wrap it directly
        execArgs.code = wrapAsyncSendMessage(action);
    else if (action.code) {
        // Passed details object https://developer.chrome.com/extensions/tabs#method-executeScript
        execArgs = action;
        execArgs.code = wrapAsyncSendMessage(action.code);
    }
    else if (action.file)
        throw new Error(`Cannot execute ${action.file}. File based execute scripts are not supported.`);
    else
        throw new Error(`Cannot execute ${JSON.stringify(action)}, it must be a function, string, or have a code property.`);

    return execArgs;
}

function promisifyRuntimeMessage(id) {
    // We don't have a reject because the finally in the script wrapper should ensure this always gets called.
    return new Promise(resolve => {
        const listener = request => {
            // Check that the message sent is intended for this listener
            if (request && request.asyncFuncID === id) {

                // Remove this listener
                chrome.runtime.onMessage.removeListener(listener);
                resolve(request);
            }

            // Return false as we don't want to keep this channel open https://developer.chrome.com/extensions/runtime#event-onMessage
            return false;
        };

        chrome.runtime.onMessage.addListener(listener);
    });
}

chrome.tabs.executeAsyncFunction = async function (tab, action) {

    // Generate a random 4-char key to avoid clashes if called multiple times
    const id = Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);

    const details = setupDetails(action, id);
    const message = promisifyRuntimeMessage(id);

    // This will return a serialised promise, which will be broken
    await chrome.tabs.executeScript(tab, details);

    // Wait until we have the result message
    const { content, error } = await message;

    if (error)
        throw new Error(`Error thrown in execution script: ${error.message}.
Stack: ${error.stack}`)

    return content;
}

This executeAsyncFunction can then be called like this:

const result = await chrome.tabs.executeAsyncFunction(
    tab.id,
    // Async function to execute in the page
    async function() {
        // Do lots of things with await
        return true;
    });

This wraps the chrome.tabs.executeScript and chrome.runtime.onMessage.addListener, and wraps the script in a try-finally before calling chrome.runtime.sendMessage to resolve the promise.


问:
fit controls to screen vba
i'm trying to fit the user form to screen on diifernet screens.

the userform was first managed in my work screen and i fit it to my screen but  when i'm trying the userform on other screens part of it vanished.

i can't put the whole code in here but i will put just the sub that suppose to fit to screen:

```<code>Private Sub UserForm_Initialize()
Dim w As Long, h As Long
Application.Visible = False

With Me
        rMaxHeight = Application.Height
        rMaxWidth = Application.Width
        If .Height > Application.Height - 10 Then
        rNormalHeight = rMaxHeight * 0.85
        Else
        rNormalHeight = Me.Height
        End If
        If .Width > Application.Width - 10 Then
        rNormalWidth = rMaxWidth * 0.85
        Else
        rNormalWidth = Me.Width
        End If

        .StartUpPosition = 1
        .Left = 0
        .Top = 0
         FitSize
...

Private Sub FitSize()
Dim h, w
Dim c As Control
Dim PHeight, PWidth As Double

PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width
h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub

    For Each c In Me.Controls
        If c.Visible Then
            If c.Top + c.Height > h Then h = (c.Top + c.Height) ' * PHeight

            If c.Left + c.Width > w Then w = (c.Left + c.Width) ' * PWidth

            If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then   c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
        End If
    Next c

    If h > 0 And w > 0 Then
        With Me
            .Width = w + 40
            .Height = h + 40
        End With
    End If
End Sub
</code>```

hope you could help me with that

Thank you all
sefi

答:
Hello and thank for everyone that tried to help me.
I found the solution to this problem by fitting the controls to the proportion of the screen copared with the original form.

At first step you need to calculate the proportion:

```<code>Dim PHeight, PWidth As Double
'define form size compared with the original size of the form
rMaxHeight = Application.Height
rMaxWidth = Application.Width
If Me.Height > Application.Height Then
rNormalHeight = rMaxHeight * 0.85
Else
rNormalHeight = Me.Height
End If
If Me.Width > Application.Width Then
rNormalWidth = rMaxWidth * 0.85
Else
rNormalWidth = Me.Width
End If
 'normal is the size needed in normal mode before the form get to maximize mode
 'we want to calculate the needed divided to the orignal
PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width
</code>```

now we call fitsize()

```<code>Private Sub FitSize()
Dim h, w
Dim c As Control

h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub ' if the it is the original size of the form- don't bother...

'loop on the form controls
For Each c In Me.Controls
   If c.Visible Then                                     ' just visible controls
      c.Top = c.Top * PHeight                            ' fit to proportion of the screen compared with the original form
      c.Height = c.Height * PHeight
      If c.Top + c.Height > h Then h = c.Top + c.Height  ' collect the height needed from the controls

      c.Left = c.Left * PWidth                           ' fit to proportion of the screen compared with the original form
      c.Width = c.Width * PWidth
      If c.Left + c.Width > w Then w = c.Left + c.Width  ' collect the height needed from the controls

      'fit the font for the text controls
      If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
      End If
Next c

'define the size needed form the specific screen
If h > 0 And w > 0 Then
    With Me
      .Width = w + 40
      .Height = h + 40
      .StartUpPosition = 0
      .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
      .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
     End With
End If

End Sub
</code>```

this code will define the size needed in each screen by the proportion that calculated in the needed value divded to the original value.

Try it and tell me if it works.

thank you all
sefi

Title: fit controls to screen vba

Body:
i'm trying to fit the user form to screen on diifernet screens.

the userform was first managed in my work screen and i fit it to my screen but  when i'm trying the userform on other screens part of it vanished.

i can't put the whole code in here but i will put just the sub that suppose to fit to screen:

Private Sub UserForm_Initialize()
Dim w As Long, h As Long
Application.Visible = False

With Me
        rMaxHeight = Application.Height
        rMaxWidth = Application.Width
        If .Height > Application.Height - 10 Then
        rNormalHeight = rMaxHeight * 0.85
        Else
        rNormalHeight = Me.Height
        End If
        If .Width > Application.Width - 10 Then
        rNormalWidth = rMaxWidth * 0.85
        Else
        rNormalWidth = Me.Width
        End If

        .StartUpPosition = 1
        .Left = 0
        .Top = 0
         FitSize
...

Private Sub FitSize()
Dim h, w
Dim c As Control
Dim PHeight, PWidth As Double

PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width
h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub

    For Each c In Me.Controls
        If c.Visible Then
            If c.Top + c.Height > h Then h = (c.Top + c.Height) ' * PHeight

            If c.Left + c.Width > w Then w = (c.Left + c.Width) ' * PWidth

            If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then   c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
        End If
    Next c

    If h > 0 And w > 0 Then
        With Me
            .Width = w + 40
            .Height = h + 40
        End With
    End If
End Sub

hope you could help me with that

Thank you all
sefi

Body:
Hello and thank for everyone that tried to help me.
I found the solution to this problem by fitting the controls to the proportion of the screen copared with the original form.

At first step you need to calculate the proportion:

Dim PHeight, PWidth As Double
'define form size compared with the original size of the form
rMaxHeight = Application.Height
rMaxWidth = Application.Width
If Me.Height > Application.Height Then
rNormalHeight = rMaxHeight * 0.85
Else
rNormalHeight = Me.Height
End If
If Me.Width > Application.Width Then
rNormalWidth = rMaxWidth * 0.85
Else
rNormalWidth = Me.Width
End If
 'normal is the size needed in normal mode before the form get to maximize mode
 'we want to calculate the needed divided to the orignal
PHeight = rNormalHeight / Me.Height
PWidth = rNormalWidth / Me.Width

now we call fitsize()

Private Sub FitSize()
Dim h, w
Dim c As Control

h = 0: w = 0

If PHeight = 1 And PWidth = 1 Then Exit Sub ' if the it is the original size of the form- don't bother...

'loop on the form controls
For Each c In Me.Controls
   If c.Visible Then                                     ' just visible controls
      c.Top = c.Top * PHeight                            ' fit to proportion of the screen compared with the original form
      c.Height = c.Height * PHeight
      If c.Top + c.Height > h Then h = c.Top + c.Height  ' collect the height needed from the controls

      c.Left = c.Left * PWidth                           ' fit to proportion of the screen compared with the original form
      c.Width = c.Width * PWidth
      If c.Left + c.Width > w Then w = c.Left + c.Width  ' collect the height needed from the controls

      'fit the font for the text controls
      If Not TypeName(c) = "Image" Or TypeName(c) = "ListBox" Then c.FontSize = c.FontSize * ((PHeight + PWidth) / 2)
      End If
Next c

'define the size needed form the specific screen
If h > 0 And w > 0 Then
    With Me
      .Width = w + 40
      .Height = h + 40
      .StartUpPosition = 0
      .Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
      .Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
     End With
End If

End Sub

this code will define the size needed in each screen by the proportion that calculated in the needed value divded to the original value.

Try it and tell me if it works.

thank you all
sefi


问:
How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?
I'm currently trying out Genymotion and boy, it's so much faster than the ADT emulator.

But I need to install Google Play to download some apps into it. How do I do this?

答:
Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not
  included by default in Genymotion virtual devices. However, if you
  really need them, you can use the packages provided by OpenGapps.
  Simply follow these steps:

Visit opengapps.org

Select x86 as platform

Choose the Android version corresponding to your virtual device

Select nano as variant

Download the zip file

Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)

Follow the pop-up instructions

    Please note Genymobile Inc. and Genymotion assume no liability
    whatsoever resulting from the download, install and use of Google Play
    Services within your virtual devices. You are solely responsible for
    the use and assume all liability related thereto. Moreover, we
    disclaim any warranties of any kind for a particular purpose regarding
    the compatibility of the OpenGapps packages with any version of
    Genymotion.


问:
Matching multiple objects using IValueProvider.GetValue
I have following piece of code:

```<code>var ids = bindingContext
            .ValueProvider
            .GetValue("Factors.Item1")
            .AttemptedValue;
</code>```

the get value's argument might be either "Factors.Item1" or "Factors.Item_Check". I wonder if there's a way for checking both cases in one line, for example something like this:

```<code>var ids = bindingContext
            .ValueProvider
            .GetValue("Factors.Item1" | "Factors.Item_Check")
            .AttemptedValue;
</code>```

答:
No, there is not. The interface doesn't contain a method to retrieve multiple values, and a binary OR isn't going to help either.

The best I could come up with is this:

```<code>var ids = new[] { "Factors.Item1", "Factors.Item_Check"}
            .Select( v => bindingContext
                          .ValueProvider
                          .GetValue(v)
                          .AttemptedValue
                  )
            .ToArray(); // materialize if you need to
</code>```

Body:
I have following piece of code:

var ids = bindingContext
            .ValueProvider
            .GetValue("Factors.Item1")
            .AttemptedValue;

the get value's argument might be either "Factors.Item1" or "Factors.Item_Check". I wonder if there's a way for checking both cases in one line, for example something like this:

var ids = bindingContext
            .ValueProvider
            .GetValue("Factors.Item1" | "Factors.Item_Check")
            .AttemptedValue;

Body:
No, there is not. The interface doesn't contain a method to retrieve multiple values, and a binary OR isn't going to help either.

The best I could come up with is this:

var ids = new[] { "Factors.Item1", "Factors.Item_Check"}
            .Select( v => bindingContext
                          .ValueProvider
                          .GetValue(v)
                          .AttemptedValue
                  )
            .ToArray(); // materialize if you need to


答:
With the way you are doing it:</p>

```<code>var myObject = {};
$('.test').each(
    function(){
        var elem = $(this);
        myObject[elem.attr('name')] = elem.val();
    }
);
</code>```

Title: filling javascript object "on the fly"

Body:
With the way you are doing it:

var myObject = {};
$('.test').each(
    function(){
        var elem = $(this);
        myObject[elem.attr('name')] = elem.val();
    }
);


问:
How to handle data for large number of pins on mapview?
I am developing an App that shows a map with annotations. The annotations are in thousands and growing. There are data associated with the annotation pins. I get the data from web service. Should I download all the data for all the pins upfront? That obviously is bad. But how should I do it in an efficient way that when the user zooms in and out the map, there is no lag.

Thanks in advance!

答: Show pins according particular region zoom, instead of showing all pins at one time.    </p>


问:
Compare 2 strings in Java upto a delimiter
String 1:

```<code>func1(test1)
</code>```

String 2:

```<code>func1(test2)
</code>```

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

答:
String#substring() method will help on this case this combined with String#indexOf() method

```<code>String x1 = "func1(test1)";
String x2 = "func1(test1)";
String methName1 = x1.substring(0, x1.indexOf("("));
String methName2 = x2.substring(0, x2.indexOf("("));
System.out.println(methName1);
System.out.println(methName2);
System.out.println(methName1.equals(methName2));
</code>```

Body:
String 1:

func1(test1)

String 2:

func1(test2)

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

Body:
String#substring() method will help on this case this combined with String#indexOf() method

String x1 = "func1(test1)";
String x2 = "func1(test1)";
String methName1 = x1.substring(0, x1.indexOf("("));
String methName2 = x2.substring(0, x2.indexOf("("));
System.out.println(methName1);
System.out.println(methName2);
System.out.println(methName1.equals(methName2));


问:
Collect directory updates into one email
I currently have a python script that notifies me of changes to a directory via email. However, because I am notified of updates to OneNote documents (which autosave once a change is made) I am sent multiple emails when a document is edited.

I want all updates that happen in a 10 minute period to be sent to me in one email, but I don't know how to do this.

Here is my code:

```<code>    import os
import win32file
import win32con
import win32com.client

o   = win32com.client.Dispatch("Outlook.Application")

ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}

FILE_LIST_DIRECTORY = 0x0001

path_to_watch =r"\\FILE-LUX12-03\lux12_Translation\Translation\jllevent\QA_threads"
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)
while 1:

  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    True,
    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
     win32con.FILE_NOTIFY_CHANGE_SIZE |
     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
     win32con.FILE_NOTIFY_CHANGE_SECURITY,
    None,
    None
  )
  for action, file in results:
      if file.endswith(".one"):
          if action in (1, 2, 3):
              full_filename = os.path.join (path_to_watch, file)
              Msg = o.CreateItem(0)
              Msg.To = "emailaddress"
              Msg.Subject = "NOTIFICATION OF UPDATE"
              newbodyvariable = str(full_filename) + " has been " + str(ACTIONS.get (action, "Unknown"))
              Msg.Body = newbodyvariable
              Msg.Send()
</code>```

答:
Can't you just check every 10 minutes and then send aggregated data via email?</p>

```<code>import time
while 1:
      time.sleep(60 * 10)
      results = win32file.ReadDirectoryChangesW (
        hDir,
        1024,
        True,
        win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
         win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
         win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
         win32con.FILE_NOTIFY_CHANGE_SIZE |
         win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
         win32con.FILE_NOTIFY_CHANGE_SECURITY,
        None,
        None
      )
      all_changes = []
      for action, file in results:
          if file.endswith(".one"):
              if action in (1, 2, 3):
                  full_filename = os.path.join (path_to_watch, file)
                  all_changes.append((full_filename, ACTIONS.get (action, "Unknown")))
      if all_changes:
          Msg = o.CreateItem(0)
          Msg.To = "emailaddress"
          Msg.Subject = "NOTIFICATION OF UPDATE"
          newbodyvariable = "; ".join("{full_filename} has been {action}".format(full_filename, action) for full_filename, action in all_changes)
          Msg.Body = newbodyvariable
          Msg.Send()
</code>```

Body:
I currently have a python script that notifies me of changes to a directory via email. However, because I am notified of updates to OneNote documents (which autosave once a change is made) I am sent multiple emails when a document is edited.

I want all updates that happen in a 10 minute period to be sent to me in one email, but I don't know how to do this.

Here is my code:

    import os
import win32file
import win32con
import win32com.client

o   = win32com.client.Dispatch("Outlook.Application")

ACTIONS = {
  1 : "Created",
  2 : "Deleted",
  3 : "Updated",
  4 : "Renamed from something",
  5 : "Renamed to something"
}

FILE_LIST_DIRECTORY = 0x0001

path_to_watch =r"\\FILE-LUX12-03\lux12_Translation\Translation\jllevent\QA_threads"
hDir = win32file.CreateFile (
  path_to_watch,
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS,
  None
)
while 1:

  results = win32file.ReadDirectoryChangesW (
    hDir,
    1024,
    True,
    win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
     win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
     win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
     win32con.FILE_NOTIFY_CHANGE_SIZE |
     win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
     win32con.FILE_NOTIFY_CHANGE_SECURITY,
    None,
    None
  )
  for action, file in results:
      if file.endswith(".one"):
          if action in (1, 2, 3):
              full_filename = os.path.join (path_to_watch, file)
              Msg = o.CreateItem(0)
              Msg.To = "emailaddress"
              Msg.Subject = "NOTIFICATION OF UPDATE"
              newbodyvariable = str(full_filename) + " has been " + str(ACTIONS.get (action, "Unknown"))
              Msg.Body = newbodyvariable
              Msg.Send()

Body:
Can't you just check every 10 minutes and then send aggregated data via email?

import time
while 1:
      time.sleep(60 * 10)
      results = win32file.ReadDirectoryChangesW (
        hDir,
        1024,
        True,
        win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
         win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
         win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
         win32con.FILE_NOTIFY_CHANGE_SIZE |
         win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
         win32con.FILE_NOTIFY_CHANGE_SECURITY,
        None,
        None
      )
      all_changes = []
      for action, file in results:
          if file.endswith(".one"):
              if action in (1, 2, 3):
                  full_filename = os.path.join (path_to_watch, file)
                  all_changes.append((full_filename, ACTIONS.get (action, "Unknown")))
      if all_changes:
          Msg = o.CreateItem(0)
          Msg.To = "emailaddress"
          Msg.Subject = "NOTIFICATION OF UPDATE"
          newbodyvariable = "; ".join("{full_filename} has been {action}".format(full_filename, action) for full_filename, action in all_changes)
          Msg.Body = newbodyvariable
          Msg.Send()