问:
Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting OutOfMemoryError error of:

(java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM)

I have no idea or why its out of memory. I think my image size is very large so I tried to change it.

```<code>Iterator<String> it = imageArray.iterator();
while (it.hasNext()) {
  Object element = it.next();
  String objElement = element.toString();
  Log.e("objElement ", " = " + objElement);
  final ImageView imageView = new ImageView (getContext());
  final ProgressBar pBar = new ProgressBar(getContext(), null,
                                           android.R.attr.progressBarStyleSmall);
  imageView.setTag(it);
  pBar.setTag(it);

  imageView.setImageResource(R.drawable.img_placeholder);
  pBar.setVisibility(View.VISIBLE);

  if (objElement.endsWith(mp3_Pattern)) {
     Log.e("Mp3 ", " ends with ");
     pBar.setVisibility(View.GONE);
     imageView.setImageResource(R.drawable.audio_control);
  }
  if (objElement.endsWith(png_Pattern)) {
     Bitmap bitmap = BitmapFactory.decodeFile(objElement);
     int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
     int x = (bitmap.getWidth() - size) / 2;
     int y = (bitmap.getHeight() - size) / 2;
     Bitmap bitmap_Resul = Bitmap.createBitmap(bitmap, x, y, size, size);
     Log.e("bitmap_Resul "," = "+ bitmap_Resul);

     if (bitmap_Resul != bitmap) {
        bitmap.recycle();
     }
     imageView.setImageBitmap(bitmap_Resul);
     Log.e("png_Pattern ", " ends with ");
     Log.e(" bitmap "," = " + bitmap);
  }

  holder.linearLayout.addView(imageView);
  holder.linearLayout.addView(pBar);
</code>```

The log cat information:

```<code>08-27 14:11:15.307    1857-1857/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.tazeen.classnkk, PID: 1857
    java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:812)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:709)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:634)
            at com.example.tazeen.classnkk.AllPosts_Page$MyListAdapter.getView(AllPosts_Page.java:357)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1659)
            at android.widget.AbsListView.onLayout(AbsListView.java:2151)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

答:
```<code>Bitmap image =((BitmapDrawable)imageView1.getDrawable()).getBitmap();

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.JPEG,50/100,byteArrayOutputStream);
</code>```

50/100 if one uses 100 then original resolution can stopped the Apps for out of memory.

if 50 or less than 100 this will be 50% or less than 100 resolution so this will prevent from out of memory problem

Body:
I want to show the Bitmap image in ImageView from sd card which is stored already. After run my application is crash and getting OutOfMemoryError error of:

(java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM)

I have no idea or why its out of memory. I think my image size is very large so I tried to change it.

Iterator<String> it = imageArray.iterator();
while (it.hasNext()) {
  Object element = it.next();
  String objElement = element.toString();
  Log.e("objElement ", " = " + objElement);
  final ImageView imageView = new ImageView (getContext());
  final ProgressBar pBar = new ProgressBar(getContext(), null,
                                           android.R.attr.progressBarStyleSmall);
  imageView.setTag(it);
  pBar.setTag(it);

  imageView.setImageResource(R.drawable.img_placeholder);
  pBar.setVisibility(View.VISIBLE);

  if (objElement.endsWith(mp3_Pattern)) {
     Log.e("Mp3 ", " ends with ");
     pBar.setVisibility(View.GONE);
     imageView.setImageResource(R.drawable.audio_control);
  }
  if (objElement.endsWith(png_Pattern)) {
     Bitmap bitmap = BitmapFactory.decodeFile(objElement);
     int size = Math.min(bitmap.getWidth(), bitmap.getHeight());
     int x = (bitmap.getWidth() - size) / 2;
     int y = (bitmap.getHeight() - size) / 2;
     Bitmap bitmap_Resul = Bitmap.createBitmap(bitmap, x, y, size, size);
     Log.e("bitmap_Resul "," = "+ bitmap_Resul);

     if (bitmap_Resul != bitmap) {
        bitmap.recycle();
     }
     imageView.setImageBitmap(bitmap_Resul);
     Log.e("png_Pattern ", " ends with ");
     Log.e(" bitmap "," = " + bitmap);
  }

  holder.linearLayout.addView(imageView);
  holder.linearLayout.addView(pBar);

The log cat information:

08-27 14:11:15.307    1857-1857/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.tazeen.classnkk, PID: 1857
    java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.Bitmap.nativeCreate(Native Method)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:812)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:789)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:709)
            at android.graphics.Bitmap.createBitmap(Bitmap.java:634)
            at com.example.tazeen.classnkk.AllPosts_Page$MyListAdapter.getView(AllPosts_Page.java:357)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillDown(ListView.java:698)
            at android.widget.ListView.fillFromTop(ListView.java:759)
            at android.widget.ListView.layoutChildren(ListView.java:1659)
            at android.widget.AbsListView.onLayout(AbsListView.java:2151)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
            at android.view.View.layout(View.java:15671)
            at android.view.ViewGroup.layout(ViewGroup.java:5038)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2086)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1843)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Body:
Bitmap image =((BitmapDrawable)imageView1.getDrawable()).getBitmap();

ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();

image.compress(Bitmap.CompressFormat.JPEG,50/100,byteArrayOutputStream);

50/100 if one uses 100 then original resolution can stopped the Apps for out of memory.

if 50 or less than 100 this will be 50% or less than 100 resolution so this will prevent from out of memory problem


来源: stackexchange

问:
How to uncheck first two checkbox of a group of check box?
I have a list of checkboxes. Checkbox name is CHKBOXPAYANYONE. It has four checkboxes. I want to unchecked first two check box. I am getting the checkbox item by using $("input[name=CHKBOXPAYANYONE]")[0] and $("input[name=CHKBOXPAYANYONE]")[1] . So please suggest how to uncheck them.

答:
Supporting @Carsten Løvbo Andersen answer, you can also use .checked html property:

$("input[name=CHKBOXPAYANYONE]")[0].checked = false;
$("input[name=CHKBOXPAYANYONE]")[1].checked = false;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/></code>```

ContentLicense: CC BY-SA 3.0

Body:
Supporting @Carsten Løvbo Andersen answer, you can also use .checked html property:

$("input[name=CHKBOXPAYANYONE]")[0].checked = false;
$("input[name=CHKBOXPAYANYONE]")[1].checked = false;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>


问:
Bundling not working when edit in tinymce.js
I added the following code in tinymce.js
// Process type specific selector

```<code>if (settings.elements) {
                    each(DOM.select("#" + settings.elements), function (elm) {
                        createEditor(createId(elm), settings, elm);
                    });
                    return;
                }
</code>```

Now, when I run locally with Debug="True", it works fine. But when I set debug="False" and run the project, bundling is not done and the changes which I have made in tinymce.js is not working.

答: Since TinyMCE already comes minified, I solved this just by excluding it from the bundle and loading it separately</p>

Body:
I added the following code in tinymce.js
// Process type specific selector

if (settings.elements) {
                    each(DOM.select("#" + settings.elements), function (elm) {
                        createEditor(createId(elm), settings, elm);
                    });
                    return;
                }

Now, when I run locally with Debug="True", it works fine. But when I set debug="False" and run the project, bundling is not done and the changes which I have made in tinymce.js is not working.


问:
Visual studio stuck installing and it gives up
This is the error log

```<code>enter code here
</code>```

https://pastebin.com/pDy8H4sW

I have been googling solutions and no luck. Tried uninstalling all visual studio related folders, and reinstalling with admin privileges.
I am installing only the visual studio core , and the visual studio for unity workloads. The bottom bar under download won't get past zero.

I want to install visual studio so I can use it with Unity instead of monodevelop, but no luck after endless tries. I cant post on the visual studio community group because I would need to access it from the program that Im unable to install.

I know there are similar questions but none of those solutions seems to apply to my problem, plus my error log is different . Thank you for your help.

答: It says another installation already in progress, it sometimes does that when windows is installing updates, make sure that there is no windows update going on, restart your pc and try again.</p>

Body:
This is the error log

enter code here

https://pastebin.com/pDy8H4sW

I have been googling solutions and no luck. Tried uninstalling all visual studio related folders, and reinstalling with admin privileges.
I am installing only the visual studio core , and the visual studio for unity workloads. The bottom bar under download won't get past zero.

