问:
Exception java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder
I am developing Android Application and After published it on play store, I facing this problem many time.

```<code>Exception java.lang.IndexOutOfBoundsException: Inconsistency detected.Invalid view holder adapter positionViewHolder{2f9d83c position=11 id=-1, oldPos=-1, pLpos:-1 no parent}
android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition (RecyclerView.java:5297)
android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline (RecyclerView.java:5479)
android.support.v7.widget.GapWorker.prefetchPositionWithDeadline (GapWorker.java:282)
android.support.v7.widget.GapWorker.flushTaskWithDeadline (GapWorker.java:336)
android.support.v7.widget.GapWorker.flushTasksWithDeadline (GapWorker.java:349)
android.support.v7.widget.GapWorker.prefetch (GapWorker.java:356)
android.support.v7.widget.GapWorker.run (GapWorker.java:387)
android.os.Handler.handleCallback (Handler.java:815)
android.os.Handler.dispatchMessage (Handler.java:104)
android.os.Looper.loop (Looper.java:207)
android.app.ActivityThread.main (ActivityThread.java:5737)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:789)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:679)
</code>```

I searched for long time about this problem and applying many Solution but the Exception still raised

One of Solution that I applied was Making Custom LinearLayoutManager:

```<code>public class WrapContentLinearLayoutManager  extends LinearLayoutManager {

    public WrapContentLinearLayoutManager(Context context) {
        super(context);
    }

    //... constructor
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
            setAutoMeasureEnabled(false);
        } catch (IndexOutOfBoundsException e) {
            Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens");
        }
    }

    public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        setAutoMeasureEnabled(false);
    }

    public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setAutoMeasureEnabled(false);
    }

    @Override
    public boolean supportsPredictiveItemAnimations() {
        return false;
    }
}
</code>```

In My Application depends on RecyclerView with Load more and Swipe to Refresh features

I using Volley to get Data from web Service for Load more and Swipe to Refresh

To Load More Item in RecyclerView, inside the call back of Volley Response I append the new Items in to ArrayList and notify the adapter Like this:

```<code>    final int positionStart = list.size() - 1;
    final int itemCount = response.length();
    for (int i=0;i<response.length();i++)
    {
        try
        {
            obj = response.getJSONObject(i);
            list.add(new ItemEntry(obj.getInt("Id"),obj.getString("Title").trim()obj.getBoolean("isFavorite"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(index == 0)
        {
            // for first Initialize for adapter
            adapter = new MyAdapter(latestEntryList,getActivity());
            adapter.setOnItemClickCallBack(mainFragment);
            recyclerView.setAdapter(adapter);
        }
        else
        {
            // for load more items
            recyclerView.post(new Runnable()
            {
                @Override
                public void run()
                {
                   adapter.updateItems(positionStart,itemCount);
                }
            });
        }
    }
</code>```

The Code for Adapter.UpdateItems

```<code>  public void updateItems(int positionStart,int itemCount) {
        itemsCount = getItemCount();
        this.notifyItemRangeInserted(positionStart,itemCount);
    }
</code>```

In case of load More I do the following; in OnRefresh

```<code>   public void onRefresh() {
        listFragment.LatestEntry(0,false);
// 0 the index and False isAppend to list of not
    }
</code>```

The code for LatestEntry is:

```<code>   private void LatestEntry(final int index, final boolean isAppend)
        {
        String customerId = "123";
        String uri = String.format(BASE_URL+"/api/Entry/LatestEntry?customerId=%s&index=%s",customerId,index);

            JsonArrayRequest LatestEntryJsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri,
                null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response)
                   {
                        JSONObject obj = new JSONObject();
                        if(response.length() > 0 && !isAppend)
                        {
                            int startPosition = 0;
                            int preSize;

                            if(adapter != null)
                                preSize = adapter.entries.size();
                            else
                                preSize = 0;
                            if(preSize > 0 && EntryList.size() > 0) {
                                EntryList.clear();
                                adapter.entries.clear();
                                adapter.notifyItemRangeRemoved(startPosition, preSize);
                            }
                        }

                        final int positionStart = EntryList.size() - 1;
                        final int itemCount = response.length();
                        for (int i=0;i<response.length();i++)
                        {
                            try {
                                obj = response.getJSONObject(i);
                                list.add(new ItemEntry
                               (obj.getInt("Id"),obj.getString("Title").trim()
                                  obj.getBoolean("isFavorite"));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        if(index == 0)
                        { // for first Initialize for adapter
                            adapter = new MyAdapter(latestEntryList,getActivity());
                            adapter.setOnItemClickCallBack(mainFragment);
                            recyclerView.setAdapter(adapter);
                        }
                        else
                        {
                            // for load more items
                            recyclerView.post(new Runnable()
                            {
                                @Override
                                public void run() {
                                   adapter.updateItems(positionStart,itemCount);
                                }
                            });
                        }
                    }
                    setListShownNoAnimation(true);
                    if(mainFragment.swipeRefreshLayout.isRefreshing())
                      mainFragment.swipeRefreshLayout.setRefreshing(false);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MyApplication.getAppContext(),error.getMessage(),Toast.LENGTH_LONG);
                }
            }
            );

            LatestEntryJsonArrayRequest.setTag("LatestEntry");
            KidsSingleton.getInstance().addToRequestQueue(LatestEntryJsonArrayRequest);
        }
</code>```

Please note the Following:

The Recyclerview Version is: recyclerview-v7:25.3.0

I have Three RecylerView in ViewPager

Each ViewPager Contain Fragment and The Fragment Contain ListFragment  with RecylerView.

There are one Adapter for all RecylcrViews.

Can any one help to overcome this issue?

答:
RecyclerView$Recycler.validateViewHolderForOffsetPosition complains about not receiving a valid ViewHolder item, while it seems to be at the offset position of the 11th item.

would assume you might have forgotten to inflate the ViewHolder when adding more items to the Adapter... the way of processing appears wrongful; while ordinary, one only has to update the data array and then notify the Adapter with eg. notifyDataChanged(); think when adding items directly to the Adapter, these notifications are being triggered internally.

the swipeRefreshLayout.setRefreshing(false) probably should happen within a callback method, so that the wheel animation disappears, when the loading has completed.

maybe check this example to get an idea in which order the framework triggers the events (hence it is often the problem, that one creates functionality, which the framework already brings with it)... stepping into might also provide a clue, why there is no valid ViewHolder being inflated for that item.

Body:
I am developing Android Application and After published it on play store, I facing this problem many time.

Exception java.lang.IndexOutOfBoundsException: Inconsistency detected.Invalid view holder adapter positionViewHolder{2f9d83c position=11 id=-1, oldPos=-1, pLpos:-1 no parent}
android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition (RecyclerView.java:5297)
android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline (RecyclerView.java:5479)
android.support.v7.widget.GapWorker.prefetchPositionWithDeadline (GapWorker.java:282)
android.support.v7.widget.GapWorker.flushTaskWithDeadline (GapWorker.java:336)
android.support.v7.widget.GapWorker.flushTasksWithDeadline (GapWorker.java:349)
android.support.v7.widget.GapWorker.prefetch (GapWorker.java:356)
android.support.v7.widget.GapWorker.run (GapWorker.java:387)
android.os.Handler.handleCallback (Handler.java:815)
android.os.Handler.dispatchMessage (Handler.java:104)
android.os.Looper.loop (Looper.java:207)
android.app.ActivityThread.main (ActivityThread.java:5737)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:789)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:679)

I searched for long time about this problem and applying many Solution but the Exception still raised

One of Solution that I applied was Making Custom LinearLayoutManager:

public class WrapContentLinearLayoutManager  extends LinearLayoutManager {

    public WrapContentLinearLayoutManager(Context context) {
        super(context);
    }