I want to install visual studio so I can use it with Unity instead of monodevelop, but no luck after endless tries. I cant post on the visual studio community group because I would need to access it from the program that Im unable to install.

I know there are similar questions but none of those solutions seems to apply to my problem, plus my error log is different . Thank you for your help.


问:
IEnumerable from IEnumerator
I have writen about custom IEnumerator. Whats the simplest way to make IEnumerable from it ? Ideal solution (one line of code) would be if there was some class for that purpose. Or do I have to create my own ?

答:
What I do is make a class that implements both IEnumerator and IEnumerable. Make GetEnumerator() return itself and you can iterate it like normal.</p>

```<code>public class MyClassEnumerator : IEnumerator<MyClass>, IEnumerable<MyClass>
{
    public MyClass Current { get; private set; }

    object IEnumerator.Current => Current;

    public void Reset()
    {
        ...
    }

    public bool MoveNext()
    {
        ...
    }

    public IEnumerator<MyClass> GetEnumerator()
    {
        return this;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this;
    }

    public void Dispose()
    {
        ...
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: IEnumerable from IEnumerator

Body:
What I do is make a class that implements both IEnumerator and IEnumerable. Make GetEnumerator() return itself and you can iterate it like normal.

public class MyClassEnumerator : IEnumerator<MyClass>, IEnumerable<MyClass>
{
    public MyClass Current { get; private set; }

    object IEnumerator.Current => Current;

    public void Reset()
    {
        ...
    }

    public bool MoveNext()
    {
        ...
    }

    public IEnumerator<MyClass> GetEnumerator()
    {
        return this;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this;
    }

    public void Dispose()
    {
        ...
    }
}


问:
Byte skipping when casting occurs
I have a struct that looks like this

```<code>struct message_header
{
    unsigned long msg_num : 32;            //0-3    message id
    unsigned long msg_len : 32;            //4-7    message length
    unsigned long hardware_version : 16;   //8-9    hardware version
    unsigned long sender_location : 32     //10-13  location
    unsigned long message;                 //14 ... messages
};

message_header * msg_ptr;
</code>```

After receiving the character array (recvbuf) from recvfrom function, i will do
reinterpret_cast,

msg_ptr = reinterpret_cast<message_header*>(recvbuf)

However, after my simulator (from linux, VM) sends the data, and my receiver (the struct is in the receiver) (on windows), the output data does not tally.

Assuming the data send from the simulator is:

msg num : 1010

msg len : 20

hardware version: 1

location: 25

messages: //rest of the bytes

Packets from the wireshark shows:

00 00 03 F2

00 00 00 14

00 01 00 00

00 19 00 00

...

The output print is:

msg num : 1010

msg len : 20

hardware version: 1

location: 1638400

After much debugging, I noticed that during the cast, after hardware version, the 00 00 after the 01 was either discarded, or skipped, i am not sure which as I can't find a way to determine it, and the next 4 bytes of 00 19 00 00 was cast into my sender_location.

All the message types and length, from the sender is build base on the sender's design specification, and the hardware version on the sender is an unsigned short.

I have read up on the following question and answers

Fields in a struct skipping bytes

#pragma pack effect

And i have tried but to no avail, please advise.

答:
The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

I did not understand what this means at first, till i re-read over and over again, i realize that my hardware version is using a long of 4 bytes, rather than i should be using a short of 2 bytes instead, another question comes to mind, which is why is the bitfield limitation not working, or i  may have understand it wrongly.

So after changing it from long to short, and with #pragma pack(1), the cast works fine now.

And how i found out was by using offsetof function to check

cout << offsetof (message_header, msg_num) << endl;

cout << offsetof (message_header, msg_len) << endl;

cout << offsetof (message_header, hardware_version) << endl;

cout << offsetof (message_header, sender_location ) << endl;

cout << offsetof (message_header, message) << endl;

And the printout is, then i realize the bitfield was not working at all.

0

4

8

12

16

After changing hardware_version, from long to short, AND without #pragma pack(1), the printout is still similar to the one above, however, once #pragma pack(1) is enabled, the printout is

0

4

6

10

14

Title: Byte skipping when casting occurs

Body:
I have a struct that looks like this

struct message_header
{
    unsigned long msg_num : 32;            //0-3    message id
    unsigned long msg_len : 32;            //4-7    message length
    unsigned long hardware_version : 16;   //8-9    hardware version
    unsigned long sender_location : 32     //10-13  location
    unsigned long message;                 //14 ... messages
};

message_header * msg_ptr;

After receiving the character array (recvbuf) from recvfrom function, i will do
reinterpret_cast,

msg_ptr = reinterpret_cast<message_header*>(recvbuf)

However, after my simulator (from linux, VM) sends the data, and my receiver (the struct is in the receiver) (on windows), the output data does not tally.

Assuming the data send from the simulator is:

msg num : 1010

msg len : 20

hardware version: 1

location: 25

messages: //rest of the bytes

Packets from the wireshark shows:

00 00 03 F2

00 00 00 14

00 01 00 00

00 19 00 00

...

The output print is:

msg num : 1010

msg len : 20

hardware version: 1

location: 1638400

After much debugging, I noticed that during the cast, after hardware version, the 00 00 after the 01 was either discarded, or skipped, i am not sure which as I can't find a way to determine it, and the next 4 bytes of 00 19 00 00 was cast into my sender_location.

All the message types and length, from the sender is build base on the sender's design specification, and the hardware version on the sender is an unsigned short.

I have read up on the following question and answers

Fields in a struct skipping bytes

#pragma pack effect

And i have tried but to no avail, please advise.


问:
what is the difference between spring data save and hibernate save?
what is the difference between spring data save and hibernate save? Do they work in same way?

答:
Hibernate's Session.save() is a proprietary Hibernate operation that doesn't exist in JPA. It basically does the same thing as EntityManager.persist(), except it guarantees that the ID is generated and returns it. The same cascades are not applied though, since Hibernate has a proprietary SAVE cascade option that of course does exist in JPA.

Spring-data-jpa's SimpleJpaRepository's save operation either calls EntityManager.persist(), if the entity is considered new, or EntityManager.merge(), if the entity is not considered new.

So no, they're not the same thing, and don't work the same way.

ContentLicense: CC BY-SA 4.0


问:
Sort a string alphabetically using a function
Imagine you were given a string and you had to sort that string alphabetically using a function. Example:

```<code>sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'
</code>```

What would be the best way to do this?

答:
Newer browsers support String.prototype.localeCompare() which makes sorting utf8 encoded strings really simple. Note that different languages may have a different order of characters. More information on MDN about localCompare.

function sortAlphabet(str) {
  return [...str].sort((a, b) => a.localeCompare(b)).join("");
}

console.log(sortAlphabet("drpoklj")); // Logs: "djklopr"```
</div>
</div>
</p>
<p>If you only have to support ascii strings then the default sorting implementation will do.</p>
<pre class="lang-js prettyprint-override"><code>function sortAlphabet(str) {
  return [...str].sort().join("");
}
</code>```

Body:
Imagine you were given a string and you had to sort that string alphabetically using a function. Example:

sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'

What would be the best way to do this?

Body:
Newer browsers support String.prototype.localeCompare() which makes sorting utf8 encoded strings really simple. Note that different languages may have a different order of characters. More information on MDN about localCompare.

function sortAlphabet(str) {
  return [...str].sort((a, b) => a.localeCompare(b)).join("");
}

console.log(sortAlphabet("drpoklj")); // Logs: "djklopr"

If you only have to support ascii strings then the default sorting implementation will do.

function sortAlphabet(str) {
  return [...str].sort().join("");
}


问:
Is there an XML Editor with grid view similar to that of XMLSpy?
I have been testing out a few different xml editor/viewers and I can't seem to find any that have a feature that is comparable to XMLSpy's grid view.  Another feature I'd like to find, but is a deal breaker would be XMLSpy's ability to "Copy as Structured Text".  Haven't found anything similar to this either in the free varieties of xml editors/viewers.

Anybody ever worked with a free xml editor that has the grid view option like XMLSpy?

答:
There appears to be a product called XML Marker that claims to have this as well.

http://symbolclick.com/

Never tried it.


问:
Difference Between 2 Ways to Start Async Task Without Waiting in ASP.NET MVC
An asynchronous method like below should be executed without waiting in a ASP.NET MVC website.

```<code>public async Task DoStaff()
{
    // business logic here
}
</code>```

And we found two solutions to accomplish this and both work on our testbed:

Solution 1:

```<code>public void DoStaffWrapper()
{
    DoStaff();
    // clean up
}

public ActionResult Caller()
{
    DoStaffWrapper();
    // return blah blah blah;
}
</code>```

Solution 2:

```<code>public async Task DoStaffWrapperAsync()
{
    await DoStaff();
    // clean up
}

public ActionResult Caller()
{
    Task.Run(() => DoStaffWrapperAsync());
    // return blah blah blah;
}
</code>```

So what is the difference between them? which is the better and why? Any benefits?

答:
Unless you have precise control over the lifecycle of your IIS pool (or unless you're not actually running on IIS), you should use QueueBackgroundWorkItem to launch your fire-and-forget tasks. It makes sure the runtime is able to track them, and won't terminate prematurely the process.

```<code>HostingEnvironment.QueueBackgroundWorkItem(_ => DoStaff());
</code>```

If for some reason you don't want to use this method, or don't need it, there's an important difference between the two ways of calling the async method:

DoStaff() will run synchronously on the current thread until an await statement is found, then it will yield control over the thread (and whatever you have after DoStaff will be able to execute. Also, the mehtod will execute inside of ASP.NET's synchronization context, so you will run into trouble if you're not using .ConfigureAwait(false) whenever awaiting calls inside of it.

Task.Run(() => DoStaffWrapperAsync()) will entirely run asynchronously, and in a separate context (so you won't run into the aforementioned issue).

To put it simple, take the following method:

```<code>public Task DoStaff()
{
    Thread.Sleep(1000);

    await AnotherMethodAsync();

    Thread.Sleep(1000);
}
</code>```

If you call DoStaff, the call will be blocking for one second. If you call Task.Run(() => DoStaff()), the call will return immediately. But if there's no significant amount of work before the first await, then you'll be jumping to a new thread for no practical gain.

Body:
An asynchronous method like below should be executed without waiting in a ASP.NET MVC website.

public async Task DoStaff()
{
    // business logic here
}

And we found two solutions to accomplish this and both work on our testbed:

Solution 1:

public void DoStaffWrapper()
{
    DoStaff();
    // clean up
}

public ActionResult Caller()
{
    DoStaffWrapper();
    // return blah blah blah;
}

Solution 2:

public async Task DoStaffWrapperAsync()
{
    await DoStaff();
    // clean up
}

public ActionResult Caller()
{
    Task.Run(() => DoStaffWrapperAsync());
    // return blah blah blah;
}

So what is the difference between them? which is the better and why? Any benefits?

Body:
Unless you have precise control over the lifecycle of your IIS pool (or unless you're not actually running on IIS), you should use QueueBackgroundWorkItem to launch your fire-and-forget tasks. It makes sure the runtime is able to track them, and won't terminate prematurely the process.

HostingEnvironment.QueueBackgroundWorkItem(_ => DoStaff());

If for some reason you don't want to use this method, or don't need it, there's an important difference between the two ways of calling the async method:

DoStaff() will run synchronously on the current thread until an await statement is found, then it will yield control over the thread (and whatever you have after DoStaff will be able to execute. Also, the mehtod will execute inside of ASP.NET's synchronization context, so you will run into trouble if you're not using .ConfigureAwait(false) whenever awaiting calls inside of it.

Task.Run(() => DoStaffWrapperAsync()) will entirely run asynchronously, and in a separate context (so you won't run into the aforementioned issue).

To put it simple, take the following method:

public Task DoStaff()
{
    Thread.Sleep(1000);

    await AnotherMethodAsync();

    Thread.Sleep(1000);
}

If you call DoStaff, the call will be blocking for one second. If you call Task.Run(() => DoStaff()), the call will return immediately. But if there's no significant amount of work before the first await, then you'll be jumping to a new thread for no practical gain.


问:
SignalR supplying authorization token
I'm struggling to decide how best to add authentication and authorisation to my SignalR service.

At the moment it is hosted in Owin alongside a WebApi2 web service. I use OAuth2 bearer tokens to authenticate with those, and it works perfectly. However, I wonder if they're suitable for SignalR?

My client is JavaScript based, and SignalR uses WebSockets if available. This means I can't use the Authorization header. I figured out that I can supply the token using the qs property before I connect. But of course an OAuth2 access token will expire (and relatively shortly in my implementation). I assume that updating the qs property won't make a difference once connected (particularly with web sockets).

I suppose my question is what is the best way to supply a security token, ticket, or any kind of authorization information to SignalR? Preferably a way that can be consistent on both my WebApi and SignalR, but I am looking to know how I should be doing it.

Thanks

答:
It's been sometime now - but we used to look for the auth cookie in the signalR request to ensure that only a signed in user can subscribe to signalr notifications.

It didn't handle the case where the token expired - since the cookie was checked only on connect. This wasn't a problem for us.

Title: SignalR supplying authorization token


问:
Laravel Update not working
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();
</code>```

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

```<code>$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();
</code>```

Can you help me why first code is not working.

答:
Model use to interact with table so all attributes which you need to store in DB you should need to define in your model as your Admin model should look like

```<code>   <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $fillable = ['name', 'is_delete'];
}
</code>```

You missing is_delete from your Model code.

Title: Laravel Update not working

Body:
I have table called admins and model called Admin.

When i try to update the records it fails every time with one field.

$admindetail = Admin::find($id);
$admindetail->fill(['is_delete'=>1])->save();

Above code is not updating record in DB. datatype for is_delete is tinyint.

If i update name field it works with the same code like

$admindetail = Admin::find($id);
$admindetail->fill(['name'=>'abc'])->save();

Can you help me why first code is not working.

Body:
Model use to interact with table so all attributes which you need to store in DB you should need to define in your model as your Admin model should look like

   <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $fillable = ['name', 'is_delete'];
}

You missing is_delete from your Model code.


问:
Doctrine - Unable to persist entity with composite key
I'm using Doctrine with YML mappings. I have two entities. One Group entity and one User entity.

I'm trying to set it up so Users have unique names within a group.

I can create a User, assign it a Group, and save it to the DB. But when I try to create a User with the same name and a different Group, then I get an error saying the unique constraint on name is violated.

Why can't I persist that User?

Their mappings look like this:

```<code>Entity\Group:
    type: entity
    table: groups
    id:
        id:
            type: guid
            nullable: false
            id: true
            generator:
                strategy: AUTO
    fields:
        name:
            type: text
            nullable: true

Entity\User:
    type: entity
    table: users
    id:
        group:
            associationKey: true
            nullable: false
        name:
            type: string
    manyToOne:
        Group:
            targetEntity: Entity\Group
            joinColumn:
                name: group
                referencedColumnName: id
</code>```

答:
I eventually figured this out. I was confusing Doctrine.

The non-standard thing was that I'm using a capitalized parameter name to represent an object and changing that to lowercase for the table column. I did this in the manyToOne: section using name:.

The documentation doesn't really do this, so I didn't know that I still had to reference the capitalized property name in the id: section and separately define the column name there.

So, I changed the User mapping to this:

```<code>Entity\User:
    type: entity
    table: users
    id:
        Group:
            column: group
            associationKey: true
            nullable: false
        name:
            type: string
    manyToOne:
        Group:
            targetEntity: Entity\Group
            joinColumn:
                name: group
                referencedColumnName: id
</code>```

Body:
I'm using Doctrine with YML mappings. I have two entities. One Group entity and one User entity.

I'm trying to set it up so Users have unique names within a group.

I can create a User, assign it a Group, and save it to the DB. But when I try to create a User with the same name and a different Group, then I get an error saying the unique constraint on name is violated.

Why can't I persist that User?

Their mappings look like this:

Entity\Group:
    type: entity
    table: groups
    id:
        id:
            type: guid
            nullable: false
            id: true
            generator:
                strategy: AUTO
    fields:
        name:
            type: text
            nullable: true