    //... constructor
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        try {
            super.onLayoutChildren(recycler, state);
            setAutoMeasureEnabled(false);
        } catch (IndexOutOfBoundsException e) {
            Log.e("Error", "IndexOutOfBoundsException in RecyclerView happens");
        }
    }

    public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        setAutoMeasureEnabled(false);
    }

    public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setAutoMeasureEnabled(false);
    }

    @Override
    public boolean supportsPredictiveItemAnimations() {
        return false;
    }
}

In My Application depends on RecyclerView with Load more and Swipe to Refresh features

I using Volley to get Data from web Service for Load more and Swipe to Refresh

To Load More Item in RecyclerView, inside the call back of Volley Response I append the new Items in to ArrayList and notify the adapter Like this:

    final int positionStart = list.size() - 1;
    final int itemCount = response.length();
    for (int i=0;i<response.length();i++)
    {
        try
        {
            obj = response.getJSONObject(i);
            list.add(new ItemEntry(obj.getInt("Id"),obj.getString("Title").trim()obj.getBoolean("isFavorite"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(index == 0)
        {
            // for first Initialize for adapter
            adapter = new MyAdapter(latestEntryList,getActivity());
            adapter.setOnItemClickCallBack(mainFragment);
            recyclerView.setAdapter(adapter);
        }
        else
        {
            // for load more items
            recyclerView.post(new Runnable()
            {
                @Override
                public void run()
                {
                   adapter.updateItems(positionStart,itemCount);
                }
            });
        }
    }

The Code for Adapter.UpdateItems

  public void updateItems(int positionStart,int itemCount) {
        itemsCount = getItemCount();
        this.notifyItemRangeInserted(positionStart,itemCount);
    }

In case of load More I do the following; in OnRefresh

   public void onRefresh() {
        listFragment.LatestEntry(0,false);
// 0 the index and False isAppend to list of not
    }

The code for LatestEntry is:

   private void LatestEntry(final int index, final boolean isAppend)
        {
        String customerId = "123";
        String uri = String.format(BASE_URL+"/api/Entry/LatestEntry?customerId=%s&index=%s",customerId,index);

            JsonArrayRequest LatestEntryJsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri,
                null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response)
                   {
                        JSONObject obj = new JSONObject();
                        if(response.length() > 0 && !isAppend)
                        {
                            int startPosition = 0;
                            int preSize;

                            if(adapter != null)
                                preSize = adapter.entries.size();
                            else
                                preSize = 0;
                            if(preSize > 0 && EntryList.size() > 0) {
                                EntryList.clear();
                                adapter.entries.clear();
                                adapter.notifyItemRangeRemoved(startPosition, preSize);
                            }
                        }

                        final int positionStart = EntryList.size() - 1;
                        final int itemCount = response.length();
                        for (int i=0;i<response.length();i++)
                        {
                            try {
                                obj = response.getJSONObject(i);
                                list.add(new ItemEntry
                               (obj.getInt("Id"),obj.getString("Title").trim()
                                  obj.getBoolean("isFavorite"));

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        if(index == 0)
                        { // for first Initialize for adapter
                            adapter = new MyAdapter(latestEntryList,getActivity());
                            adapter.setOnItemClickCallBack(mainFragment);
                            recyclerView.setAdapter(adapter);
                        }
                        else
                        {
                            // for load more items
                            recyclerView.post(new Runnable()
                            {
                                @Override
                                public void run() {
                                   adapter.updateItems(positionStart,itemCount);
                                }
                            });
                        }
                    }
                    setListShownNoAnimation(true);
                    if(mainFragment.swipeRefreshLayout.isRefreshing())
                      mainFragment.swipeRefreshLayout.setRefreshing(false);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MyApplication.getAppContext(),error.getMessage(),Toast.LENGTH_LONG);
                }
            }
            );

            LatestEntryJsonArrayRequest.setTag("LatestEntry");
            KidsSingleton.getInstance().addToRequestQueue(LatestEntryJsonArrayRequest);
        }

Please note the Following:

The Recyclerview Version is: recyclerview-v7:25.3.0

I have Three RecylerView in ViewPager

Each ViewPager Contain Fragment and The Fragment Contain ListFragment  with RecylerView.

There are one Adapter for all RecylcrViews.

Can any one help to overcome this issue?


来源: stackexchange

问:
MVC TextBoxFor selected value
I don't use DropDownListFor,without DropDownListFor..
I want use TextBoxFor because my TextBoxFor contain autodata,
With save TextBoxFor value 0 in my database..How I get selected value and save values my database ..for help thanks
 Code:

```<code>@Html.TextBoxFor(model=>model.Fakulteler,new {@type="text",@class="form-control",id= "FakultelerId"})
</code>```

JavaScript:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#FakultelerId").autocomplete({
            source: '@Url.Action("Search","Fakulte")'
        });
    });
</script>
</code>```

Code:

```<code>public List<string> Search(string name)
{
    KutuphaneContext db = new DataContext.KutuphaneContext();
    return db.Fakulte.Where(x => x.FakulteAdi.Contains(name)).Select(x => x.FakulteAdi).ToList();
}

public ActionResult Search(string term)
{
    Fakulte fak = new Models.Fakulte();
    return Json(fak.Search(term), JsonRequestBehavior.AllowGet);
}
</code>```

答:
Use the autocomplete change event to save the selected data:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#FakultelerId").autocomplete({
            source: '@Url.Action("Search","Fakulte")',
            change: function( event, ui ) {
                if (ui.item !== null) {
                    $.ajax({
                        url: '/Search/SaveData',
                        type: 'POST',
                        data: { Value: ui.item.value },
                        success: function (data) {
                            // do something after saving
                        }
                    });
                }
            }
        });
    });
</script>
</code>```

And you will have your method:

```<code>[HttpPost]
public IActionResult SaveData(string Value)
{
    // Do something with data
    return Json(true);
}
</code>```

The change event will be triggered only if the selected value has changed.

ContentLicense: CC BY-SA 3.0

Title: MVC TextBoxFor selected value

Body:
I don't use DropDownListFor,without DropDownListFor..
I want use TextBoxFor because my TextBoxFor contain autodata,
With save TextBoxFor value 0 in my database..How I get selected value and save values my database ..for help thanks
 Code:

@Html.TextBoxFor(model=>model.Fakulteler,new {@type="text",@class="form-control",id= "FakultelerId"})

JavaScript:

Code:

public List<string> Search(string name)
{
    KutuphaneContext db = new DataContext.KutuphaneContext();
    return db.Fakulte.Where(x => x.FakulteAdi.Contains(name)).Select(x => x.FakulteAdi).ToList();
}

public ActionResult Search(string term)
{
    Fakulte fak = new Models.Fakulte();
    return Json(fak.Search(term), JsonRequestBehavior.AllowGet);
}

Body:
Use the autocomplete change event to save the selected data:

<script type="text/javascript">
    $(document).ready(function () {
        $("#FakultelerId").autocomplete({
            source: '@Url.Action("Search","Fakulte")',
            change: function( event, ui ) {
                if (ui.item !== null) {
                    $.ajax({
                        url: '/Search/SaveData',
                        type: 'POST',
                        data: { Value: ui.item.value },
                        success: function (data) {
                            // do something after saving
                        }
                    });
                }
            }
        });
    });
</script>

And you will have your method:

[HttpPost]
public IActionResult SaveData(string Value)
{
    // Do something with data
    return Json(true);
}

The change event will be triggered only if the selected value has changed.


问:
Change ticks of y-axis in python
I want to change y axis ticks in python. I am using the code

```<code>import pylab as plt
y1 = [0,1,2,...10]
y2 = [90,40,65,12,....]
labels = [0.30,0.29,0.28,....]
plt.plot(y1)
plt.plot(y2,'r')
plt.yticks(y1, labels)
plt.yticks(y2, labels)
plt.show()
</code>```

But all the y axis label appear at one place on top of one another

答:
Borrowing heavily from this example, the code below demonstrates one possible way to have two plots on one figure. </p>