Entity\User:
    type: entity
    table: users
    id:
        group:
            associationKey: true
            nullable: false
        name:
            type: string
    manyToOne:
        Group:
            targetEntity: Entity\Group
            joinColumn:
                name: group
                referencedColumnName: id

Body:
I eventually figured this out. I was confusing Doctrine.

The non-standard thing was that I'm using a capitalized parameter name to represent an object and changing that to lowercase for the table column. I did this in the manyToOne: section using name:.

The documentation doesn't really do this, so I didn't know that I still had to reference the capitalized property name in the id: section and separately define the column name there.

So, I changed the User mapping to this:

Entity\User:
    type: entity
    table: users
    id:
        Group:
            column: group
            associationKey: true
            nullable: false
        name:
            type: string
    manyToOne:
        Group:
            targetEntity: Entity\Group
            joinColumn:
                name: group
                referencedColumnName: id


问:
Need to delete all data after third colon of a string
i have a file say test.txt with the following contents

```<code>apple:orange:mango:123:1234:12345
</code>```

i want all data after third colon to be removed

Expected output

```<code>apple:orange:mango:
</code>```

Kinldy help

答:
using grep: IF last colon is required.

```<code>grep -oP '^.*?:.*?:.*?:' input
apple:orange:mango:
</code>```

If last colon is not required:

```<code>grep -oP '^.*?:.*?:[^:]+' input
apple:orange:mango
</code>```

Body:
i have a file say test.txt with the following contents

apple:orange:mango:123:1234:12345

i want all data after third colon to be removed

Expected output

apple:orange:mango:

Kinldy help

Body:
using grep: IF last colon is required.

grep -oP '^.*?:.*?:.*?:' input
apple:orange:mango:

If last colon is not required:

grep -oP '^.*?:.*?:[^:]+' input
apple:orange:mango


问:
Understanding .bind() in relation to arguments
I am reviewing some game code and I have a piece that I don't quite understand.

```<code>var game = (function(){

   // Start with our constructor
   function Game(){
        this.viewport = document.getElementById('viewport');
        this.ctx = this.viewport.getContext('2d');
    };

    Game.prototype.updateAnimation = function(t){

        // work out the delta time
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        // run relevent updates here

        // queue the next animation time.
        this.animationId = window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport );
    }

    // return game class
    return Game;

})();
</code>```

Then

```<code>// call new game object
var clientGame = new game();

// call event loop
clientGame.updateAnimation(new Date().getTime());
</code>```

When request window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport ); runs. How does it know the value of the paramter t. It seems to update each time, but I don't understand why. Can someone please explain whats going on? Thanks.

EDIT

There is a function attached to the Number prototype chain called fixed(). Here it is for clarity

```<code> Number.prototype.fixed = function(n) { n = n || 3; return parseFloat(this.toFixed(n)); };
</code>```

答:
First of all the code could be written better, there is no need to bind the function all over again each time, it's enough to do it once (for example during the initialization of the object)

Secondly, the function requestAnimationFrame accepts one argument only, so there is no meaning to the second one, and the first argument is the t which sent by the browser to the callback.

The method .bind doesn't change the function arguments (maybe except arguments.callee though this is redundant) but only the context of the function so the first argument stays t (the timestamp)

more info https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

Edit

So the user is using some polyfill which allows to send two arguments to requestAnimationFrame

Body:
I am reviewing some game code and I have a piece that I don't quite understand.

var game = (function(){

   // Start with our constructor
   function Game(){
        this.viewport = document.getElementById('viewport');
        this.ctx = this.viewport.getContext('2d');
    };

    Game.prototype.updateAnimation = function(t){

        // work out the delta time
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        // run relevent updates here

        // queue the next animation time.
        this.animationId = window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport );
    }

    // return game class
    return Game;

})();

Then

// call new game object
var clientGame = new game();

// call event loop
clientGame.updateAnimation(new Date().getTime());

When request window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport ); runs. How does it know the value of the paramter t. It seems to update each time, but I don't understand why. Can someone please explain whats going on? Thanks.

EDIT

There is a function attached to the Number prototype chain called fixed(). Here it is for clarity

 Number.prototype.fixed = function(n) { n = n || 3; return parseFloat(this.toFixed(n)); };


问:
Error while iterating with *ngFor in angular2
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

```<code>return this.http.post(this.url,params)
        .map(res => res.json())
</code>```

Assigning response to travelGuides

```<code>.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}
</code>```

JSON

```<code>{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}
</code>```

here is *ngFor im trying

```<code> <div *ngFor="let travelguide of travelGuides">
   {{travelguide.TravelGuide.Category}}
 </div>
</code>```

but getting this

```<code>Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

also tried

```<code> <div *ngFor="let travelguide of travelGuides.TravelGuide">
   {{travelguide.Category}}
 </div>
</code>```

for this getting error

```<code>Cannot read property 'TravelGuide' of undefined
</code>```

答:
Assuming travelGuides is assigned asynchronously, your code should be like

```<code><div *ngFor="let travelguide of travelGuides?.TravelGuide">
 {{travelguide?.Category}}
</div>
</code>```

More info on safe navigation operator (?): Why we use "?" operator in template binding in angular 2

or

```<code><div *ngIf="travelGuides && travelGuides.length && travelGuides.length > 0">
  <div *ngFor="let travelguide of travelGuides.TravelGuide">
   {{travelguide.Category}}
  </div>
</div>
</code>```

Body:
I have json response like, Im trying to iterate over json response but it is giving errors

I don't know if angular2 don't suport iteration like this as I'm new to angular2

serive call

return this.http.post(this.url,params)
        .map(res => res.json())

Assigning response to travelGuides

.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData;
}

JSON

{
  "resultCode": 1,
  "resultData": {
    "TravelGuide": [
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      },
      {
        "Help": "TravelGuide",
        "IsDocument": "1",
        "EventType": "Success",
        "Category": "HOTEL",
        "SupplierType": "SUPTYPE-0-0-11",
        "HotelSrno": "HOTEL-0-0-62",
        "Name": "Radisson Blu Plaza Bangkok",
        "Optional": "0",
        "Fileupload1": "hotel.jpg",
        "FileUpload1Path": "/Documents/MasterData/HOTEL/HOTEL-0-0-62/hotel.jpg"
      }
    ],
    "TravelGuide_Img": [
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Radisson Blu ",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1",
        "AltText": "Radisson Blu ",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-1/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Radisson Blu Plaza Bangkok",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-62",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-1"
      },
      {
        "Help": "TravelGuide_Img",
        "IsDocument": "0",
        "EventType": "Success",
        "Category": "HOTEL",
        "Name": "hotelimage.jpg",
        "TextoverImg": "Text Over Image",
        "Textbox2": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2",
        "AltText": "Text Over Image",
        "path": "/Documents/MasterData/HOTELIMG/HOTELIMG-0-0-2/hotelimage.jpg",
        "ImageCategoryName": "IMGCATG",
        "HotelName": "Pullman Bangkok Hotel G",
        "ImageSize": "Medium",
        "ImageResolution": "IMGSIZE-0-0-1",
        "ImageCategory": "IMGCATG",
        "Hotel": "HOTEL-0-0-63",
        "ImageSize_srno": "IMGSIZE-0-0-1",
        "ImageResolution1": "RESOLUTIO-0-0-2"
      }
    ]
  }
}

here is *ngFor im trying

   {{travelguide.TravelGuide.Category}}

but getting this

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

also tried

   {{travelguide.Category}}

for this getting error

Cannot read property 'TravelGuide' of undefined

Body:
Assuming travelGuides is assigned asynchronously, your code should be like

<div *ngFor="let travelguide of travelGuides?.TravelGuide">
 {{travelguide?.Category}}
</div>

More info on safe navigation operator (?): Why we use "?" operator in template binding in angular 2

or

<div *ngIf="travelGuides && travelGuides.length && travelGuides.length > 0">
  <div *ngFor="let travelguide of travelGuides.TravelGuide">
   {{travelguide.Category}}
  </div>
</div>


问:
Android application must not run on rooted devices
I'm writing an application that must not run on rooted devices. I want to store some secure data and which is possible only on non-rooted devices as nobody can access files in /data/data/package-name.

Does anyone know:

1) Is it possible to prevent the installation of an application on rooted devices? I read something about the "copy-protection mechanism" of Android Market. This feature seems to be outdated and replaced by the licensing feature. However, licensing is only possible for paid application and mine is free...

2) Is it possible to check programmatically whether a device is rooted or not? If it would be possible to do so I could simply stop the application if the device is rooted.

Any help regarding this topic is appreciated!

答:
1) no. how would you deny installation? why would a rooted device deny installation of something the user wants to install on the fs? being the whole point of rooting that you can make the device do basically whatever.

2) no. not for your purposes. you can check if you can gain root for your application through the usual methods. so you can make a check for a positive but you cannot prove programmatically that it is not rooted, from within your app.

also, what you are asking if you can make perfect copy protection drm system - you might also be missing the point that the user can alter your application, removing your root check. if you have a checksum/crc check of some kind, the user can fake the result of that as well.


问:
Adding global exception handling to ASP.NET
I work on a rather large web site. We currently have 4 web servers and an active passive db cluster running ASP.NET 2.0 with C#. Currently our exception handling is not trapping the correct exception being thrown. I have heard it is because Server.GetLastError() is not thread safe (note: we currently do not use Server.GetLastError().GetBaseException() which might be why we are not getting the correct error).

We are starting a project to trap exact exceptions so we can actually see the root cause of the error and I’m trying to find the best way to do it.

Our options are:

Go through all of our classes/methods(hundreds, if not thousands) to add try/catch/finally blocks to trap the correct exception.

Figure out a way to properly handle the exceptions in the global.asax.

So I guess my questions are:

Is Server.GetLastError() thread safe?

If two exceptions are thrown at the same time, will both be logged?

Is there a better way to handle this than what I have listed?

答:
I believe that you should not alter the initial application at all. You should create and register at web.config an IHttpModule that hooks on Error event to log recursively the exception thrown and it's inner exceptions.

Further Reading:

MSDN - Using HTTP Modules and Handlers to Create Pluggable ASP.NET Components

DotNetSlackers - ELMAH - Error Logging Modules And Handlers

CodeProject - ELMAH - Error Loggin Module and Handler For unhandled errors in asp.net

OwnerDisplayName: Diadistis

LastEditorDisplayName: Diadistis


问:
Is there a tool that will format MySQL output?
MySQL's command line output is very unreadable.  I know about \G, but sometimes it's not me running the query.  For example, if somebody emails or IMs me query output, or if PHPUnit is auto printing output.

Is there some light weight online tool already made that I can drop in a MySQL command line output and it display it in a readable format?

答:
Except from forcing them to use the --table option when using mysql, I don't know :)

I'm going to have a look if such a tool exists.


问:
select given column in delimited text file using regex
I have a text file like below

```<code>Name     Phone
ABCDE    12345
FGHIJ    67890
KLMNO    23876
</code>```

I want to select only values under Name ( or values under Phone) using RegEx
How should I approach this?

Thanks

答:
Do values under name only have uppercase letters? If this is the case, then:

[A-Z]+ - will only give you names.

[0-9]+ - will only give you phone numbers.

Square brackets are called character classes, basically when you say [abc] this means "Find me text which has a or b or c", notation with - in it, [A-Z] takes ASCII code of A, and ASCII code of Z, and basically puts every ASCII character between these two values into brackets, so you would have every uppercase alphabet letter in brackets.

Plus sign (+) after square brackets means: "Find occurrences of square brackets one or more time".

Note:

Plus sign doesn't only work for square brackets. For example if you say a+ this would find you text where letter a appears one or more time.

Body:
I have a text file like below

Name     Phone
ABCDE    12345
FGHIJ    67890
KLMNO    23876

I want to select only values under Name ( or values under Phone) using RegEx
How should I approach this?

Thanks


问:
C# Console Application, search for matching string[] from two text files
I have two text files: animal.txt that has

```<code>number,letter,color,animal
1,a,green,alligator
2,b,brown,bear
3,c,black,cat
4,d,white,dog
5,e,pink,elephant
</code>```

and habit.txt that has

```<code>colour,animal,found,diet
green,alligator,swamp,fish
green,alligator,swamp,bird
brown,bear,forest,fruit
black,cat,home,catfood
white,dog,home,dogfood
pink,elephant,space,spacefruit
</code>```

My code so far asks for a number and a letter. and searches the text file using string[] and split.

```<code>class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        bool lineFound = false;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                if ((number == words[1]) && (letter == words[0]))
                {
                    Console.WriteLine(line);
                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

        }
            while (!lineFound);
</code>```

depending on the input it'll display the line with color and animal.
How do I make it so that it will search another file, habit.txt for matching lines found in animal.txt. for example input can be '1' and 'a' the console will display

```<code>green,alligator,swamp,fish
green,alligator,swamp,bird
</code>```

答:
```<code>class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        // this assumes that there will always be only one record??
        bool lineFound;

        string animalType = null;
        string animalColor = null;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                // your example data shows the number in position 0 and the letter in position 1
                if ((number == words[0]) && (letter == words[1]))
                {
                    Console.WriteLine(line);

                    // assign the found animals type and color to use later

                    animalType = words[3];
                    animalColor = words[2];

                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

            System.IO.StreamReader habitatFile = new System.IO.StreamReader("habitat.txt");
            // line is being used by two different streams and can create unexpected behavior so instead create a seperate variable
            while ((line = habitatFile.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                // your example data shows the number in position 0 and the letter in position 1
                if ((animalColor == words[0]) && (animalType == words[1]))
                {
                    Console.WriteLine(line);
                }
            }

            habitatFile.Close();
        }
        while (!lineFound);
    }
}
</code>```

But I would consider looking at making these line of text into classes and seeing what things you can make easier (for example, what if you can search instead for animals by color?)

```<code>public class Animal
{
    public int Number { get; set; }

    public string Letter { get; set; }

    public string Color { get; set; }

    // CSV file has listed as 'animal'
    public string Name { get; set; }
}

public class Habitat
{
    public string Color { get; set; }

    // CSV file has listed as 'animal'
    public string Name { get; set; }

    public string Found { get; set; }

    public string Diet { get; set; }

}
</code>```

Body:
I have two text files: animal.txt that has

number,letter,color,animal
1,a,green,alligator
2,b,brown,bear
3,c,black,cat
4,d,white,dog
5,e,pink,elephant

and habit.txt that has

colour,animal,found,diet
green,alligator,swamp,fish
green,alligator,swamp,bird
brown,bear,forest,fruit
black,cat,home,catfood
white,dog,home,dogfood
pink,elephant,space,spacefruit

My code so far asks for a number and a letter. and searches the text file using string[] and split.

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        bool lineFound = false;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                if ((number == words[1]) && (letter == words[0]))
                {
                    Console.WriteLine(line);
                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

        }
            while (!lineFound);

depending on the input it'll display the line with color and animal.
How do I make it so that it will search another file, habit.txt for matching lines found in animal.txt. for example input can be '1' and 'a' the console will display

green,alligator,swamp,fish
green,alligator,swamp,bird

Body:
class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        // this assumes that there will always be only one record??
        bool lineFound;

        string animalType = null;
        string animalColor = null;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                // your example data shows the number in position 0 and the letter in position 1
                if ((number == words[0]) && (letter == words[1]))
                {
                    Console.WriteLine(line);

                    // assign the found animals type and color to use later

                    animalType = words[3];
                    animalColor = words[2];

                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

            System.IO.StreamReader habitatFile = new System.IO.StreamReader("habitat.txt");
            // line is being used by two different streams and can create unexpected behavior so instead create a seperate variable
            while ((line = habitatFile.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                // your example data shows the number in position 0 and the letter in position 1
                if ((animalColor == words[0]) && (animalType == words[1]))
                {
                    Console.WriteLine(line);
                }
            }

            habitatFile.Close();
        }
        while (!lineFound);
    }
}

But I would consider looking at making these line of text into classes and seeing what things you can make easier (for example, what if you can search instead for animals by color?)

public class Animal
{
    public int Number { get; set; }

    public string Letter { get; set; }

    public string Color { get; set; }

    // CSV file has listed as 'animal'
    public string Name { get; set; }
}

public class Habitat
{
    public string Color { get; set; }

    // CSV file has listed as 'animal'
    public string Name { get; set; }

    public string Found { get; set; }

    public string Diet { get; set; }

}


答:
I think if you are assigning the whole response to travelGuides, it should be ,

```<code> <div *ngFor="let travelguide of travelGuides?.resultData.TravelGuide">
   {{travelguide.Category}}
 </div>