```<code>import pylab as plt

fig, ax1 = plt.subplots()
y1 = [0,1,2,3,4,5,6,7,8,9,10]

labels = [0.30,0.29,0.28,0.27,0.26,0.25,0.24,0.23,0.22,0.21,0.20]
ax1.plot(labels, y1, 'b-')

ax1.set_xlabel('labels')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('y1', color='b', rotation="horizontal")
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
y2 = [90,40,65,12,23,43,54,13,42,53,63]
ax2.plot(labels, y2, 'r-')
ax2.set_ylabel('y2', color='r', rotation="horizontal")
ax2.tick_params('y', colors='r')

fig.tight_layout()
plt.show()
</code>```

Title: Change ticks of y-axis in python

Body:
I want to change y axis ticks in python. I am using the code

import pylab as plt
y1 = [0,1,2,...10]
y2 = [90,40,65,12,....]
labels = [0.30,0.29,0.28,....]
plt.plot(y1)
plt.plot(y2,'r')
plt.yticks(y1, labels)
plt.yticks(y2, labels)
plt.show()

But all the y axis label appear at one place on top of one another

Body:
Borrowing heavily from this example, the code below demonstrates one possible way to have two plots on one figure.

import pylab as plt

fig, ax1 = plt.subplots()
y1 = [0,1,2,3,4,5,6,7,8,9,10]

labels = [0.30,0.29,0.28,0.27,0.26,0.25,0.24,0.23,0.22,0.21,0.20]
ax1.plot(labels, y1, 'b-')

ax1.set_xlabel('labels')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('y1', color='b', rotation="horizontal")
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
y2 = [90,40,65,12,23,43,54,13,42,53,63]
ax2.plot(labels, y2, 'r-')
ax2.set_ylabel('y2', color='r', rotation="horizontal")
ax2.tick_params('y', colors='r')

fig.tight_layout()
plt.show()


问:
OpenCL could not found Intel HD 4000
I'll warn you in advance my written english it is not good, so please have some patience because I'll do a lot of errors.
I need to expose the graphic card in order to do some benchmark with parallel algorithms on finite element analysis. I downloaded the intel sdk at this link https://software.intel.com/en-us/intel-opencl .
I am using Ubuntu 16.10, so i followed all the instruction as explained in this post https://streamcomputing.eu/blog/2011-06-24/install-opencl-on-debianubuntu-orderly/ .
When i run a simple algorithm wich checks all the device, it only recognizes the cpu, failing to find the graphic card. The same program works well on a mac (because OpenCL is in the stack of course).

```<code>// includes...

int main(int argc, const char * argv[])
{
// See what standard OpenCL sees
std::vector<cl::Platform> platforms;

// Get platform
cl::Platform::get(&platforms);

// Temp
std::string s;

// Where the GPU lies
cl::Device gpudevice;

// Found a GPU
bool gpufound = false;

std::cout << "**** OPENCL ****" << std::endl;

// See if we have a GPU
for (auto p : platforms)
{
    std::vector<cl::Device> devices;

    p.getDevices(CL_DEVICE_TYPE_ALL, &devices);

    for (auto d : devices)
    {
        std::size_t i = 4;
        d.getInfo(CL_DEVICE_TYPE, &i);

        std::cout << "> Device type     " <<
                    (i & CL_DEVICE_TYPE_CPU ? "CPU" : "") <<
                    (i & CL_DEVICE_TYPE_GPU ? "GPU" : "") <<
                    (i & CL_DEVICE_TYPE_ACCELERATOR ? "ACCELERATOR" : "");

        if (i & CL_DEVICE_TYPE_GPU)
        {
            gpudevice = d;
            gpufound  = true;
        }

        std::cout << " Version  " << s << std::endl;

    }
}

if (!gpufound)
{
    std::cout << "NO GPU FOUND. ABORTING." << std::endl;
    return 1;
}
// Do other things...
</code>```

the output is:

```<code>/home/andrea/Dropbox/fem/SiNDy/clfem/cmake-build-debug/vector_sycl
**** OPENCL ****
> Device type     CPU Version
NO GPU FOUND. ABORTING.

Process finished with exit code 1
</code>```

I tried to add the current user in the video group, i also tried to install Intel Media Server Studio following the instructions coming with the package but I could not build the kernel because of some compile errors.
I also updated all the drivers with the automatic software update of Ubuntu, but still the GC is not found.

答: Maybe you want to try beignet, which is an OpenCL implementation for IvyBridge+ iGPUs. There are packages of beignet for Ubuntu 16.10. To be more precise, I think you are looking for the packages beignet-dev and beignet-opencl-icd. Test it yourself since I have no Ubuntu installation currently available. (However, beignet itself works pretty well on my Intel HD Graphics 520 and Antergos/Arch Linux)

Title: OpenCL could not found Intel HD 4000

Body:
I'll warn you in advance my written english it is not good, so please have some patience because I'll do a lot of errors.
I need to expose the graphic card in order to do some benchmark with parallel algorithms on finite element analysis. I downloaded the intel sdk at this link https://software.intel.com/en-us/intel-opencl .
I am using Ubuntu 16.10, so i followed all the instruction as explained in this post https://streamcomputing.eu/blog/2011-06-24/install-opencl-on-debianubuntu-orderly/ .
When i run a simple algorithm wich checks all the device, it only recognizes the cpu, failing to find the graphic card. The same program works well on a mac (because OpenCL is in the stack of course).

// includes...