</code>```

EDIT

Change the assignment part as,

```<code>.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData.TravelGuide;
}
</code>```

and HTML

```<code><div *ngFor="let travelguide of travelGuides?.TravelGuide">
 {{travelguide?.Category}}
</div>
</code>```

Title: Error while iterating with *ngFor in angular2

Body:
I think if you are assigning the whole response to travelGuides, it should be ,

 <div *ngFor="let travelguide of travelGuides?.resultData.TravelGuide">
   {{travelguide.Category}}
 </div>

EDIT

Change the assignment part as,

.subscribe(travelGuides => {
        this.travelGuides = travelGuides.resultData.TravelGuide;
}

and HTML

<div *ngFor="let travelguide of travelGuides?.TravelGuide">
 {{travelguide?.Category}}
</div>


问:
Why "LC_ALL=C" cannot speed up "bzgrep"
In terms of the cases that covers ASCII only, we could use LC_ALL=C to significantly speed up the grep procedure.
Since bzgrep is a lot similar to grep, I tried to adopt this as well. Turns out it didn't help much.
The command lines I used are listed as following:

```<code>$ time bzgrep Debug 001.log.bz2 | sed -n '/^09:00/ , /^09:30/p' | grep "Pattern1.*Pattern2" > /dev/null
$ time LC_ALL=C bzgrep Debug 001.log.bz2 | sed -n '/^09:00/ , /^09:30/p' | grep "Pattern1.*Pattern2" > /dev/null
</code>```

Update:

```<code>$ time bzgrep

real    1m51.686s
user    1m52.310s
sys     0m6.682s

$ time LC_ALL=C bzgrep
real    1m51.835s
user    1m52.455s
sys     0m6.738s

$ time grep

real    1m9.553s
user    1m3.189s
sys     0m2.120s

$ time LC_ALL grep

real    0m4.136s
user    0m3.187s
sys     0m0.946s
</code>```

答:
Assuming bzgrep isn't ignoring LC_ALL entirely, you're probably seeing a performance bottleneck in which the decompression performance limits the speed at which the actual grep code gets the data in the first place, thus making the speed of the actual grep code largely moot.

To use a car analogy, imagine that you have two groups of car washers—one that can wash a car in a minute, and another that takes five minutes.  You have ten cars to wash.  The first team washes ten cars in ten minutes; the other team washes ten cars in 50 minutes.

Now suppose that you have a fire marshall who doesn't like having that many cars on the property at once and decides to solve the problem by allowing exactly one car to enter the car wash, precisely at the top of every hour.  Thus, each team finishes with its car and then waits either 55 or 59 minutes for the next one.

In that scenario, the first team gets a car and washes it in a minute, waits an hour, washes another car, etc.  They start washing the tenth car nine hours after they started washing the first, so it takes nine hours and one minute in total.  The second team does the same thing, but takes five minutes to wash the last car, so it takes then nine hours and five minutes in total.

In much the same way, if the grep part is dramatically faster than the decompression part, then assuming you have a multicore CPU, the total time depends only upon the time required to decompress the data plus the time to grep the very last chunk of data.

Title: Why "LC_ALL=C" cannot speed up "bzgrep"

Body:
In terms of the cases that covers ASCII only, we could use LC_ALL=C to significantly speed up the grep procedure.
Since bzgrep is a lot similar to grep, I tried to adopt this as well. Turns out it didn't help much.
The command lines I used are listed as following:

$ time bzgrep Debug 001.log.bz2 | sed -n '/^09:00/ , /^09:30/p' | grep "Pattern1.*Pattern2" > /dev/null
$ time LC_ALL=C bzgrep Debug 001.log.bz2 | sed -n '/^09:00/ , /^09:30/p' | grep "Pattern1.*Pattern2" > /dev/null

Update:

$ time bzgrep

real    1m51.686s
user    1m52.310s
sys     0m6.682s

$ time LC_ALL=C bzgrep
real    1m51.835s
user    1m52.455s
sys     0m6.738s

$ time grep

real    1m9.553s
user    1m3.189s
sys     0m2.120s

$ time LC_ALL grep

real    0m4.136s
user    0m3.187s
sys     0m0.946s


问:
Populating dropdown lists using Ajax
Total noob to ajax here, how close am I with this syntax? I want the second dropdown box to be dependent on the first drop down box. I know this can't be the easiest way to solve this problem so any help is appreciated. acura.txt is a text file with markup to make another dropdown list. Thanks for your help everyone!

JavaScript:

```<code>function loadXMLDoc() {
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("acura").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "acura.txt", true);
    xmlhttp.send();
}
</code>```

HTML:

```<code><select id="stateinjured">
    <option selected="selected">Select your state</option>
    <option id="acura" onClick="loadMXLDOC">Acura</option>
    <option id="bmw">BMW</option>
    <option id="audi">Audi</option>
    <option id="benz">Benz</option>
</select>
</code>```

答:
It's not going to work to stuff a <select> tag (with its own <option> contents, presumably) into the content of an <option> tag. That's what your code will attempt to do now.

This code here:

```<code>if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementById("acura").innerHTML=xmlhttp.responseText;
  }
</code>```

The element whose "id" value is "acura" is one of the <option> tags in the <select> on the page. Thus, if that response text is just a <select>, it's going to go in the wrong place.

Maybe you just want another  on the page, or something; it depends on what it's supposed to look like.

Another thing: you don't want to pick up the "click" event on the <option>. It's possible for an option to be selected (by the user) without any "clicks" taking place. Probably you should track the "change" event on the <select> tag, and check the value in the handler.

Title: Populating dropdown lists using Ajax

Body:
Total noob to ajax here, how close am I with this syntax? I want the second dropdown box to be dependent on the first drop down box. I know this can't be the easiest way to solve this problem so any help is appreciated. acura.txt is a text file with markup to make another dropdown list. Thanks for your help everyone!

JavaScript:

function loadXMLDoc() {
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("acura").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "acura.txt", true);
    xmlhttp.send();
}

HTML:

<select id="stateinjured">
    <option selected="selected">Select your state</option>
    <option id="acura" onClick="loadMXLDOC">Acura</option>
    <option id="bmw">BMW</option>
    <option id="audi">Audi</option>
    <option id="benz">Benz</option>
</select>

Body:
It's not going to work to stuff a <select> tag (with its own <option> contents, presumably) into the content of an <option> tag. That's what your code will attempt to do now.

This code here:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
  document.getElementById("acura").innerHTML=xmlhttp.responseText;
  }

The element whose "id" value is "acura" is one of the <option> tags in the <select> on the page. Thus, if that response text is just a <select>, it's going to go in the wrong place.

Maybe you just want another <span> on the page, or something; it depends on what it's supposed to look like.

Another thing: you don't want to pick up the "click" event on the <option>. It's possible for an option to be selected (by the user) without any "clicks" taking place. Probably you should track the "change" event on the <select> tag, and check the value in the handler.


问:
when change exec-opt native.cgroupdriver to "cgroupfs"，docker can not run correct?
```<code>my os version : centos7.3
kenerl version : 3.10.0-514.16.1.el7.x86_64
docker version : 1.12.6
</code>```

I modify the config file "/lib/systemd/system/docker.service" ,after change the option "--exec-opt native.cgroupdriver" from systemd to cgroupfs. I find the docker can not run any images!

```<code>[root@surenode2 system]# cat /lib/systemd/system/docker.service |grep cgroup
          --exec-opt native.cgroupdriver=cgroupfs \