int main(int argc, const char * argv[])
{
// See what standard OpenCL sees
std::vector<cl::Platform> platforms;

// Get platform
cl::Platform::get(&platforms);

// Temp
std::string s;

// Where the GPU lies
cl::Device gpudevice;

// Found a GPU
bool gpufound = false;

std::cout << "**** OPENCL ****" << std::endl;

// See if we have a GPU
for (auto p : platforms)
{
    std::vector<cl::Device> devices;

    p.getDevices(CL_DEVICE_TYPE_ALL, &devices);

    for (auto d : devices)
    {
        std::size_t i = 4;
        d.getInfo(CL_DEVICE_TYPE, &i);

        std::cout << "> Device type     " <<
                    (i & CL_DEVICE_TYPE_CPU ? "CPU" : "") <<
                    (i & CL_DEVICE_TYPE_GPU ? "GPU" : "") <<
                    (i & CL_DEVICE_TYPE_ACCELERATOR ? "ACCELERATOR" : "");

        if (i & CL_DEVICE_TYPE_GPU)
        {
            gpudevice = d;
            gpufound  = true;
        }

        std::cout << " Version  " << s << std::endl;

    }
}

if (!gpufound)
{
    std::cout << "NO GPU FOUND. ABORTING." << std::endl;
    return 1;
}
// Do other things...

the output is:

/home/andrea/Dropbox/fem/SiNDy/clfem/cmake-build-debug/vector_sycl
**** OPENCL ****
> Device type     CPU Version
NO GPU FOUND. ABORTING.

Process finished with exit code 1

I tried to add the current user in the video group, i also tried to install Intel Media Server Studio following the instructions coming with the package but I could not build the kernel because of some compile errors.
I also updated all the drivers with the automatic software update of Ubuntu, but still the GC is not found.


问:
Button stays disabled after "back" in safari due to bfcache
I submit a form using

```<code>$('#submitbutton').attr('disabled','true');
setTimeout(function(){ $("#myform").submit(); }, 100);
</code>```

In safari, when returning to this page by clicking the back button of the browser, the button is still disabled.

I've tried adding:

```<code>$( document ).ready(function() {
    $('#submitbutton').removeAttr("disabled");
...
</code>```

but that doesn't work either.

I've looked online, and it seems that this has to do with bfcache.
While I understand the concept of this cache, and how this can improve loading speed, I don't want it on this page. Is there an easy solution to disable it, cross-browser? The solutions I've found online are all 2-5 years old, and don't work.

Note that in Chrome, everything works fine: the button is enabled AND all my JS is executed after clicking the back-button.

I could implement things like enabling the button on page leave or something like that, but I really don't like this different behaviour in different browsers. So I want to disable bfcache for all browsers, OR, use bfcache in all browsers.

Note: I don't want to force a page refresh after clicking the back button, because this looks very ugly and bulky on my page.

答:
The event pageshow can be triggered even in bfcache, so write your js code like this:

```<code>window.addEventListener('pageshow', function( e ){
    //your code
});
</code>```

Body:
I submit a form using

$('#submitbutton').attr('disabled','true');
setTimeout(function(){ $("#myform").submit(); }, 100);

In safari, when returning to this page by clicking the back button of the browser, the button is still disabled.

I've tried adding:

$( document ).ready(function() {
    $('#submitbutton').removeAttr("disabled");
...

but that doesn't work either.

I've looked online, and it seems that this has to do with bfcache.
While I understand the concept of this cache, and how this can improve loading speed, I don't want it on this page. Is there an easy solution to disable it, cross-browser? The solutions I've found online are all 2-5 years old, and don't work.

Note that in Chrome, everything works fine: the button is enabled AND all my JS is executed after clicking the back-button.

I could implement things like enabling the button on page leave or something like that, but I really don't like this different behaviour in different browsers. So I want to disable bfcache for all browsers, OR, use bfcache in all browsers.

Note: I don't want to force a page refresh after clicking the back button, because this looks very ugly and bulky on my page.

Body:
The event pageshow can be triggered even in bfcache, so write your js code like this:

window.addEventListener('pageshow', function( e ){
    //your code
});


问:
How to upgrade Appium 1.5.3 to Appium 1.8.1
I have tried with command:

```<code>npm -install -g appium@1.6
</code>```

but when I restart Appium, it is still in 1.5.3 version.

答:
You can run below command in terminal to install appium 1.6

```<code>npm install appium
</code>```

For this you need node.js to be installed in your machine
You can specify the version of the appium to be installed by using below command

```<code>npm install appium 1.6.3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have tried with command:

npm -install -g appium@1.6

but when I restart Appium, it is still in 1.5.3 version.

Body:
You can run below command in terminal to install appium 1.6

npm install appium

For this you need node.js to be installed in your machine
You can specify the version of the appium to be installed by using below command

npm install appium 1.6.3


问:
The dependency `Firebase/Core` is not used in any concrete target
I am using Xcode 8.2.1, Swift 3, and IOS 10.2 (for iphone simulator). I am trying to follow this tutorial https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

I have not gotten to the Firebase stuff. Right now I am just trying to build and compile the starter code.

The starter Podfile looks like this:

```<code>inhibit_all_warnings!

pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Auth'
</code>```

When I run pod install, I get

```<code>Re-creating CocoaPods due to major version update.
Analyzing dependencies
[!] The dependency `Firebase/Core` is not used in any concrete target.
The dependency `Firebase/Database` is not used in any concrete target.
The dependency `Firebase/Auth` is not used in any concrete target.
</code>```

What should I do to fix this?

答: It's caused by not specifying the target. You have to add the target "your target name" in Podfile.

Body:
I am using Xcode 8.2.1, Swift 3, and IOS 10.2 (for iphone simulator). I am trying to follow this tutorial https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

I have not gotten to the Firebase stuff. Right now I am just trying to build and compile the starter code.

The starter Podfile looks like this:

inhibit_all_warnings!

pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Auth'

When I run pod install, I get

Re-creating CocoaPods due to major version update.
Analyzing dependencies
[!] The dependency `Firebase/Core` is not used in any concrete target.
The dependency `Firebase/Database` is not used in any concrete target.
The dependency `Firebase/Auth` is not used in any concrete target.

What should I do to fix this?


问:
jQuery - Issues with combining selectors in a single event handler
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});
</code>```

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

答:
Why is it less efficient? In this case mainly because you're casting this to a jQuery object an extra 3 times per click per element, where as:

```<code>$("#container").delegate('a.button', 'click', function() {
  alert("a.button was clicked");
}).delegate('span.xyz', 'click', function() {
  alert("span.xyz was clicked");
}).delegate('a.another', 'click', function() {
  alert("a.another was clicked");
});
</code>```

Would bind once to the container (3 handlers) and run each of the 3 selectors once per click, rather than also having n handlers (number of elements) across all bound elements.  So the binding time is lower and the number of overall handlers (assuming there's 3+ elements) is far lower in a big page, as this will always attach exactly 3.

Also you're not incurring the cost of the initial $('a.button, span.xyz, a.another') selector to find the elements you need at the onset.

ContentLicense: CC BY-SA 2.5

Body:
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

Body:
Why is it less efficient? In this case mainly because you're casting this to a jQuery object an extra 3 times per click per element, where as:

$("#container").delegate('a.button', 'click', function() {
  alert("a.button was clicked");
}).delegate('span.xyz', 'click', function() {
  alert("span.xyz was clicked");
}).delegate('a.another', 'click', function() {
  alert("a.another was clicked");
});

Would bind once to the container (3 handlers) and run each of the 3 selectors once per click, rather than also having n handlers (number of elements) across all bound elements.  So the binding time is lower and the number of overall handlers (assuming there's 3+ elements) is far lower in a big page, as this will always attach exactly 3.

Also you're not incurring the cost of the initial $('a.button, span.xyz, a.another') selector to find the elements you need at the onset.


问:
Renaming a file with gulp rename and adding an index
I need to rename a batch of photos adding an index to them, like 'image-1-tmb' or 'image-23-tmb'. I have already searched this and didn't find it, didn't even come close to finding it.

This is my actual code:

```<code>gulp.task('rsz_tmb_menu',function(){
 return gulp.src('./zips/**/*.{jpg,JPG}', { base: './zips' })
 .pipe(imageResize({
   width : width_tmb_menu,
   height : height_tmb_menu,
   crop : true,
   quality : 0.6,
   imageMagick : true,
   upscale : false
 }))
 .pipe(gulp.dest('./images/tmb_menu'));
});
</code>```

答:
I'd like to do it to append the size of the original image…
In my case, this is a requirement of photoswipe.

Trying to do it with gulp, unfortunately, I get stuck even when trying to append the size of the current image:

```<code>var sizeOf = require('image-size');

(...)

.pipe(rename(function (path) {
  var dimensions = sizeOf(path);
  path.basename += ("-" + dimensions.width + "x" +  dimensions.height);
 }))
</code>```

raises an error:

```<code>node_modules/image-size/lib/index.js:79
throw new TypeError('invalid invocation');
</code>```

answering my own question in case it helps someone

based on http://www.pixeldonor.com/2014/feb/20/writing-tasks-gulpjs/

```<code>return gulp.src(...)
.pipe(through.obj(function (chunk, enc, cb) {
        dimensions = sizeOf(chunk.path);
        extname = Path.extname(chunk.path);
        dirname = Path.dirname(chunk.path);
        basename = Path.basename(chunk.path, extname);
        chunk.path = Path.join(dirname, basename + "-" + dimensions.width + "x" + dimensions.height + extname);
        this.push(chunk);
        cb(null, chunk);
}))
.pipe(imageResize({
        width : 600,
        height : 600,
        crop : true,
        upscale : true
}))
.pipe(gulp.dest(...));
</code>```

Body:
I need to rename a batch of photos adding an index to them, like 'image-1-tmb' or 'image-23-tmb'. I have already searched this and didn't find it, didn't even come close to finding it.

This is my actual code:

gulp.task('rsz_tmb_menu',function(){
 return gulp.src('./zips/**/*.{jpg,JPG}', { base: './zips' })
 .pipe(imageResize({
   width : width_tmb_menu,
   height : height_tmb_menu,
   crop : true,
   quality : 0.6,
   imageMagick : true,
   upscale : false
 }))
 .pipe(gulp.dest('./images/tmb_menu'));
});

Body:
I'd like to do it to append the size of the original image…
In my case, this is a requirement of photoswipe.

Trying to do it with gulp, unfortunately, I get stuck even when trying to append the size of the current image:

var sizeOf = require('image-size');

(...)

.pipe(rename(function (path) {
  var dimensions = sizeOf(path);
  path.basename += ("-" + dimensions.width + "x" +  dimensions.height);
 }))

raises an error:

node_modules/image-size/lib/index.js:79
throw new TypeError('invalid invocation');

answering my own question in case it helps someone

based on http://www.pixeldonor.com/2014/feb/20/writing-tasks-gulpjs/

return gulp.src(...)
.pipe(through.obj(function (chunk, enc, cb) {
        dimensions = sizeOf(chunk.path);
        extname = Path.extname(chunk.path);
        dirname = Path.dirname(chunk.path);
        basename = Path.basename(chunk.path, extname);
        chunk.path = Path.join(dirname, basename + "-" + dimensions.width + "x" + dimensions.height + extname);
        this.push(chunk);
        cb(null, chunk);
}))
.pipe(imageResize({
        width : 600,
        height : 600,
        crop : true,
        upscale : true
}))
.pipe(gulp.dest(...));


问:
ScrollView inside Fragment Relative layout is not working
I am using fragment to display registration page
I want "OTP" button stick to the bottom, so I used relative layout for that. I am using linear layout for edittext. When i click on edittext, keyboard appeared but when I am trying to scroll the page when keyboard is opened, its not scrolling at all
Someone please Help

Here is my fragment code

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F4F4F4"
tools:context="values.Registration">

<ScrollView
    android:fillViewport="true"
    android:isScrollContainer="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F4F4F4"
        android:orientation="vertical">

        <ImageView
            android:layout_width="110dp"
            android:layout_height="110dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:background="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Mobile No. /\nमो. नंबर "
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:maxLength="10"
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:phoneNumber="true"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView5"
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Mail Id. /\nइ-मेल "
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="60dp"
            android:layout_marginTop="2dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Name /\nनाव"
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>
    </LinearLayout>
</ScrollView>

<Button
    android:id="@+id/bt_send_otp"
    android:layout_width="match_parent"
    android:layout_height="52dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@color/colorPrimary"
    android:drawablePadding="-40dp"
    android:drawableRight="@drawable/arrow_right"
    android:paddingRight="15dp"
    android:text="SEND OTP / वो. टि. पी. पाठवा"
    android:textColor="#FFF"
    android:textSize="16dp" />

</RelativeLayout>
</code>```

答:
in Manifest:</p>

```<code>android:windowSoftInputMode="adjustResize"
</code>```

Body:
I am using fragment to display registration page
I want "OTP" button stick to the bottom, so I used relative layout for that. I am using linear layout for edittext. When i click on edittext, keyboard appeared but when I am trying to scroll the page when keyboard is opened, its not scrolling at all
Someone please Help

Here is my fragment code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F4F4F4"
tools:context="values.Registration">

<ScrollView
    android:fillViewport="true"
    android:isScrollContainer="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F4F4F4"
        android:orientation="vertical">

        <ImageView
            android:layout_width="110dp"
            android:layout_height="110dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"
            android:background="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Mobile No. /\nमो. नंबर "
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:maxLength="10"
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:phoneNumber="true"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView5"
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Mail Id. /\nइ-मेल "
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="60dp"
            android:layout_marginTop="2dp"
            android:background="#fff"
            android:orientation="horizontal">

            <TextView
                android:layout_width="130dp"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:paddingLeft="15dp"
                android:text="Name /\nनाव"
                android:textSize="17dp" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="58dp"
                android:layout_gravity="center"
                android:gravity="center_vertical"
                android:hint="Mobile NO."
                android:paddingLeft="15dp"
                android:paddingStart="5dp"
                android:singleLine="true"
                android:textColor="#000"
                android:textColorHint="#fff"
                android:textSize="17dp" />
        </LinearLayout>
    </LinearLayout>
</ScrollView>

<Button
    android:id="@+id/bt_send_otp"
    android:layout_width="match_parent"
    android:layout_height="52dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:background="@color/colorPrimary"
    android:drawablePadding="-40dp"
    android:drawableRight="@drawable/arrow_right"
    android:paddingRight="15dp"
    android:text="SEND OTP / वो. टि. पी. पाठवा"
    android:textColor="#FFF"
    android:textSize="16dp" />

</RelativeLayout>

Body:
in Manifest:

android:windowSoftInputMode="adjustResize"


问:
How to print all the substrings from a file using python
I have the text file like this

```<code>Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.106
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.107
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.108
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.109
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1
</code>```

I want to print all the IPv4 Addresses from this file using python script.
Currently I am able to print only first IPv4 (10.0.6.106) address only with the below python script.

ip =  open("ip.txt").read().split("IPv4 ")[1].split(":")[1].split("\n")[0].strip()
print ip

please help me to print all the IPv4 adresses.

答:
I have text file like this

```<code>[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Tx2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0119# 001113
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0306# 005252
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0110# 055222
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0074# 006433
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0071# 023523

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Rx2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0120# 004322
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0303# 005325
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0111# 009940
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0075# 007544
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0079# 001221

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Rx2Bsave
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0125# 001123
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0309# 007704
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0133# 002323
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0085# 002433
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0032# 000875

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Bsave2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0122# 000232
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0311# 001223
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0113# 004422
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0333# 004343
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0323# 000212
</code>```

I need to sort out the data based on frame name.
In the above I have 4 frame names TX2TX,Rx2Tx,Rx2Bsave,Bsave2Tx.
I need to identify those frame names and extact its data and create excel sheet and write into corresponding sheets.

Below is the code Which wrote for this purpose.
I am able to create the excel sheet but I am unable to write into its individual sheets.

```<code> import xlwt

 wbk = xlwt.Workbook()

 row = 4 # row counter
col = 0
sheet_number = 0

f = open('Log1.txt')

 for line in f:
    if 'Frame Name' in line:
         sheet_number += 1
         sheetname = line.split(':')[-1]

        sheet = wbk.add_sheet(sheetname)
        wbk.active_sheet = 0

      L = line.split('#')
        for i,c in enumerate(L):
       sheet.write(row,i,c)
     row += 1

 wbk.save('example.xls')
</code>```

Body:
I have the text file like this

Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.106
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.107
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.108
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.109
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

I want to print all the IPv4 Addresses from this file using python script.
Currently I am able to print only first IPv4 (10.0.6.106) address only with the below python script.

ip =  open("ip.txt").read().split("IPv4 ")[1].split(":")[1].split("\n")[0].strip()
print ip

please help me to print all the IPv4 adresses.

Body:
I have text file like this

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Tx2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0119# 001113
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0306# 005252
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0110# 055222
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0074# 006433
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #23# 0x0071# 023523

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Rx2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0120# 004322
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0303# 005325
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0111# 009940
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0075# 007544
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #22# 0x0079# 001221

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Rx2Bsave
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0125# 001123
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0309# 007704
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0133# 002323
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0085# 002433
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #24# 0x0032# 000875

[   59.095037] TRACE0 LOG  task: pid:0 errid:0 Frame Name: Bsave2Tx
[   59.102857] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0122# 000232
[   59.102971] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0311# 001223
[   59.103079] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0113# 004422
[   59.103229] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0333# 004343
[   59.103341] TRACE0 LOG  task: pid:0 errid:0 #25# 0x0323# 000212

I need to sort out the data based on frame name.
In the above I have 4 frame names TX2TX,Rx2Tx,Rx2Bsave,Bsave2Tx.
I need to identify those frame names and extact its data and create excel sheet and write into corresponding sheets.

Below is the code Which wrote for this purpose.
I am able to create the excel sheet but I am unable to write into its individual sheets.

 import xlwt

 wbk = xlwt.Workbook()

 row = 4 # row counter
col = 0
sheet_number = 0

f = open('Log1.txt')

 for line in f:
    if 'Frame Name' in line:
         sheet_number += 1
         sheetname = line.split(':')[-1]

        sheet = wbk.add_sheet(sheetname)
        wbk.active_sheet = 0

      L = line.split('#')
        for i,c in enumerate(L):
       sheet.write(row,i,c)
     row += 1

 wbk.save('example.xls')


问:
find possible paths in map : recursive function in javascript

doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      }
    }
  }
}

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {

      keystr += str[i] + ".";

      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
            // console.log("Obj check" + JSON.stringify(nObj) + keystr)
          arr.push(nObj);
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = (get(temp, concat.substr(0, concat.length - 1)));

          if (obj != "") {
            // console.log("existing arr "+JSON.stringify(arr))
            obj[m] = (obj[0])[concat.substr(0, concat.length - 1)]
              //  console.log("hello "+JSON.stringify(obj) + " end hello")
            arr.push(obj);
          }
        } else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  return arr;
}

var result = (get(doc, 'a.*.e'))
console.log(result)```

For input of 'a.*.e' the output should  be {'a.d.e': {'f': 'blah blah blah'}}}. But I get all the replacement for wild card as well in the array. I am sure something is wrong but not able to detect it. Help would be appreciated.

答:
You could change the structure of the operation a little bit with a recursive approach and an exit early exit often paradigm with checking of single parts with exit options, like

length, a part result is found,

falsy or not object types,

part at index is a star, then iterate all keys from the object, or

the part at index is a key, then call the function again.

At the end, with a found path, joint the path and generate a new property with the actual value of the object.

function get(object, path) {

    function iter(o, p, i) {
        if (i === parts.length) {
            result[p.join('.')] = o;
            return;
        }
        if (!o || typeof o !== 'object') {
            return;
        }
        if (parts[i] === '*') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], p.concat(k), i + 1);
            });
            return;
        }
        if (parts[i] in o) {
            iter(o[parts[i]], p.concat(parts[i]), i + 1);
        }
    }

    var result = {},
        parts = path.split('.');

    iter(object, [], 0);
    return result;
}

var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };

console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Version with * as wildcard for any level.

function get(object, path) {

    function iter(o, p, i) {
        if (i === parts.length) {
            result[p.join('.')] = o;
            return;
        }
        if (!o || typeof o !== 'object') {
            return;
        }
        if (parts[i] === '*') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], p.concat(k), i);
                iter(o[k], p.concat(k), i + 1);
            });
            return;
        }
        if (parts[i] in o) {
            iter(o[parts[i]], p.concat(parts[i]), i + 1);
        }
    }

    var result = {},
        parts = path.split('.');

    iter(object, [], 0);
    return result;
}

var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };

console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));
console.log(get(doc, 'a.*.f'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
doc = {
  'a': {
    'b': {
      'c': 'hello'
    },
    'd': {
      'c': 'sup',
      'e': {
        'f': 'blah blah blah'
      }
    }
  }
}

function get(json, path) {
  var str = path.split('.');
  var temp = json;
  var arr = [];
  var keystr = "";
  for (var i = 0; i < str.length; i++) {
    if (str[i] != "*") {

      keystr += str[i] + ".";

      if (temp[str[i]] === undefined)
        break;
      else {
        temp = temp[str[i]];
        if (i == str.length - 1) {
          var nObj = {};
          nObjKey = keystr.substr(0, keystr.length - 1);
          nObj[nObjKey] = temp
            // console.log("Obj check" + JSON.stringify(nObj) + keystr)
          arr.push(nObj);
        }
      }
    } else {
      for (var key in temp) {
        var concat = key + "."
        for (var j = i + 1; j < str.length; j++)
          concat += str[j] + ".";
        if (temp[key] !== undefined && temp[key] instanceof Object) {

          var m = keystr + concat.substr(0, concat.length - 1);
          var obj = (get(temp, concat.substr(0, concat.length - 1)));

          if (obj != "") {
            // console.log("existing arr "+JSON.stringify(arr))
            obj[m] = (obj[0])[concat.substr(0, concat.length - 1)]
              //  console.log("hello "+JSON.stringify(obj) + " end hello")
            arr.push(obj);
          }
        } else if (temp[key] !== undefined && i == str.length - 1) {
          // arr.push(temp);
        }
      }
    }
  }
  return arr;
}

var result = (get(doc, 'a.*.e'))
console.log(result)

For input of 'a.*.e' the output should  be {'a.d.e': {'f': 'blah blah blah'}}}. But I get all the replacement for wild card as well in the array. I am sure something is wrong but not able to detect it. Help would be appreciated.

Body:
You could change the structure of the operation a little bit with a recursive approach and an exit early exit often paradigm with checking of single parts with exit options, like

length, a part result is found,

falsy or not object types,

part at index is a star, then iterate all keys from the object, or

the part at index is a key, then call the function again.

At the end, with a found path, joint the path and generate a new property with the actual value of the object.

function get(object, path) {

    function iter(o, p, i) {
        if (i === parts.length) {
            result[p.join('.')] = o;
            return;
        }
        if (!o || typeof o !== 'object') {
            return;
        }
        if (parts[i] === '*') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], p.concat(k), i + 1);
            });
            return;
        }
        if (parts[i] in o) {
            iter(o[parts[i]], p.concat(parts[i]), i + 1);
        }
    }

    var result = {},
        parts = path.split('.');

    iter(object, [], 0);
    return result;
}