[root@surenode2 system]# docker images | grep mysql
docker.io/mysql     latest              e799c7f9ae9c        3 weeks ago         407.3 MB
[root@surenode2 system]# docker run -p 3307:3307 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
3395c8d505d3fc20d39e25c510a090649f9f447bce985028ea7274e79183d077
/usr/bin/docker-current: Error response from daemon: invalid header field value "oci runtime error: container_linux.go:247: starting container process caused \"process_linux.go:334: running prestart hook 1 caused \\\"error running hook: exit status 1, stdout: , stderr: \\\"\"\n".
</code>```

And,if I change exec-opt native.cgroupdriver to systemd ,Docker can run any images..

答:
Docker 1.12.6 ("community edition") is EOL and no longer supported;

We can install the latest docker version refer to 'https://docs.docker.com/engine/installation/linux/centos/'.

When using the latest docker version ,this issue is no longer reproduce !

```<code>[root@surenode1 ~]# docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.05.0-ce
Storage Driver: devicemapper
 Pool Name: docker-253:1-393732-pool
 Pool Blocksize: 65.54kB
 Base Device Size: 10.74GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 11.8MB
 Data Space Total: 107.4GB
 Data Space Available: 50.86GB
 Metadata Space Used: 581.6kB
 Metadata Space Total: 2.147GB
 Metadata Space Available: 2.147GB
 Thin Pool Minimum Free Space: 10.74GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 9048e5e50717ea4497b757314bad98ea3763c145
runc version: 9c2d8d184e5da67c95d601382adf14862e4f2228
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 3.10.0-514.16.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 3.702GiB
Name: surenode1
ID: NIYU:7BRX:JIQP:ZJMW:ZV6N:3336:5JSB:MWVQ:WR72:AO7J:QOEW:CHCA
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

[root@surenode1 ~]# docker version
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:10:29 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:10:29 2017
 OS/Arch:      linux/amd64
 Experimental: false

[root@surenode1 tmp]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               latest              e799c7f9ae9c        3 weeks ago         407MB
[root@surenode1 tmp]# ps -ef | grep docker
root     10173     1  1 17:31 ?        00:00:03 /usr/bin/dockerd **--exec-opt native.cgroupdriver=cgroupfs**
root     10177 10173  0 17:31 ?        00:00:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root     10535  9634  0 17:34 pts/0    00:00:00 grep --color=auto docker
[root@surenode1 tmp]# docker run -p 3307:3307 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
8f2d30ea779b872604bdf0d3d500de16e17d1409cdc5b2688893202bfcebbf16
[root@surenode1 tmp]#
</code>```

Also,We can find a bug description about this issue.

https://bugzilla.redhat.com/show_bug.cgi?id=1444662

Body:
my os version : centos7.3
kenerl version : 3.10.0-514.16.1.el7.x86_64
docker version : 1.12.6

I modify the config file "/lib/systemd/system/docker.service" ,after change the option "--exec-opt native.cgroupdriver" from systemd to cgroupfs. I find the docker can not run any images!

[root@surenode2 system]# cat /lib/systemd/system/docker.service |grep cgroup
          --exec-opt native.cgroupdriver=cgroupfs \
[root@surenode2 system]# docker images | grep mysql
docker.io/mysql     latest              e799c7f9ae9c        3 weeks ago         407.3 MB
[root@surenode2 system]# docker run -p 3307:3307 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
3395c8d505d3fc20d39e25c510a090649f9f447bce985028ea7274e79183d077
/usr/bin/docker-current: Error response from daemon: invalid header field value "oci runtime error: container_linux.go:247: starting container process caused \"process_linux.go:334: running prestart hook 1 caused \\\"error running hook: exit status 1, stdout: , stderr: \\\"\"\n".

And,if I change exec-opt native.cgroupdriver to systemd ,Docker can run any images..

Body:
Docker 1.12.6 ("community edition") is EOL and no longer supported;

We can install the latest docker version refer to 'https://docs.docker.com/engine/installation/linux/centos/'.

When using the latest docker version ,this issue is no longer reproduce !

[root@surenode1 ~]# docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.05.0-ce
Storage Driver: devicemapper
 Pool Name: docker-253:1-393732-pool
 Pool Blocksize: 65.54kB
 Base Device Size: 10.74GB
 Backing Filesystem: xfs
 Data file: /dev/loop0
 Metadata file: /dev/loop1
 Data Space Used: 11.8MB
 Data Space Total: 107.4GB
 Data Space Available: 50.86GB
 Metadata Space Used: 581.6kB
 Metadata Space Total: 2.147GB
 Metadata Space Available: 2.147GB
 Thin Pool Minimum Free Space: 10.74GB
 Udev Sync Supported: true
 Deferred Removal Enabled: false
 Deferred Deletion Enabled: false
 Deferred Deleted Device Count: 0
 Data loop file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 9048e5e50717ea4497b757314bad98ea3763c145
runc version: 9c2d8d184e5da67c95d601382adf14862e4f2228
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 3.10.0-514.16.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 3.702GiB
Name: surenode1
ID: NIYU:7BRX:JIQP:ZJMW:ZV6N:3336:5JSB:MWVQ:WR72:AO7J:QOEW:CHCA
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

[root@surenode1 ~]# docker version
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:10:29 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:10:29 2017
 OS/Arch:      linux/amd64
 Experimental: false

[root@surenode1 tmp]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               latest              e799c7f9ae9c        3 weeks ago         407MB
[root@surenode1 tmp]# ps -ef | grep docker
root     10173     1  1 17:31 ?        00:00:03 /usr/bin/dockerd **--exec-opt native.cgroupdriver=cgroupfs**
root     10177 10173  0 17:31 ?        00:00:00 docker-containerd -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --shim docker-containerd-shim --runtime docker-runc
root     10535  9634  0 17:34 pts/0    00:00:00 grep --color=auto docker
[root@surenode1 tmp]# docker run -p 3307:3307 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
8f2d30ea779b872604bdf0d3d500de16e17d1409cdc5b2688893202bfcebbf16
[root@surenode1 tmp]#

Also,We can find a bug description about this issue.

https://bugzilla.redhat.com/show_bug.cgi?id=1444662


问:
How to plotted graph save as a JPEG image in C#
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

```<code> private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }
</code>```

This is my part of .csv file data as follows;

```<code>Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE
</code>```

答:
I found the solution for this.This is working code for that.</p>

```<code> private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                this.chart1.SaveImage(dlg.FileName, ChartImageFormat.Jpeg);
            MessageBox.Show("Chart details Successful saved as jpeg image");
        }
</code>```

Body:
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

 private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }

This is my part of .csv file data as follows;

Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE

Body:
I found the solution for this.This is working code for that.

 private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                this.chart1.SaveImage(dlg.FileName, ChartImageFormat.Jpeg);
            MessageBox.Show("Chart details Successful saved as jpeg image");
        }


问:
Getting an error after initial firebase setup in Xcode project
Getting this error, how do I totally get the firebase out of my Xcode project? I don't really need to know the right way of getting it back in, but how do I fully get it out? Thanks! Here's a screenshot of my error.

答: If you are using cocoapods, just delete this pod 'Firebase/Core' line from your podfile and again update pod from terminal.</p>


问:
Google Sheets ARRAYFORMULA with nested if statements
Im working on what I thought would be a fairly straight forward arrayformula where I only needed a single cell entry instead of having to copy it down to 100+ rows.

I am working on a spreadsheet for use with the beast shape, elemental body, and plant shape spells in Pathfinder.

My table looks like

_________A___________B________C

1___Spell name_____Type_____Size

Where A2 will contain the arrayformula. B2:B will contain Animal, Plant, Elemental, Magical Beast. C2:C will contain the range of sizes.

I have tried

ARRAYFORMULA(if(B2:B<>"",CONCATENATE(if(AND(B2:B="Animal", OR(C2:C="Small", C2:C="Medium")),"Beast Shape 1","Fail BS1"),if(AND(B2:B="Animal", OR(C2:C="Tiny", C2:C="Large")),"Beast Shape 2","Fail BS2")),"Fail Other"))

and

=ARRAYFORMULA(if(B2:B<>"",if(and(B2:B="Animal",C2:C="Small"),"Beast Shape 1", "not"), "if fail"))

But they produce incorrect output. I have tried several others as well but with various issues, usually not being propagated down all the cells, or just having the wrong information. Even when I try using only a single statement.

Originally my plan was to have a concat statement which contained multiple if statements which would produce the spell name or nothing. It looked something like

arrayformula(if(b2:b<>"",concatenate(if(and(b2:b="Animal",OR(c2="small",c2="medium")), "Beast shape 1", ""), if(and(b2:b="Animal",OR(c2="tiny",c2="large")), "Beast shape 2", ""))

However the output is wrong, and I havent been able to figure out why. Ive seen comments in places which suggests AND and OR are not valid as they have single output statements, and that concatenate must be replaced with &, but even when those are removed it does not work.

答:
Replace AND with * and OR with +:

if(and(b2:b="Animal",OR(c2="small",c2="medium"))

becomes:

if( (b2:b="Animal") * ((c2:c="small") + (c2:c="medium")) )

array-formula must work with that.


问:
ng-bind-html is not able to bind text and image url together
I am trying to use some string and a image together in ng-bind-html tag in AngularJS but it is giving error so far what i did is

```<code><div class="row">
    <span data-ng-bind-html="question"></span>