var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };

console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));

.as-console-wrapper { max-height: 100% !important; top: 0; }

Version with * as wildcard for any level.

function get(object, path) {

    function iter(o, p, i) {
        if (i === parts.length) {
            result[p.join('.')] = o;
            return;
        }
        if (!o || typeof o !== 'object') {
            return;
        }
        if (parts[i] === '*') {
            Object.keys(o).forEach(function (k) {
                iter(o[k], p.concat(k), i);
                iter(o[k], p.concat(k), i + 1);
            });
            return;
        }
        if (parts[i] in o) {
            iter(o[parts[i]], p.concat(parts[i]), i + 1);
        }
    }

    var result = {},
        parts = path.split('.');

    iter(object, [], 0);
    return result;
}

var doc = { a: { b: { c: 'hello' }, d: { c: 'sup', e: { f: 'blah blah blah' } } } };

console.log(get(doc, 'a.*.e'));
console.log(get(doc, 'a.*.c'));
console.log(get(doc, 'a.*.f'));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Read Fillable PDF form fields in ASP.NET
I have a fillable PDF form created using Adobe Acrobat DC and I want to submit this form to a URL: http://localhost:49168/WebForm1.aspx.

I am using Aspose.Pdf library to read the PDF file on my code but whenever I am trying to read the file it throws an exception: "Incorrect file format". Can anybody help/guide me how to read the fields from this form.

Below is code I am trying to use:

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        string pdftype = Request.ContentType;
        int pdfocument = Request.ContentLength;
        try
        {
            byte[] pdf = new byte[pdfocument];
            Stream stream = new MemoryStream(pdf);
            Aspose.Pdf.Facades.Form form = new Aspose.Pdf.Facades.Form(stream);

         //   HttpContext.Request.InputStream.Read(pdf, 0, pdfocument);
            Document doc = new Document(stream);

        }
        catch (Exception ex)
        {
        }

    }