</div>
</code>```

If only string value is coming or only image url is coming then it works fine but when string + image url both are coming it does not display anything and it thrown error(404) can not find resource.

This value is coming from DB which will assign to question variable

"This is Instruction for below question"
 http://localhost:8080/OnlineExam/static/css/question_images/ tid_27-8-16_10AM_qno_25.png

答:
var app = angular.module("exApp",["ngSanitize"]);

app.controller('ctrl', function($scope, $sce){
$scope.image = $sce.trustAsHtml('');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-sanitize.min.js"></script>
<body ng-app="exApp">
<div ng-controller="ctrl">
<span ng-bind-html="image"></span>
</div>
</body></code>```

Body:
I am trying to use some string and a image together in ng-bind-html tag in AngularJS but it is giving error so far what i did is

If only string value is coming or only image url is coming then it works fine but when string + image url both are coming it does not display anything and it thrown error(404) can not find resource.

This value is coming from DB which will assign to question variable

"This is Instruction for below question"
 http://localhost:8080/OnlineExam/static/css/question_images/ tid_27-8-16_10AM_qno_25.png

Body:
var app = angular.module("exApp",["ngSanitize"]);

app.controller('ctrl', function($scope, $sce){
$scope.image = $sce.trustAsHtml('<img src="http://i67.tinypic.com/s6rmeo.jpg" style="width:200px;height:200px">');
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-sanitize.min.js"></script>
<body ng-app="exApp">
<div ng-controller="ctrl">
<span ng-bind-html="image"></span>
</div>
</body>


问:
Make row expanded element ie extjs grid and chart resizable on window resize
I have used rowExpander plugin in extjs grid on expand of each row 1 property grid with details of row selected and chart is rendered in the div of rowBodyTpl. I want to resize both the elements on window(browser) resize.
`
My parent grid is like this with rowexpander

```<code>    var grid = Ext.create('Ext.app.CustomizedGridPanelv2', {
        width: '100%',
        overflowY: 'auto',
        flex: 1,
        store: this.gridStore,
        plugins: [{
            pluginId: 'expander',
            ptype: 'rowexpander',
            expandOnDblClick: false,
            expandOnEnter: false,
            rowBodyTpl: '<div id="{someId}' + this.id + '"></div>'
        }],
        viewConfig: {
            stripeRows: true,
            deferEmptyText: false,
            emptyText: " No detailsfound."
        },
        columns: [{ columns needed}] });
</code>```

On expand i create a panel and render to the div

```<code>grid.getView().addListener('expandbody', function(_rowNode, _rec, _expandedHTML) {

        var panel = Ext.create('myPanel', {
            srcPanel: me,
            srcRecord: _rec,
            srcDiv: _rec.get('someId') + me.id
        });

        panel.render(_rec.get('someId') + me.id);

        grid.doLayout();
    });
</code>```

My panel will contain property grid and chart which are the items of extjs panel
`
my parent grid get resized on window resize but the expanded elements get truncated. Is there any way to resize them with browser. Thanks.

答:
I think you can add resize event listener for parent component (grid in your case):

```<code>listeners: {
    resize: function (grid) {
        var plugin = grid.findPlugin('rowexpander');
        if (plugin && plugin.recordsExpanded) {
            for (var id in plugin.recordsExpanded) {
                grid.getEl().down('.my_row_body#' + id).setWidth('100%');
            }
        }
    }
}
</code>```

But actually row body resize with grid out of the box, check this fiddle.

Also you can check this question.

If your issue relates to browser window resize, not just grid resize I think you can add resize event listener for entire window (not sure its good solution btw):

```<code>window.addEventListener('resize', function () {
    myView.doLayout();
}, true);
</code>```

Body:
I have used rowExpander plugin in extjs grid on expand of each row 1 property grid with details of row selected and chart is rendered in the div of rowBodyTpl. I want to resize both the elements on window(browser) resize.
`
My parent grid is like this with rowexpander

    var grid = Ext.create('Ext.app.CustomizedGridPanelv2', {
        width: '100%',
        overflowY: 'auto',
        flex: 1,
        store: this.gridStore,
        plugins: [{
            pluginId: 'expander',
            ptype: 'rowexpander',
            expandOnDblClick: false,
            expandOnEnter: false,
            rowBodyTpl: '

'
        }],
        viewConfig: {
            stripeRows: true,
            deferEmptyText: false,
            emptyText: " No detailsfound."
        },
        columns: [{ columns needed}] });

On expand i create a panel and render to the div

grid.getView().addListener('expandbody', function(_rowNode, _rec, _expandedHTML) {

        var panel = Ext.create('myPanel', {
            srcPanel: me,
            srcRecord: _rec,
            srcDiv: _rec.get('someId') + me.id
        });

        panel.render(_rec.get('someId') + me.id);

        grid.doLayout();
    });

My panel will contain property grid and chart which are the items of extjs panel
`
my parent grid get resized on window resize but the expanded elements get truncated. Is there any way to resize them with browser. Thanks.

Body:
I think you can add resize event listener for parent component (grid in your case):

listeners: {
    resize: function (grid) {
        var plugin = grid.findPlugin('rowexpander');
        if (plugin && plugin.recordsExpanded) {
            for (var id in plugin.recordsExpanded) {
                grid.getEl().down('.my_row_body#' + id).setWidth('100%');
            }
        }
    }
}

But actually row body resize with grid out of the box, check this fiddle.

Also you can check this question.

If your issue relates to browser window resize, not just grid resize I think you can add resize event listener for entire window (not sure its good solution btw):

window.addEventListener('resize', function () {
    myView.doLayout();
}, true);


问:
C++ detection idiom without void_t
How I can implement C++ detection idiom without using void_t? In other words, can I implement C++17 std::is_detected etc using only C++03-features?

UPD Detection idiom requires C++11 by definition. In my question I just meant that I want to implement is_detected somehow without void_t. My problem is in it: unused parameters in alias templates were not guaranteed to ensure SFINAE and could be ignored, ans VS 2013 has this defect; another tries (like on cppreference) leads to compiler crash (yep, cl is the greatest compiler in the world).

UPD2 I suppose that VS 2013 can break any C++ metaprogramming techniques (and programmer's brains too).

答:
Back in the good old days, this is how we do it

```<code>template<typename T>
T declval();

template<typename T>
struct can_foo
{
    typedef char yes;
    struct no {char c[2];};

    template<typename U>
    static yes check(int (*)[sizeof(declval<U>().foo(), 1)]);
    template<typename>
    static no check(...);

    enum {value = sizeof(check<T>(0)) == sizeof(yes)};
};

struct fooer
{
    void foo() {}
};
struct barer
{
    void bar() {}
};

#include<cassert>

int main()
{
    assert(can_foo<fooer>::value);
    assert(!can_foo<barer>::value);
}
</code>```

Live example

The trick is to abuse sizeof as much as possible.

Note that the declval is different from std::declval.

Title: C++ detection idiom without void_t

Body:
Back in the good old days, this is how we do it

template<typename T>
T declval();

template<typename T>
struct can_foo
{
    typedef char yes;
    struct no {char c[2];};

    template<typename U>
    static yes check(int (*)[sizeof(declval<U>().foo(), 1)]);
    template<typename>
    static no check(...);

    enum {value = sizeof(check<T>(0)) == sizeof(yes)};
};

struct fooer
{
    void foo() {}
};
struct barer
{
    void bar() {}
};

#include<cassert>

int main()
{
    assert(can_foo<fooer>::value);
    assert(!can_foo<barer>::value);
}

Live example

The trick is to abuse sizeof as much as possible.

Note that the declval is different from std::declval.