</code>```

答: I resolved the issue with using HTML export format instead of FDF format and read the values using Form collection.</p>

Body:
I have a fillable PDF form created using Adobe Acrobat DC and I want to submit this form to a URL: http://localhost:49168/WebForm1.aspx.

I am using Aspose.Pdf library to read the PDF file on my code but whenever I am trying to read the file it throws an exception: "Incorrect file format". Can anybody help/guide me how to read the fields from this form.

Below is code I am trying to use:

protected void Page_Load(object sender, EventArgs e)
    {
        string pdftype = Request.ContentType;
        int pdfocument = Request.ContentLength;
        try
        {
            byte[] pdf = new byte[pdfocument];
            Stream stream = new MemoryStream(pdf);
            Aspose.Pdf.Facades.Form form = new Aspose.Pdf.Facades.Form(stream);

         //   HttpContext.Request.InputStream.Read(pdf, 0, pdfocument);
            Document doc = new Document(stream);

        }
        catch (Exception ex)
        {
        }

    }


问:
Can we use GPIO_PinAFConfig function to make a pin as output on STM32L1?
I'm using stm32l100rc board. I need to make a pin output/input several times so can I use GPIO_PinAFConfig function to do that? or do I have to initialize whole GPIO_InitTypeDef structure for it.</p>

答:
A GPIO can be configured as either an input, output, or one of possibly several alternate functions.  As its name suggests, GPIO_PinAFConfig sets one of those alternate functions, so would not achieve your aim at all.

If switching between input and output using the standard peripheral library, there will be some redundancy - register values that do not change, or which are mutually exclusive to input or output.  If you need the switch to be as fast as possible (and we are talking tens or hundreds of nanoseconds here), then direct register access might make significant savings by changing only those registers necessarily necessary.


问:
ContextMenu Icons not displaying
I have some images that I use as icons for ContextMenu Items:

```<code><UserControl.Resources>
    <Image x:Key="DeleteIco" Source="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" Width="16" Height="16"/>
    ...
    <ContextMenu x:Key="MyMenu1">
        <MenuItem Header="Delete" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>

    <ContextMenu x:Key="MyMenu2">
        <MenuItem Header="Delete me" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>
<UserControl.Resources>
</code>```

Sometimes the first menu miss the icon, sometimes the second... why? I don't do anything on the icons in the code.

答:
You have created an Image control, and tried to put it twice in the visual tree. Since all controls can only have one parent your Image got disconnected. Thus using it a second time, the first will be disconnected, resulting in your missing icon.

You can resolve this, by not adding the Image, but the ImageSource instead to your resources:

```<code><BitmapImage x:Key="DeleteIco" UriSource="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" />
</code>```

Your menu has to change a bit for it to work though:

```<code><ContextMenu x:Key="MyMenu1">
    <MenuItem Header="Delete">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>

<ContextMenu x:Key="MyMenu2">
    <MenuItem Header="Delete me">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>
</code>```

Update:

You can also use styles to set some basic properties of the Image for you

```<code><Style TargetType="Image">
    <Setter Property="Width" Value="16"/>
    <Setter Property="Width" Value="16"/>
</Style>
</code>```

Or use a Style for MenuItem to set the Icon each time.

```<code><Style TargetType="MenuItem" x:Key="DeleteMenuIcon">
    <Setter Property="Icon">
        <Setter.Value>
             <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
        </Setter.Value>
    </Setter>
</Style>
</code>```

And the MenuItem:

```<code><MenuItem Header="Delete me" Style="{StaticResource DeleteMenuIcon}" />
</code>```

Title: ContextMenu Icons not displaying

Body:
I have some images that I use as icons for ContextMenu Items:

<UserControl.Resources>
    <Image x:Key="DeleteIco" Source="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" Width="16" Height="16"/>
    ...
    <ContextMenu x:Key="MyMenu1">
        <MenuItem Header="Delete" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>

    <ContextMenu x:Key="MyMenu2">
        <MenuItem Header="Delete me" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>
<UserControl.Resources>

Sometimes the first menu miss the icon, sometimes the second... why? I don't do anything on the icons in the code.

Body:
You have created an Image control, and tried to put it twice in the visual tree. Since all controls can only have one parent your Image got disconnected. Thus using it a second time, the first will be disconnected, resulting in your missing icon.

You can resolve this, by not adding the Image, but the ImageSource instead to your resources:

<BitmapImage x:Key="DeleteIco" UriSource="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" />

Your menu has to change a bit for it to work though:

<ContextMenu x:Key="MyMenu1">
    <MenuItem Header="Delete">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>

<ContextMenu x:Key="MyMenu2">
    <MenuItem Header="Delete me">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>

Update:

You can also use styles to set some basic properties of the Image for you

<Style TargetType="Image">
    <Setter Property="Width" Value="16"/>
    <Setter Property="Width" Value="16"/>
</Style>

Or use a Style for MenuItem to set the Icon each time.

<Style TargetType="MenuItem" x:Key="DeleteMenuIcon">
    <Setter Property="Icon">
        <Setter.Value>
             <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
        </Setter.Value>
    </Setter>
</Style>

And the MenuItem:

<MenuItem Header="Delete me" Style="{StaticResource DeleteMenuIcon}" />


问:
Do not update or delete data from the database
I have doman class:

```<code>package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}
</code>```

I'm trying to delete or update data from a table In my controller:

```<code>def team = Teams.get(1)
team.delete()
</code>```

Update:

```<code>team.name = '123'
team.save()
</code>```

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.

答:
delete ->

```<code>   def delete(Long id) {
            def teamsInstance = Teams.get(id)
            if (!teamsInstance) {
         your logic,  if team instance is null
            }

                teamsInstance.delete(flush: true, failOnError:true)
                 }
</code>```

update ->

```<code>def update(Long id {
        def teamsInstance = Teams.get(id)
         teamsInstance.setName("xyz");
teamsInstance.save(flush: true, failOnError:true)
}
</code>```

In both action i have use flush: true, failOnError:true
If there will any error in your domain then failOnError will throw exception, and with the help of exception you can trace the issue.

Body:
I have doman class:

package testgrails12
class Teams {
String name
static mapping = {
version false
}
static constraints = {
name nullable: true
}
}

I'm trying to delete or update data from a table In my controller:

def team = Teams.get(1)
team.delete()

Update:

team.name = '123'
team.save()

I do not get a result either in the first or in the second cases. Also I do not get any errors. I'm confused. It just does not work. I see the result in the database.

Body:
delete ->

   def delete(Long id) {
            def teamsInstance = Teams.get(id)
            if (!teamsInstance) {
         your logic,  if team instance is null
            }

                teamsInstance.delete(flush: true, failOnError:true)
                 }

update ->

def update(Long id {
        def teamsInstance = Teams.get(id)
         teamsInstance.setName("xyz");
teamsInstance.save(flush: true, failOnError:true)
}

In both action i have use flush: true, failOnError:true
If there will any error in your domain then failOnError will throw exception, and with the help of exception you can trace the issue.


问:
Logging in Typescript using Bunyan and Logentries
I want to setup remote Logging using logentries.com in my ionic app.

This an extract from my package.json:

```<code>  "dependencies": {

    "bunyan": "^1.8.5",
    "bunyan-logentries": "^1.2.0",

  },
  "devDependencies": {
    "@types/bunyan": "0.0.35",
    "@types/bunyan-logentries": "0.1.30",
    "typescript": "2.0.9"
  },
</code>```

Code

```<code>import {createStream} from "bunyan-logentries";
import * as Logger from "bunyan";

// ...
constructor() {
    let token = 'xxxxxxxxxxxxxxxxx';
    let log = Logger.createLogger({
      name: '',
      streams: [{
        level: 'info',
        stream: createStream({token: token}),
        type: 'raw'
       }]
    });
    log.info("Created log");
 }
</code>```

The problem

My IDE does not warn me about any errors. But as soon as I run the app I get the following error:

exists is not a function. (In 'exists(pkgPath)', 'exists' is undefined)

```<code>findPackage@http://localhost:8101/build/main.js:131257:18
register@http://localhost:8101/build/main.js:131332:31
http://localhost:8101/build/main.js:112585:50
http://localhost:8101/build/main.js:113391:34
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:129423:37
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:29972:95
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:80592:90
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:59390:96
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:59495:94
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:128048:94
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:116775:92
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:149625:89
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:66:37
global code@http://localhost:8101/build/main.js:67:12
</code>```

I think the core of the problem is that the @types don't match the actual node modules, but it is unclear how this is supposed to be addressed.

答:
I have faced the same issue.
The bunyan-logentries module depends on le_node: the logentries module for node.

le_node uses the net and tls modules that are not available from the browser.

To move on, I have implemented a custom bunyan stream that sends the logs to logentries via their REST API. It is straightforward to code and it works.

Here is a sample code to illustrate this solution.

The LoggerService that creates Bunyan Instances:

```<code>@Injectable()
export class LoggerService {
    constructor(private http: Http) {
    }

    public create(name: string): Logger{
        return Bunyan.createLogger({
            name: name,
            streams: [{
                stream: new LogentriesBunyanStream(AppConfig.LogEntries.token, this.http),
                type: 'raw'
            }]
        });
    }
}
</code>```

The bunyan custom stream that sends logs to logentries:

```<code>export class LogentriesBunyanStream extends Writable {
    private token: string;
    private http: Http;

    constructor(token: string, http: Http) {
        super({objectMode: true});
        this.http = http;
        this.token = token;
    }

    public _write(rec: any, encoding?: string, cb?: Function) {
        // Replace the level code with a friendly string
        rec.level = LogentriesBunyanStream.resolveLevel(rec.level);

        // Send the post request to logentries
        // https://docs.logentries.com/docs/http-post
        const LOGENTRIES_URL = "https://webhook.logentries.com/noformat/logs/";
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        let requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: JSON.stringify(rec)
        });
        this.http.request(LOGENTRIES_URL + this.token, requestoptions).toPromise().then((response) => {
            cb();
        }).catch((error) =>{
            console.log("faield to send log to the logentries server");
        });
    };

    private static resolveLevel(bunyanLevel) {
        let levelToName = {
            10: 'DEBUG',
            20: 'DEBUG',
            30: 'INFO',
            40: 'WARN',
            50: 'ERROR',
            60: 'CRIT'
        };
        return levelToName[bunyanLevel] || 'INFO';
    }
};
</code>```

Maybe it helps,

Regards.

Body:
I want to setup remote Logging using logentries.com in my ionic app.

This an extract from my package.json:

  "dependencies": {

    "bunyan": "^1.8.5",
    "bunyan-logentries": "^1.2.0",

  },
  "devDependencies": {
    "@types/bunyan": "0.0.35",
    "@types/bunyan-logentries": "0.1.30",
    "typescript": "2.0.9"
  },

Code

import {createStream} from "bunyan-logentries";
import * as Logger from "bunyan";

// ...
constructor() {
    let token = 'xxxxxxxxxxxxxxxxx';
    let log = Logger.createLogger({
      name: '',
      streams: [{
        level: 'info',
        stream: createStream({token: token}),
        type: 'raw'
       }]
    });
    log.info("Created log");
 }

The problem

My IDE does not warn me about any errors. But as soon as I run the app I get the following error:

exists is not a function. (In 'exists(pkgPath)', 'exists' is undefined)

findPackage@http://localhost:8101/build/main.js:131257:18
register@http://localhost:8101/build/main.js:131332:31
http://localhost:8101/build/main.js:112585:50
http://localhost:8101/build/main.js:113391:34
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:129423:37
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:29972:95
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:80592:90
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:59390:96
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:59495:94
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:128048:94
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:116775:92
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:149625:89
__webpack_require__@http://localhost:8101/build/main.js:20:34
http://localhost:8101/build/main.js:66:37
global code@http://localhost:8101/build/main.js:67:12

I think the core of the problem is that the @types don't match the actual node modules, but it is unclear how this is supposed to be addressed.

Body:
I have faced the same issue.
The bunyan-logentries module depends on le_node: the logentries module for node.

le_node uses the net and tls modules that are not available from the browser.

To move on, I have implemented a custom bunyan stream that sends the logs to logentries via their REST API. It is straightforward to code and it works.

Here is a sample code to illustrate this solution.

The LoggerService that creates Bunyan Instances:

@Injectable()
export class LoggerService {
    constructor(private http: Http) {
    }

    public create(name: string): Logger{
        return Bunyan.createLogger({
            name: name,
            streams: [{
                stream: new LogentriesBunyanStream(AppConfig.LogEntries.token, this.http),
                type: 'raw'
            }]
        });
    }
}

The bunyan custom stream that sends logs to logentries:

export class LogentriesBunyanStream extends Writable {
    private token: string;
    private http: Http;

    constructor(token: string, http: Http) {
        super({objectMode: true});
        this.http = http;
        this.token = token;
    }

    public _write(rec: any, encoding?: string, cb?: Function) {
        // Replace the level code with a friendly string
        rec.level = LogentriesBunyanStream.resolveLevel(rec.level);

        // Send the post request to logentries
        // https://docs.logentries.com/docs/http-post
        const LOGENTRIES_URL = "https://webhook.logentries.com/noformat/logs/";
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        let requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: JSON.stringify(rec)
        });
        this.http.request(LOGENTRIES_URL + this.token, requestoptions).toPromise().then((response) => {
            cb();
        }).catch((error) =>{
            console.log("faield to send log to the logentries server");
        });
    };

    private static resolveLevel(bunyanLevel) {
        let levelToName = {
            10: 'DEBUG',
            20: 'DEBUG',
            30: 'INFO',
            40: 'WARN',
            50: 'ERROR',
            60: 'CRIT'
        };
        return levelToName[bunyanLevel] || 'INFO';
    }
};

Maybe it helps,

Regards.


问:
Best Practice to Update EAV table rows
I have the following table:

```<code>SubjectID AttributeID ValueID
1         1           2
1         1           3
1         2           1
2         1           3
2         2           1
1         3           1
</code>```

An attribute can have multiple values (multiple appearances in the above table for the same attribute).
There is no constraint of how many appearances for the same attribute (different value).

I wan't to Update the Subject with SubjectID=1, to change the ValueID to only 1 where the AttributeID is 1, so

Before:

```<code>Select * from Subject WHERE SubjectID=1 AND AttributeID=1
--returns:
SubjectID AttributeID ValueID
1         1           2
1         1           3
</code>```

After:

```<code>Select * from Subject WHERE SubjectID=1 AND AttributeID=1
--returns:
SubjectID AttributeID ValueID
1         1           1
</code>```

I am doing this with a stored procedure with optional parameters (all null and update only the attributes that were provided), now this is not an issue. My question is:

What is the best practice to update this rows? I see the following answers as viable:

Delete all the rows that contain the specified attribute, then insert the new ones;

If there is only one attribute of that type (for the specified subject) update that one (not a good solution if there are more than 1 for the same attribute)

Any other ideas?

答:
You could update just one row and then delete the others like so:</p>

```<code>set rowcount 1;

update Subject
   set ValuedID = 1
 where SubjectID = 1
   and AttributeID = 1;

set rowcount 0;

delete Subject
 where SubjectID = 1
   and AttributeID = 1
   and ValuedID <> 1;
</code>```

Title: Best Practice to Update EAV table rows

Body:
I have the following table:

SubjectID AttributeID ValueID
1         1           2
1         1           3
1         2           1
2         1           3
2         2           1
1         3           1

An attribute can have multiple values (multiple appearances in the above table for the same attribute).
There is no constraint of how many appearances for the same attribute (different value).

I wan't to Update the Subject with SubjectID=1, to change the ValueID to only 1 where the AttributeID is 1, so

Before:

Select * from Subject WHERE SubjectID=1 AND AttributeID=1
--returns:
SubjectID AttributeID ValueID
1         1           2
1         1           3

After:

Select * from Subject WHERE SubjectID=1 AND AttributeID=1
--returns:
SubjectID AttributeID ValueID
1         1           1

I am doing this with a stored procedure with optional parameters (all null and update only the attributes that were provided), now this is not an issue. My question is:

What is the best practice to update this rows? I see the following answers as viable:

Delete all the rows that contain the specified attribute, then insert the new ones;

If there is only one attribute of that type (for the specified subject) update that one (not a good solution if there are more than 1 for the same attribute)

Any other ideas?

Body:
You could update just one row and then delete the others like so:

set rowcount 1;

update Subject
   set ValuedID = 1
 where SubjectID = 1
   and AttributeID = 1;

set rowcount 0;

delete Subject
 where SubjectID = 1
   and AttributeID = 1
   and ValuedID <> 1;