问:
How to add paging functionally to a DevExpress GridView with page controls
I am creating a new DevExpress GridView with pagination, but the links to other pages do not do anything when they are clicked. I need to add this functionallity, but I am not sure where to start.

The new DevExpress GridView is based off a view that doesn't use DevExpress. This page will be a list of the corporate directory, so it has columns like name, telephone, and location. The view has been created and displays with paging controls. I have done a bit of looking around on the DevExpress forums for similar issues, but those are all using .aspx and I am using .cshtml for my GridView.

public ActionResult DevExpressView()
{
   return View(EmployeeList);
}
```

```@Html.DevExpress().GetStyleSheets(new StyleSheet { ExtensionSuite = ExtensionSuite.GridView})

@Html.DevExpress().GridView(
    settings =>
    {
        settings.Name = "GridView";
        settings.CallbackRouteValues = new { Controller = "DevExpessController", Action = "DevExpressView" };

        settings.KeyFieldName = "Clock";
        settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
        settings.SettingsPager.PageSize = 32;
        settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
        settings.Settings.VerticalScrollableHeight = 350;
        settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
        settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
        settings.ControlStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);

        settings.Columns.Add("FirstName");
        settings.Columns.Add("LastName");
        settings.Columns.Add("Department");
        settings.Columns.Add("Title");
        settings.Columns.Add("PlantNO");
        settings.Columns.Add("Telephone");
        settings.Columns.Add("Mobile");
        settings.Columns.Add("Pager");

    }).Bind(Model).GetHtml()
```

There are controls at the bottom of the GridView to handle pagination, but nothing happens when they are clicked. I would like these controls to change the page of employees being displayed. Sorry if my question doesn't make sense, I am new to DevExpress.

答:
Having only one Controller Action is not enough for the DevExpress server side controls.
You need 2 Controller Actions, 1 View and 1 PartialView for that to work.
Also make sure to load the scripts for GridView (see below).

Client navigates to:

```<code>public ActionResult DevExpressView()
{
    IQueryable<Employee> model = GetYourDataFromSomewhere();
    return View("EmployeeList", model);
}
</code>```

EmployeeList.cshtml (View)

```<code>@model IEnumerable
@Html.DevExpress().GetScripts(new Script { ExtensionSuite = ExtensionSuite.GridView })
@Html.DevExpress().GetStyleSheets(new StyleSheet { ExtensionSuite = ExtensionSuite.GridView})

@Html.Partial("GridView", Model)
</code>```

GridView.cshtml (Partial View)

Important: This view only needs to include the grid. Nothing else!

```<code>@Html.DevExpress().GridView(
settings =>
{
    settings.Name = "GridView";
    settings.CallbackRouteValues = new { Controller = "DevExpessController", Action = "DevExpressViewPartial" };

    settings.KeyFieldName = "Clock";
    settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
    settings.SettingsPager.PageSize = 32;
    settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
    settings.Settings.VerticalScrollableHeight = 350;
    settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
    settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
    settings.ControlStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);

    settings.Columns.Add("FirstName");
    settings.Columns.Add("LastName");
    settings.Columns.Add("Department");
    settings.Columns.Add("Title");
    settings.Columns.Add("PlantNO");
    settings.Columns.Add("Telephone");
    settings.Columns.Add("Mobile");
    settings.Columns.Add("Pager");

}).Bind(Model).GetHtml()
</code>```

Callback Action for the grid:

```<code>public ActionResult DevExpressViewPartial()
{
    IQueryable<Employee> model = GetYourDataFromSomewhere();
    return PartialView("GridView", model);
}
</code>```

Have a look at their demo. If you copy that code (except the NorthwindDataProvider of course), you should have a working sample.

Body:
I am creating a new DevExpress GridView with pagination, but the links to other pages do not do anything when they are clicked. I need to add this functionallity, but I am not sure where to start.

The new DevExpress GridView is based off a view that doesn't use DevExpress. This page will be a list of the corporate directory, so it has columns like name, telephone, and location. The view has been created and displays with paging controls. I have done a bit of looking around on the DevExpress forums for similar issues, but those are all using .aspx and I am using .cshtml for my GridView.

public ActionResult DevExpressView()
{
   return View(EmployeeList);
}

@Html.DevExpress().GetStyleSheets(new StyleSheet { ExtensionSuite = ExtensionSuite.GridView})

@Html.DevExpress().GridView(
    settings =>
    {
        settings.Name = "GridView";
        settings.CallbackRouteValues = new { Controller = "DevExpessController", Action = "DevExpressView" };

        settings.KeyFieldName = "Clock";
        settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
        settings.SettingsPager.PageSize = 32;
        settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
        settings.Settings.VerticalScrollableHeight = 350;
        settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
        settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
        settings.ControlStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);

        settings.Columns.Add("FirstName");
        settings.Columns.Add("LastName");
        settings.Columns.Add("Department");
        settings.Columns.Add("Title");
        settings.Columns.Add("PlantNO");
        settings.Columns.Add("Telephone");
        settings.Columns.Add("Mobile");
        settings.Columns.Add("Pager");

    }).Bind(Model).GetHtml()

There are controls at the bottom of the GridView to handle pagination, but nothing happens when they are clicked. I would like these controls to change the page of employees being displayed. Sorry if my question doesn't make sense, I am new to DevExpress.

Body:
Having only one Controller Action is not enough for the DevExpress server side controls.
You need 2 Controller Actions, 1 View and 1 PartialView for that to work.
Also make sure to load the scripts for GridView (see below).

Client navigates to:

public ActionResult DevExpressView()
{
    IQueryable<Employee> model = GetYourDataFromSomewhere();
    return View("EmployeeList", model);
}

EmployeeList.cshtml (View)

@model IEnumerable
@Html.DevExpress().GetScripts(new Script { ExtensionSuite = ExtensionSuite.GridView })
@Html.DevExpress().GetStyleSheets(new StyleSheet { ExtensionSuite = ExtensionSuite.GridView})

@Html.Partial("GridView", Model)

GridView.cshtml (Partial View)

Important: This view only needs to include the grid. Nothing else!

@Html.DevExpress().GridView(
settings =>
{
    settings.Name = "GridView";
    settings.CallbackRouteValues = new { Controller = "DevExpessController", Action = "DevExpressViewPartial" };

    settings.KeyFieldName = "Clock";
    settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
    settings.SettingsPager.PageSize = 32;
    settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
    settings.Settings.VerticalScrollableHeight = 350;
    settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
    settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
    settings.ControlStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);

    settings.Columns.Add("FirstName");
    settings.Columns.Add("LastName");
    settings.Columns.Add("Department");
    settings.Columns.Add("Title");
    settings.Columns.Add("PlantNO");
    settings.Columns.Add("Telephone");
    settings.Columns.Add("Mobile");
    settings.Columns.Add("Pager");

}).Bind(Model).GetHtml()

Callback Action for the grid:

public ActionResult DevExpressViewPartial()
{
    IQueryable<Employee> model = GetYourDataFromSomewhere();
    return PartialView("GridView", model);
}

Have a look at their demo. If you copy that code (except the NorthwindDataProvider of course), you should have a working sample.


来源: stackexchange

问:
PHP Problem with array_count_values
I need to get one time occurence on my array, with my code I get only first result here is my example code:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}
</code>```

Thanks in advance

ciao h

ContentLicense: CC BY-SA 3.0

Title: PHP Problem with array_count_values

Body:
I need to get one time occurence on my array, with my code I get only first result here is my example code:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

Thanks in advance

ciao h

Body:
May be you've miss your real results:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
/*
now $arrs is:
array (
  'a' => 2,
  'b' => 1,
  'c' => 1,
  'd' => 1,
)
*/

foreach($arrs as $id => $count){
 if($count==1) {
   // do your code
 }
}

/*******************************************************/
/* usefull version                                     */
/*******************************************************/

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);

foreach($arr as $id ){
 if($arrs[$id]==1){
   // do your code
   echo "$id is single\n";
 }
}


问:
Emacs compilation mode won't see bash alias
Emacs M-x compile does not see any aliases set in .bashrc. If I use M-x shell then type the alias, it is fine. I tried sourcing .bashrc from /etc/profile, from ~/.profile, ~/bash_env, anything I can think of to no avail.

I am on Emacs 23 and Ubuntu 11. I start emacs using /usr/bin/emacs %F, from a desktop button.

答:
See Is there a way to get my emacs to recognize my bash aliases and custom functions when I run a shell command? for a fix which doesn't run all your .bashrc and doesn't create these error messages:

bash: cannot set terminal process group (-1): Inappropriate ioctl for device
  bash: no job control in this shell

ContentLicense: CC BY-SA 4.0


问:
SSRS Report Populate same table field values in different columns in Orderly Manner
I need to fill bank deposit slip, deposit slip in the format of 3 columns for Amount
I want to fill the amount column by column in an orderly manner
But in the table field is the only Amount

答:
You can specify the row and column that each amount should be in using RowNumber functions inside a matrix.

Insert a matrix into the report. Set the columns to be grouped by:

```<code>=(RowNumber(Nothing) +1) Mod 3
</code>```

Set the rows to be grouped by:

```<code>=Ceiling(RowNumber(Nothing) / 3)
</code>```

Here's an example of how the results would look:

Body:
You can specify the row and column that each amount should be in using RowNumber functions inside a matrix.

Insert a matrix into the report. Set the columns to be grouped by:

=(RowNumber(Nothing) +1) Mod 3

Set the rows to be grouped by:

=Ceiling(RowNumber(Nothing) / 3)

Here's an example of how the results would look:


问:
Android emulator - error while loading state for instance 0x0 of device 'goldfish_pipe'
I updated some android studio components 2 days ago and everything messed up. Now I cant use android emulator since it exits immediately the moment it gets lunched.

I already tried the following:

Delete all my virtual devices and created new ones - didn't work.

Wipe Emulator data - didn't work.

Tried to lunch emulator manually in AVD - didn't work

Launch emulator with the option Cold boot now. - Emulator displayed this message Cold boot: requested by the user and exit.

Uninstall Android Studio and deleted whole SDK folder and downloaded everything new - didn't work may be bacause the problem is within latest release.

Tried to downgrade Emulator manually! I asked it here - I downloaded the previous release and deleted everything in sdk\emulator and put files there, Deleted all virtual devices and create new ones. Pressed run. this message pops up when emulator start Cold boot different AVD Configuration and then it exits again. This is may be I didn't downgrade all emulator related tools, I don't know how!. And sometimes different message pops up saying Resetting for cold boot: emulation engine failed and exits.

None of these worked and I am out of ideas.

Here are logs get printed before emulator flash disappearance.

16:00 Emulator: C:\Users\Nux\AppData\Local\Android\Sdk\emulator\qemu\windows-x86_64\qemu-system-x86_64.exe: error while loading state for instance 0x0 of device 'goldfish_pipe'

16:00 Emulator: deleteSnapshot: for default_boot

16:00 Emulator: qemu: unsupported keyboard cmd=0x84

16:00 Emulator: Process finished with exit code 0

Screenshot of emulator before disappearance

SDK Tools screenshot

Edit
Several issues have been submitted already:

https://issuetracker.google.com/issues/132481542

https://issuetracker.google.com/issues/132834989

https://issuetracker.google.com/issues/131854864

答: i just lowered the RAM to < 768MB, worked for me</p>


问:
How to fix "ord() expected a character, but string of length 0 found" error in Python
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this? </p>

```<code>def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()
</code>```

答:
You don't need load and splitting by '/'. You added extra characters only to split and remove them. Worse, in this case after you added / you are now left with a trailing / and so when you split(), the last part is a whitespace char.

So remove the first for loop adn cut to the next one directly. If you still see the issue then it could be that input() gives you trailing characters and so the error that you are seeing makes sense.

Simply run input("The message").trimspace() to remove trailing whitespace characters and the code should work. You could work on optimizing your code separately but the issue must be that.

Body:
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this?

def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()


问:
Is this class Threadsafe?
Hi

Is the class below threadsafe?

```<code>class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}
</code>```

答: Use ConcurrentHashMap instead of HashMap and ConcurrentMap when declaring field and it should be.

Title: Is this class Threadsafe?

Body:
Hi

Is the class below threadsafe?

class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}


问:
Trigger function for multiple elements with same class
I have multiple div elements with similar buttons that have the same class name, I am trying to trigger the event handlers respective of the button I click. I have tried the "each" jquery function but it only triggers the first element. I tried using document on click too. i added stopPropagation and preventDefault too.</p>

```<code><div id="overview-comment-container" class="social-comment-container">
        <ul class="comments-list">
            <li class="posted-video-comment">
                <div class="comment-body-divider"></div>
                <div class="comment-list-divider" align="center" width="90%"></div>
                <div class="comment-user-details">
                    <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
                    <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
                </div>
                <div class="commentinfo-block-wrapper">
                    <div id="distinct-user-comment" contenteditable="false">Salute</div>
                </div>
                <div class="comment-buttons" style="display: none;">
                    <button id="update-button" class="social-update-button"> Update </button>
                    <button id="cancel-button" class="social-cancel-button"> Cancel </button>
                </div>
                <div class="comment-body-divider"></div>
            </li>
            <li class="posted-video-comment">
                <div class="comment-body-divider"></div>
                <div class="comment-list-divider" align="center" width="90%"></div>
                <div class="comment-user-details">
                    <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
                    <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
                </div>
                <div class="comment-block-wrapper">
                    <div id="distinct-user-comment"
contenteditable="false">Hello</div>
                </div>
                <div class="comment-buttons" style="display: none;">
                    <button id="update-button" class="social-update-button"> Update </button>
                    <button id="cancel-button" class="social-cancel-button"> Cancel </button>
                </div>
                <div class="comment-body-divider"></div>
            </li>
        </ul>
    </div>

$( '.edit-img' ).each( function() {
        $(this).click( function(e) {

            e.stopPropagation();

            var editComment = $( '#distinct-user-comment' );
            var editCommentText = editComment.text();
            $( '.delete-comment' ).css( "visibility", "hidden" );
            $( '.edit-comment' ).css( "visibility", "hidden" );

            editComment.html( '<textarea class="editPostedComment" placeholder="'+ editCommentText + '"style="width: 60%;">'
                                + editCommentText +
                              '</textarea>' );

            $( '.editPostedComment' ).one('focus', function() {
                $( this ).text( editCommentText );
            });

            $('.comment-buttons' ).show();
        });
    });

$( '#cancel-button' ).click( function(e) {
            e.stopPropagation();
            e.preventDefault();

            var onEditComment = $( '.editPostedComment' );

            onEditComment.replaceWith('<div id="distinct-user-comment" contenteditable="false">' + onEditComment.attr('placeholder') + '</div>');
            $( '.comment-buttons' ).hide();
            $( '.delete-comment' ).css( "visibility", "visible" );
            $( '.edit-comment' ).css( "visibility", "visible" );
        });
</code>```

答:
The reason only first comment is handled is having same ID for multiple elements. ID is meant to be unique and only first of the element with same IDs are selected, always.

Secondly, you have to establish a context that identifies a comment and then refer everything inside that context. In your case it is the 'li' tag with class 'posted-video-comment'.

We will use JQuery's closest() method to find the parent 'li' and then use .find() method inside the 'li' every time we want to refer to an element, by class, for that comment.

Here is the html:

```<code><div id="overview-comment-container" class="social-comment-container" style="border-bottom: 2px solid rgb(255, 255, 255);">
  <ul class="comments-list">
    <li class="posted-video-comment">
      <div class="comment-body-divider"></div>
      <div class="comment-list-divider" align="center" width="90%"></div>
      <div class="comment-user-details">
        <span class="distinct-user-name">Tope Babz</span>
        <span class="distinct-timestamp">5 secs ago</span>
        <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
        <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
      </div>
      <div class="commentinfo-block-wrapper">
        <div class="distinct-user-comment" contenteditable="false">Salute</div>
      </div>
      <div class="comment-buttons" style="display: none;">
        <button class="social-update-button"> Update </button>
        <button class="social-cancel-button"> Cancel </button>
      </div>
      <div class="comment-body-divider"></div>
    </li>
    <li class="posted-video-comment">
      <div class="comment-body-divider"></div>
      <div class="comment-list-divider" align="center" width="90%"></div>
      <div class="comment-user-details">
        <span class="distinct-user-name">Sergio</span>
        <span class="distinct-timestamp">15 secs ago</span>
        <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
        <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
      </div>
      <div class="commentinfo-block-wrapper">
        <div class="distinct-user-comment" contenteditable="false">Hello</div>
      </div>
      <div class="comment-buttons" style="display: none;">
        <button class="social-update-button"> Update </button>
        <button class="social-cancel-button"> Cancel </button>
      </div>
      <div class="comment-body-divider"></div>
    </li>
  </ul>
</div>
</code>```

And here is the Javascript:
    $('.edit-img').click(function(e) {
      e.stopPropagation();

```<code>  var $li = $(this).closest('.posted-video-comment');
  var editComment = $li.find('.distinct-user-comment');
  var editCommentText = editComment.text();
  $li.find('.delete-comment').css("visibility", "hidden");
  $li.find('.edit-comment').css("visibility", "hidden");

  editComment.html('<textarea class="editPostedComment" placeholder="' + editCommentText + '"style="width: 60%;">' +
    editCommentText +
    '</textarea>');

  $li.find('.editPostedComment').on('focus', function() {
    $(this).text(editCommentText);
  });

  $li.find('.comment-buttons').show();
});

$('.social-cancel-button').click(function(e) {
  e.stopPropagation();
  e.preventDefault();

  var $li = $(this).closest('.posted-video-comment');
  var onEditComment = $li.find('.editPostedComment');

  onEditComment.replaceWith('<div id="distinct-user-comment" contenteditable="false">' + onEditComment.attr('placeholder') + '</div>');
  $li.find('.comment-buttons').hide();
  $li.find('.delete-comment').css("visibility", "visible");
  $li.find('.edit-comment').css("visibility", "visible");
});
</code>```

And here is the working fiddle.

Body:
I have multiple div elements with similar buttons that have the same class name, I am trying to trigger the event handlers respective of the button I click. I have tried the "each" jquery function but it only triggers the first element. I tried using document on click too. i added stopPropagation and preventDefault too.

Salute

                    <button id="update-button" class="social-update-button"> Update </button>
                    <button id="cancel-button" class="social-cancel-button"> Cancel </button>

Hello

                    <button id="update-button" class="social-update-button"> Update </button>
                    <button id="cancel-button" class="social-cancel-button"> Cancel </button>

$( '.edit-img' ).each( function() {
        $(this).click( function(e) {

            e.stopPropagation();

            var editComment = $( '#distinct-user-comment' );
            var editCommentText = editComment.text();
            $( '.delete-comment' ).css( "visibility", "hidden" );
            $( '.edit-comment' ).css( "visibility", "hidden" );

            editComment.html( '<textarea class="editPostedComment" placeholder="'+ editCommentText + '"style="width: 60%;">'
                                + editCommentText +
                              '</textarea>' );

            $( '.editPostedComment' ).one('focus', function() {
                $( this ).text( editCommentText );
            });

            $('.comment-buttons' ).show();
        });
    });

$( '#cancel-button' ).click( function(e) {
            e.stopPropagation();
            e.preventDefault();

            var onEditComment = $( '.editPostedComment' );

            onEditComment.replaceWith('
' + onEditComment.attr('placeholder') + '
');
            $( '.comment-buttons' ).hide();
            $( '.delete-comment' ).css( "visibility", "visible" );
            $( '.edit-comment' ).css( "visibility", "visible" );
        });

Body:
The reason only first comment is handled is having same ID for multiple elements. ID is meant to be unique and only first of the element with same IDs are selected, always.

Secondly, you have to establish a context that identifies a comment and then refer everything inside that context. In your case it is the 'li' tag with class 'posted-video-comment'.

We will use JQuery's closest() method to find the parent 'li' and then use .find() method inside the 'li' every time we want to refer to an element, by class, for that comment.

Here is the html:

<div id="overview-comment-container" class="social-comment-container" style="border-bottom: 2px solid rgb(255, 255, 255);">
  <ul class="comments-list">
    <li class="posted-video-comment">
      <div class="comment-body-divider"></div>
      <div class="comment-list-divider" align="center" width="90%"></div>
      <div class="comment-user-details">
        <span class="distinct-user-name">Tope Babz</span>
        <span class="distinct-timestamp">5 secs ago</span>
        <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
        <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
      </div>
      <div class="commentinfo-block-wrapper">
        <div class="distinct-user-comment" contenteditable="false">Salute</div>
      </div>
      <div class="comment-buttons" style="display: none;">
        <button class="social-update-button"> Update </button>
        <button class="social-cancel-button"> Cancel </button>
      </div>
      <div class="comment-body-divider"></div>
    </li>
    <li class="posted-video-comment">
      <div class="comment-body-divider"></div>
      <div class="comment-list-divider" align="center" width="90%"></div>
      <div class="comment-user-details">
        <span class="distinct-user-name">Sergio</span>
        <span class="distinct-timestamp">15 secs ago</span>
        <span class="delete-comment"><img id="erase-img" title="Delete comment" src="https://www.flaticon.com/premium-icon/icons/svg/484/484662.svg"></span>
        <span class="edit-comment"><img class="edit-img" title="Edit comment" src="https://image.flaticon.com/icons/svg/61/61456.svg"></span>
      </div>
      <div class="commentinfo-block-wrapper">
        <div class="distinct-user-comment" contenteditable="false">Hello</div>
      </div>
      <div class="comment-buttons" style="display: none;">
        <button class="social-update-button"> Update </button>
        <button class="social-cancel-button"> Cancel </button>
      </div>
      <div class="comment-body-divider"></div>
    </li>
  </ul>
</div>

And here is the Javascript:
    $('.edit-img').click(function(e) {
      e.stopPropagation();

  var $li = $(this).closest('.posted-video-comment');
  var editComment = $li.find('.distinct-user-comment');
  var editCommentText = editComment.text();
  $li.find('.delete-comment').css("visibility", "hidden");
  $li.find('.edit-comment').css("visibility", "hidden");

  editComment.html('<textarea class="editPostedComment" placeholder="' + editCommentText + '"style="width: 60%;">' +
    editCommentText +
    '</textarea>');

  $li.find('.editPostedComment').on('focus', function() {
    $(this).text(editCommentText);
  });

  $li.find('.comment-buttons').show();
});

$('.social-cancel-button').click(function(e) {
  e.stopPropagation();
  e.preventDefault();

  var $li = $(this).closest('.posted-video-comment');
  var onEditComment = $li.find('.editPostedComment');

  onEditComment.replaceWith('<div id="distinct-user-comment" contenteditable="false">' + onEditComment.attr('placeholder') + '</div>');
  $li.find('.comment-buttons').hide();
  $li.find('.delete-comment').css("visibility", "visible");
  $li.find('.edit-comment').css("visibility", "visible");
});

And here is the working fiddle.


问:
Can't change production.ini file
I am following the current tutorial for setting up CKAN. (https://docs.ckan.org/en/latest/maintaining/installing/install-from-docker-compose.html)

I am not getting the DataStore tab when managing a dataset, so I was trying to follow the section where it says "Datastore and Datapusher". I got everything fine but when it says to edit the "production.ini" file, I am not getting the actual file. It says to run the following command:

sudo vim $VOL_CKAN_CONFIG/production.ini

But that just opens an empty file. And yes, I did configure the $VOL_CKAN_CONFIG variable like it says before in the tutorial. I am new to Docker and CKAN so any help will be appreciated.

答: What do echo $VOL_CKAN_CONFIG and ls $VOL_CKAN_CONFIG/* give?

Title: Can't change production.ini file


问:
Overwrite file if new session but append if same session
I have a function to convert any write-hosts in the script (keeping them for coloring purposes later) to tee object

```<code>function Write-Host($object)
{
    $object | tee .\LOG.txt -Append
}
</code>```

This currently appends to the file if it exists (or creates one if it doesnt)

i want to create one everytime a NEW session is started. only append to the file if you are in the same session

how do i do that?

答:
You don't define what a new "session" is to you, so let's use the variable $PID, which is the process ID that PowerShell is running as.

Ideally you'd just make this part of the file name so that each process has its own log. But you stated in comments that you don't want multiple files. In that case, write the PID as the first line in the file, and read it each time.

function Write-Host($object)
{
    $filename = '.\LOG.txt'

    $logPID = Get-Content -LiteralPath $filename -ReadCount 1 -ErrorAction Ignore
    $newSession = $logPID -ne $PID

    if ($newSession) {
        $PID | Set-Content -LiteralPath $filename
    }

    $object | Tee-Object -FilePath $filename -Append
}
```

Body:
I have a function to convert any write-hosts in the script (keeping them for coloring purposes later) to tee object

function Write-Host($object)
{
    $object | tee .\LOG.txt -Append
}

This currently appends to the file if it exists (or creates one if it doesnt)

i want to create one everytime a NEW session is started. only append to the file if you are in the same session

how do i do that?


问:
Using Java, how is this charAt(); turn a string into an int?
I'm a beginner at Java and I'm trying to understand and explain to myself how this for loop is working. The instructions say it's converting the numeric Unicode equivalent for each letter in each word by using loops.

Based on my understanding the for loop goes through the entire word using the .length() and then stores it as int i, which gets carried down into the parenthesis of i of the charAt. CharAt returns each character in the word and then the int converts it into an int that is stored as finalInt.

So my question is where does unicode number comes from? How does it know that it's unicode?

```<code>String word1;
int finalInt;

for (int i = 0; i < word1.length(); i++) {
    finalInt = (int) word1.charAt(i);

        }
</code>```

答:
Check the ASCII table - http://www.asciitable.com/

Your code is transforming a char (last column) into its numerical representation (first column).

Body:
I'm a beginner at Java and I'm trying to understand and explain to myself how this for loop is working. The instructions say it's converting the numeric Unicode equivalent for each letter in each word by using loops.

Based on my understanding the for loop goes through the entire word using the .length() and then stores it as int i, which gets carried down into the parenthesis of i of the charAt. CharAt returns each character in the word and then the int converts it into an int that is stored as finalInt.

So my question is where does unicode number comes from? How does it know that it's unicode?

String word1;
int finalInt;

for (int i = 0; i < word1.length(); i++) {
    finalInt = (int) word1.charAt(i);

        }


问:
Nuxt and Ag Grid issue SyntaxError Missing stack frames
Trying to add ag-grid in the nuxt app.

I followed the steps from
https://www.ag-grid.com/vue-getting-started/
and
How to use ag-grid in a Nuxt app

Added the styles in nuxt.config.js

Made a plugin and included in nuxt.config.js

Created the component  AgGridDemo.vue

Including component in page index.vue

Note: Please do not try to run the snippets since I only used them to share the source I have.

My nuxt.config.js file

require('dotenv').config()
import pkg from './package'

export default {
  mode: 'universal',

  /*
   ** Headers of the page
   */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
  },

  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#fff' },

  /*
   ** Global CSS
   */
  css: [
    { src: '~assets/bulma-modifications.scss', lang: 'scss' },
    { src: 'font-awesome/scss/font-awesome.scss', lang: 'scss' },
    { src: '~/node_modules/ag-grid-community/dist/styles/ag-grid.css',  lang: 'css' },
    { src: '~/node_modules/ag-grid-community/dist/styles/ag-theme-dark.css',  lang: 'css' }
  ],

  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    {
      src: '~/plugins/plugin-ag-grid.js',
      ssr: false
    },
    {
      src: '~plugins/plugin-vue-chartjs.js',
      ssr: false
    }
  ],

  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://buefy.github.io/#/documentation
    'nuxt-buefy',
    '@nuxtjs/pwa',
    '@nuxtjs/dotenv'
  ],
  /*
   ** Axios module configuration
   */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
  },

  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      config.resolve.alias['vue'] = 'vue/dist/vue.common'
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
      config.node = {
        fs: 'empty'
      }
    }
  },
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  }
}```
</div>
</div>
</p>

<p>My Plugin plugin-ag-grid.js:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import * as agGridEnterpise from 'ag-grid-enterprise/main'
require('dotenv').config()
agGridEnterpise.LicenseManager.setLicenseKey([process.env.AG_LICENSE_KEY])</code>```

My Component AgGridDemo.vue:

<template>
  <ag-grid-vue
    style="width: 500px; height: 500px;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
  ></ag-grid-vue>
</template>
```
</div>
</div>
</p>

<p>Finally My Page:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><template>
  <section class="section">
    Welcome to test page
    <aggriddemo></aggriddemo>
  </section>
</template>
<script>

import AgGridDemo from '~/components/AgGridDemo'
export default {
  name: 'IndexPage',
  components: {
    AgGridDemo
  }
}
</script></code>```

I am getting Error on the Screen but not on my console, console says Compiled successfully but on screen I get:

SyntaxError Missing

stack frames

Any Ideas on why is this happening and how to fix this ?

答:
After trying every solution given here (Thanks for posting), I managed to render the ag-grid on a nuxt project using < no-ssr > tag and dynamic import (minute 7:40 is explained how to do it, if you are not familiar with codesplitting I deeply recommend to watch the whole video) dynamic import video.

How did I get there? Well, Since Andrew wrote that the problem may have something to do with ssr,I switched my nuxt project into mode: 'spa' and BOOM! ag-grid-vue showed up. Now the problem was, many of my features are heavely based on ssr stuff. So I had to make it work for srr mode, but now I know ag-grid-vue is fully available on the client side, so I switched back to mode: ssr and made the following:

Note: Please do not try to run the snippets since I only used them to share the source I have.

My agGridDemo.vue

<template>
  <ag-grid-vue
    style="width: 500px; height: 500px;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
  ></ag-grid-vue>
</template>

```
</div>
</div>
</p>

<p>Nothing new  here, I guess, just that importing the stylesheets in nuxt.config.js file, made the stylesheets unreachable (at  leat in my case). So I added the < style > tag and import the stylsheets as is specified in the ag-grid docs</p>

<p>Here's where magic happened, dynamic imports (as you can see in the video I recomended) avoid to import the component code in the the first load, and import it only when is called, this often useful to optimize page load. So in my first attemp i wrote some this:</p>

```<template>

      <comAgGridDemo v-if="mostrarGrid " ></comAgGridDemo>

</template>

```

<p>So comAgGridDemo will be rendered only when mostrarGrid is true, then in mounted hook (because mounted is available in client side) I made mostrarGrid = true. And It's done. </p>

<p>I went a little futher because, i was not happy using mounted hook for this matter, so I wrapped the component comAgGridDemo on a < srr > tag, remove the v-if, and ag-grid remained rendered just fine. So the index.vue file ended up like this:</p>

<p>My index.vue</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><template>
  <section>
    <no-ssr>
      <comAgGridDemo ></comAgGridDemo>
    </no-ssr>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
// import comAgGridDemo from '~/components/comAgGridDemo.vue'
const comAgGridDemo = () => import('~/components/comAgGridDemo.vue');

@Component({
  components: {
    comAgGridDemo
  }
})
export default class extends Vue {

}
</script></code>```

And that's it.

Note that if you. If you use, < no-ssr > tag with regular import, ag-grid will fail. If you use dymamic import without < no-ssr > tag, ag-grid will fail. If you use the "v-if way" no need to use < no-ssr > tag.

Something is weird on the ssr using ag-grid. But this is how managed to solve it. If there's a better solution, please advise.

I've made a github repo: https://github.com/warheartvik/nuxt-ag-grid

Body:
Trying to add ag-grid in the nuxt app.

I followed the steps from
https://www.ag-grid.com/vue-getting-started/
and
How to use ag-grid in a Nuxt app

Added the styles in nuxt.config.js

Made a plugin and included in nuxt.config.js

Created the component  AgGridDemo.vue

Including component in page index.vue

Note: Please do not try to run the snippets since I only used them to share the source I have.

My nuxt.config.js file

require('dotenv').config()
import pkg from './package'

export default {
  mode: 'universal',

  /*
   ** Headers of the page
   */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }]
  },

  /*
   ** Customize the progress-bar color
   */
  loading: { color: '#fff' },

  /*
   ** Global CSS
   */
  css: [
    { src: '~assets/bulma-modifications.scss', lang: 'scss' },
    { src: 'font-awesome/scss/font-awesome.scss', lang: 'scss' },
    { src: '~/node_modules/ag-grid-community/dist/styles/ag-grid.css',  lang: 'css' },
    { src: '~/node_modules/ag-grid-community/dist/styles/ag-theme-dark.css',  lang: 'css' }
  ],

  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    {
      src: '~/plugins/plugin-ag-grid.js',
      ssr: false
    },
    {
      src: '~plugins/plugin-vue-chartjs.js',
      ssr: false
    }
  ],

  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    // Doc: https://buefy.github.io/#/documentation
    'nuxt-buefy',
    '@nuxtjs/pwa',
    '@nuxtjs/dotenv'
  ],
  /*
   ** Axios module configuration
   */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
  },

  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      config.resolve.alias['vue'] = 'vue/dist/vue.common'
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
      config.node = {
        fs: 'empty'
      }
    }
  },
  env: {
    baseUrl: process.env.BASE_URL || 'http://localhost:3000'
  }
}

My Plugin plugin-ag-grid.js:

import * as agGridEnterpise from 'ag-grid-enterprise/main'
require('dotenv').config()
agGridEnterpise.LicenseManager.setLicenseKey([process.env.AG_LICENSE_KEY])

My Component AgGridDemo.vue:

<template>
  <ag-grid-vue
    style="width: 500px; height: 500px;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
  ></ag-grid-vue>
</template>

Finally My Page:

<template>

    Welcome to test page
    <aggriddemo></aggriddemo>

</template>

I am getting Error on the Screen but not on my console, console says Compiled successfully but on screen I get:

SyntaxError Missing

stack frames

Any Ideas on why is this happening and how to fix this ?

Body:
After trying every solution given here (Thanks for posting), I managed to render the ag-grid on a nuxt project using < no-ssr > tag and dynamic import (minute 7:40 is explained how to do it, if you are not familiar with codesplitting I deeply recommend to watch the whole video) dynamic import video.

How did I get there? Well, Since Andrew wrote that the problem may have something to do with ssr,I switched my nuxt project into mode: 'spa' and BOOM! ag-grid-vue showed up. Now the problem was, many of my features are heavely based on ssr stuff. So I had to make it work for srr mode, but now I know ag-grid-vue is fully available on the client side, so I switched back to mode: ssr and made the following:

Note: Please do not try to run the snippets since I only used them to share the source I have.

My agGridDemo.vue

<template>
  <ag-grid-vue
    style="width: 500px; height: 500px;"
    class="ag-theme-balham"
    :columnDefs="columnDefs"
    :rowData="rowData"
  ></ag-grid-vue>
</template>
<script>
import { AgGridVue } from 'ag-grid-vue'

export default {
  name: 'ag-grid-demo',
  data() {
    return {
      columnDefs: null,
      rowData: null
    }
  },
  components: {
    AgGridVue
  },
  beforeMount() {
    this.columnDefs = [
      { headerName: 'Make', field: 'make' },
      { headerName: 'Model', field: 'model' },
      { headerName: 'Price', field: 'price' }
    ]

    this.rowData = [
      { make: 'Toyota', model: 'Celica', price: 35000 },
      { make: 'Ford', model: 'Mondeo', price: 32000 },
      { make: 'Porsche', model: 'Boxter', price: 72000 }
    ]
  }
}
</script>

<style lang="scss">
  @import "~/node_modules/ag-grid-community/dist/styles/ag-grid.css";
  @import "~/node_modules/ag-grid-community/dist/styles/ag-theme-balham.css";
</style>

Nothing new  here, I guess, just that importing the stylesheets in nuxt.config.js file, made the stylesheets unreachable (at  leat in my case). So I added the < style > tag and import the stylsheets as is specified in the ag-grid docs

Here's where magic happened, dynamic imports (as you can see in the video I recomended) avoid to import the component code in the the first load, and import it only when is called, this often useful to optimize page load. So in my first attemp i wrote some this:

<template>
  <section>
      <comAgGridDemo v-if="mostrarGrid " ></comAgGridDemo>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
// import comAgGridDemo from '~/components/comAgGridDemo.vue'
const comAgGridDemo = () => import('~/components/comAgGridDemo.vue');

@Component({
  components: {
    comAgGridDemo
  }
})
export default class extends Vue {
  mostrarGrid: boolean = false;

  mounted() {
    this.mostrarGrid = true
  }

}
</script>

So comAgGridDemo will be rendered only when mostrarGrid is true, then in mounted hook (because mounted is available in client side) I made mostrarGrid = true. And It's done.

I went a little futher because, i was not happy using mounted hook for this matter, so I wrapped the component comAgGridDemo on a < srr > tag, remove the v-if, and ag-grid remained rendered just fine. So the index.vue file ended up like this:

My index.vue

<template>
  <section>
    <no-ssr>
      <comAgGridDemo ></comAgGridDemo>
    </no-ssr>
  </section>
</template>

<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
// import comAgGridDemo from '~/components/comAgGridDemo.vue'
const comAgGridDemo = () => import('~/components/comAgGridDemo.vue');

@Component({
  components: {
    comAgGridDemo
  }
})
export default class extends Vue {

}
</script>

And that's it.

Note that if you. If you use, < no-ssr > tag with regular import, ag-grid will fail. If you use dymamic import without < no-ssr > tag, ag-grid will fail. If you use the "v-if way" no need to use < no-ssr > tag.

Something is weird on the ssr using ag-grid. But this is how managed to solve it. If there's a better solution, please advise.

I've made a github repo: https://github.com/warheartvik/nuxt-ag-grid


问:
How to Convert EST to Local Time with Dataframe
I'm trying to convert timestamps in EST to various localized timestamps in a pandas dataframe. I have a dataframe with timestamps in EST and a timezone into which they need to be converted.

I know that there are several threads already on topics like this. However, they either start in UTC or I can't replicate with my data.

Before writing, I consulted: How to convert GMT time to EST time using python

I imported the data:

```<code>import pandas
import datetime as dt
import pytz

transaction_timestamp_est         local_timezone

2013-05-28 05:18:00+00:00         America/Chicago
2013-06-12 05:23:20+00:00         America/Los_Angeles
2014-06-21 05:26:26+00:00         America/New_York
</code>```

I converted to datetime and created the following function:

```<code>df.transaction_timestamp_est =
pd.to_datetime(df.transaction_timestamp_est)

def db_time_to_local(row):

    db_tz = pytz.timezone('America/New_York')
    local_tz = pytz.timezone(row['local_timezone'])

    db_date = db_tz.localize(row['transaction_timestamp_est'])
    local_date = db_date.astimezone(local_tz)

    return local_date
</code>```

I run it here:

```<code>df['local_timestamp'] = df.apply(db_time_to_local, axis=1)
</code>```

And get this error:

ValueError: ('Not naive datetime (tzinfo is already set)', 'occurred at index 0')

I expect a new column in the dataframe called 'local_timestamp' that has the timestamp adjusted according to the data in the local_timezone column.

Any help is appreciated!

答:
```<code>from datetime import datetime, time, date
from pytz import timezone, utc

tz = timezone("Asia/Dubai")
d = datetime.fromtimestamp(1426017600,tz)
print d
midnight = tz.localize(datetime.combine(date(d.year, d.month, d.day),time(0,0)), is_dst=None)
print int((midnight - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())
</code>```

Based on code from python - datetime with timezone to epoch

Body:
I'm trying to convert timestamps in EST to various localized timestamps in a pandas dataframe. I have a dataframe with timestamps in EST and a timezone into which they need to be converted.

I know that there are several threads already on topics like this. However, they either start in UTC or I can't replicate with my data.

Before writing, I consulted: How to convert GMT time to EST time using python

I imported the data:

import pandas
import datetime as dt
import pytz

transaction_timestamp_est         local_timezone

2013-05-28 05:18:00+00:00         America/Chicago
2013-06-12 05:23:20+00:00         America/Los_Angeles
2014-06-21 05:26:26+00:00         America/New_York

I converted to datetime and created the following function:

df.transaction_timestamp_est =
pd.to_datetime(df.transaction_timestamp_est)

def db_time_to_local(row):

    db_tz = pytz.timezone('America/New_York')
    local_tz = pytz.timezone(row['local_timezone'])

    db_date = db_tz.localize(row['transaction_timestamp_est'])
    local_date = db_date.astimezone(local_tz)

    return local_date

I run it here:

df['local_timestamp'] = df.apply(db_time_to_local, axis=1)

And get this error:

ValueError: ('Not naive datetime (tzinfo is already set)', 'occurred at index 0')

I expect a new column in the dataframe called 'local_timestamp' that has the timestamp adjusted according to the data in the local_timezone column.

Any help is appreciated!

Body:
from datetime import datetime, time, date
from pytz import timezone, utc

tz = timezone("Asia/Dubai")
d = datetime.fromtimestamp(1426017600,tz)
print d
midnight = tz.localize(datetime.combine(date(d.year, d.month, d.day),time(0,0)), is_dst=None)
print int((midnight - datetime(1970, 1, 1, tzinfo=utc)).total_seconds())

Based on code from python - datetime with timezone to epoch


问:
HTTP Header - ntCoent-Length
I get the following HTTP response headers in a particular response.  All looks okay.  However I have noticed that the content-length appears twice...

Content-Length: 2424
ntCoent-Length: 2424

Is there a particular reason why the content-length is returned a second time as ntCoent-Length?

```
HTTP/1.0 200 OK
Date: Wed, 26 May 2010 09:38:19 GMT
Server: Apache
P3P: CP="NOI DSP COR CURa ADMa TA1a OUR BUS IND UNI COM NAV INT"
Accept-Charset: iso-8859-1, unicode-1-1;q=0.8
Expires: Sun, 15 Jul 1990 00:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache
Content-Language: en
ntCoent-Length: 2424
Connection: close
Content-Type: text/html;charset=iso-8859-1
Content-Length: 2424
```

答: I'm seeing a munged ntCoent-Length header without the correct version being present. The lack of a valid Content-Length is causing Mule ESB to throw an error out of the HTTP connector. Very annoying. I'm hoping our network team can control this with some Netscaler configuration.</p>

ContentLicense: CC BY-SA 2.5

Title: HTTP Header - ntCoent-Length

Body:
I get the following HTTP response headers in a particular response.  All looks okay.  However I have noticed that the content-length appears twice...

Content-Length: 2424
ntCoent-Length: 2424

Is there a particular reason why the content-length is returned a second time as ntCoent-Length?

HTTP/1.0 200 OK
Date: Wed, 26 May 2010 09:38:19 GMT
Server: Apache
P3P: CP="NOI DSP COR CURa ADMa TA1a OUR BUS IND UNI COM NAV INT"
Accept-Charset: iso-8859-1, unicode-1-1;q=0.8
Expires: Sun, 15 Jul 1990 00:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache
Content-Language: en
ntCoent-Length: 2424
Connection: close
Content-Type: text/html;charset=iso-8859-1
Content-Length: 2424


问:
Why `Error:(3, 1) TS1238:Unable to resolve signature of class decorator when called as an expression` error
I have the following decorator:

```<code>export function MyClassDecorator(): PropertyDecorator {
    return function (target: Function) {
        Object.seal(target);
        Object.seal(target.prototype);
    }
}
</code>```

And I use like that:

```<code>import {ClassDecorator} from "./class-decorator";

@MyClassDecorator()
class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}
</code>```

However, tsc reports and error:

```<code>Error:(3, 1) TS1238:Unable to resolve signature of class decorator when called as an expression.
  Supplied parameters do not match any signature of call target.
</code>```

The fix would be to change PropertyDecorator to ClassDecorator:

```<code>export function MyClassDecorator(): ClassDecorator {
</code>```

However, the question is why the error with PropertyDecorator?

Here is how class and property decorators are declared in lib.d.ts:

```<code>declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
</code>```

答:
Property decorators are used inside the class definition, and not above the class. Your property decorator is where a class decorator should be placed.

The warning related to signatures could be appearing because the target parameter in ClassDecorator must actually be a constructor function, whereas in PropertyDecorator it is a more general object. Perhaps TS is able to pick up the difference based upon where you place the decorator.

For example, if you just remove the return type for MyClassDecorator then TS automatically picks up the type for this function and everything works:

```<code>function MyClassDecorator() {
    return function (target: Function) {
        Object.seal(target);
        Object.seal(target.prototype);
    };
}

@MyClassDecorator()
class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}
</code>```

Body:
I have the following decorator:

export function MyClassDecorator(): PropertyDecorator {
    return function (target: Function) {
        Object.seal(target);
        Object.seal(target.prototype);
    }
}

And I use like that:

import {ClassDecorator} from "./class-decorator";

@MyClassDecorator()
class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}

However, tsc reports and error:

Error:(3, 1) TS1238:Unable to resolve signature of class decorator when called as an expression.
  Supplied parameters do not match any signature of call target.

The fix would be to change PropertyDecorator to ClassDecorator:

export function MyClassDecorator(): ClassDecorator {

However, the question is why the error with PropertyDecorator?

Here is how class and property decorators are declared in lib.d.ts:

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;

Body:
Property decorators are used inside the class definition, and not above the class. Your property decorator is where a class decorator should be placed.

The warning related to signatures could be appearing because the target parameter in ClassDecorator must actually be a constructor function, whereas in PropertyDecorator it is a more general object. Perhaps TS is able to pick up the difference based upon where you place the decorator.

For example, if you just remove the return type for MyClassDecorator then TS automatically picks up the type for this function and everything works:

function MyClassDecorator() {
    return function (target: Function) {
        Object.seal(target);
        Object.seal(target.prototype);
    };
}

@MyClassDecorator()
class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}


问:
Rounded corners with HTML "draggable"
I am using the "draggable" attribute and find not all browsers render the element the same way while it is being dragged. Specifically, the background color sometimes is taken from the parent element (e.g. Chromium 33), and sometimes uses white (e.g. Firefox 28).

Some content here that should have clean rounded corners while being dragged

```

See above at http://jsfiddle.net/pZv35/3/.

Is there some way (preferably using CSS) to mitigate this problem?

答:
For images, this did not work for me in present-day Chrome.  I found that this answer works well for images.

Here's my code that's working today:

In css:

```<code>.content {
  background: url('') top left no-repeat;
  overflow: hidden;
  opacity: 0.999;
  border-radius: 50%;
}
</code>```

in html:

```<code><div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <div id="drag1" class="content" style="background:url('##POPULATED PROGRAMMATICALLY##');
   height:144px; width:144px;" draggable="true" ondragstart="drag(event)"> </div>
</div>
</code>```

Title: Rounded corners with HTML "draggable"

Body:
I am using the "draggable" attribute and find not all browsers render the element the same way while it is being dragged. Specifically, the background color sometimes is taken from the parent element (e.g. Chromium 33), and sometimes uses white (e.g. Firefox 28).

Some content here that should have clean rounded corners while being dragged

See above at http://jsfiddle.net/pZv35/3/.

Is there some way (preferably using CSS) to mitigate this problem?

Body:
For images, this did not work for me in present-day Chrome.  I found that this answer works well for images.

Here's my code that's working today:

In css:

.content {
  background: url('') top left no-repeat;
  overflow: hidden;
  opacity: 0.999;
  border-radius: 50%;
}

in html:

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <div id="drag1" class="content" style="background:url('##POPULATED PROGRAMMATICALLY##');
   height:144px; width:144px;" draggable="true" ondragstart="drag(event)"> </div>
</div>


问:
header customization plugins?
I am trying to customize a header in WordPress and need a recommendation on a good plugin to get the job done.

I have tried a plugin but it would only allow adding HTML code but was not very useful in what I am trying to do.

I didn't want to make changes in the CSS file as this can sometimes bring down the entire site. Is there a good plugin for this?

答:
if you use of impreza or zephyr theme, using of "header builder" is the best option for you .
also there is a plugin called "Header Footer Elementor" that can help you ,</p>

Title: header customization plugins?


问:
EntityType has no key defined-- Composite Key, Database First
I have an asp.net MVC web application with 3 tables, PersonType, Curriculum, and CurriculumPersonType which ties the other 2 tables together with a composite key. I am trying to run a LINQ statement against that table.  When I run my code, I get an "EntityType: EntitySet 'CurriculumPersonType' has no key defined.  Define the key to this entity type." error.

I started with this in my model:

```<code>public class CurriculumPersonType
{
    [Key]
    public long CurriculumId { get; set; }

    [Key]
    public long PersonTypeId { get; set; }

    [ForeignKey("PersonTypeId")]
    public virtual PersonType PersonType { get; set; }

    [ForeignKey("CurriculumId")]
    public virtual Curriculum Curriculum { get; set; }
}
</code>```

and have tried adding other annotations such as:

```<code>    [Key]
    [Column("CurriculumId",Order =1)]
    public long CurriculumId { get; set; }

    [Key]
    [Column("PersonTypeId",Order =2)]
    public long PersonTypeId { get; set; }
</code>```

and:

```<code>    [Key]
    [ForeignKey("FK_CurriculumPersonType_CurriculumId")]
    public long CurriculumId { get; set; }

    [Key]
    [ForeignKey("FK_CurriculumPersonType_PersonTypeId")]
    public long PersonTypeId { get; set; }
</code>```

None of these seem to work.  (This is Entity Framework 6.2.0)

I have looked through similar postings on stack overflow and other sites, but non seem to solve my issue.  I think I just need another set of eyes.

Here are the tables:

```<code>CREATE TABLE [dbo].[CurriculumPersonType]
(
[CurriculumId] BIGINT NOT NULL,
[PersonTypeId] BIGINT NOT NULL,
primary key ([CurriculumId], [PersonTypeId]),
CONSTRAINT [FK_CurriculumPersonType_PersonTypeId] FOREIGN KEY ([PersonTypeId]) REFERENCES [dbo].[PersonType] ([Id]),
CONSTRAINT [FK_CurriculumPersonType_CurriculumId] FOREIGN KEY ([CurriculumId]) REFERENCES [dbo].[Curriculum] ([Id])
)

CREATE TABLE [dbo].[PersonType]
(
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
    [Name] VARCHAR(50) NOT NULL,
)

CREATE TABLE [dbo].[Curriculum]
(
[Id] BIGINT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[Name] varchar(500) NULL,
)
</code>```

The other 2 entity models:

```<code>public class Curriculum
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
}

public class PersonType
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
}
</code>```

And the DBContext:

```<code>public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext() : base("ApplicationDbContext")
    {

    }

    public DbSet<Curriculum> Curriculums { get; set; }
    public DbSet<CurriculumPersonType> CurriculumPersonTypes { get; set; }
    public DbSet<PersonType> PersonTypes { get; set; }
}
</code>```

My application has other tables/models etc, but whenever I try to hit any of them, I get the error above.

Just playing around, I added a PK to the CurriculumPersonType table & model, and everything works fine.  Of course I don't want to do that, because that will allow duplicate values, but it seems to be hung up on the model not having a property named "Id".

New Table/Model:

```<code>CREATE TABLE [dbo].[CurriculumPersonType]
(
    [Id] BIGINT NOT NULL IDENTITY(1,1),
    [CurriculumId] BIGINT NOT NULL,
    [PersonTypeId] BIGINT NOT NULL,
    CONSTRAINT [FK_CurriculumPersonType_PersonTypeId] FOREIGN KEY ([PersonTypeId]) REFERENCES [dbo].[PersonType] ([Id]),
    CONSTRAINT [FK_CurriculumPersonType_CurriculumId] FOREIGN KEY ([CurriculumId]) REFERENCES [dbo].[Curriculum] ([Id]),
    CONSTRAINT [PK_CurriculumPersonType] PRIMARY KEY ([Id])
)

public class CurriculumPersonType
{
    [Key]
    public long Id { get; set; }

    //[Key]
    //[Column(Order = 1)]
    public long CurriculumId { get; set; }

    //[Key]
    //[Column(Order = 2)]
    public long PersonTypeId { get; set; }

    [ForeignKey("CurriculumId")]
    public virtual Curriculum Curriculum { get; set; }

    [ForeignKey("PersonTypeId")]
    public virtual PersonType PersonType { get; set; }
}
</code>```

答:
The error "EntityType '{x}' has no key defined. Define the key for this EntityType." indicates that the DBSet is pointing at a class other than your above Entity definition. In the DbContext, using the in DbSet<CurriculumPersonType> right click on CurriculumPersonType and "Go to Definition". My hunch is that you have another class called CurriculumPersonType defined that is being referenced by the DbContext (such as an auto-generated class).  If the classes are in different assemblies, make sure all assemblies are built & up to date, though referenced assemblies should automatically be rebuilt when changed.

When you have an entity with a composite key using just [Key] without the column order the exception message is:

"Unable to determine composite primary key ordering for type '{x}'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys."

Column order can be assigned by using [Key, Column(Order=0)] No need to specify the column name in the attribute if the property name matches. Using orders of 0,1 or 1,2 are fine, it's just used to order the columns in the key.

Body:
I have an asp.net MVC web application with 3 tables, PersonType, Curriculum, and CurriculumPersonType which ties the other 2 tables together with a composite key. I am trying to run a LINQ statement against that table.  When I run my code, I get an "EntityType: EntitySet 'CurriculumPersonType' has no key defined.  Define the key to this entity type." error.

I started with this in my model:

public class CurriculumPersonType
{
    [Key]
    public long CurriculumId { get; set; }

    [Key]
    public long PersonTypeId { get; set; }

    [ForeignKey("PersonTypeId")]
    public virtual PersonType PersonType { get; set; }

    [ForeignKey("CurriculumId")]
    public virtual Curriculum Curriculum { get; set; }
}

and have tried adding other annotations such as:

    [Key]
    [Column("CurriculumId",Order =1)]
    public long CurriculumId { get; set; }

    [Key]
    [Column("PersonTypeId",Order =2)]
    public long PersonTypeId { get; set; }

and:

    [Key]
    [ForeignKey("FK_CurriculumPersonType_CurriculumId")]
    public long CurriculumId { get; set; }

    [Key]
    [ForeignKey("FK_CurriculumPersonType_PersonTypeId")]
    public long PersonTypeId { get; set; }

None of these seem to work.  (This is Entity Framework 6.2.0)

I have looked through similar postings on stack overflow and other sites, but non seem to solve my issue.  I think I just need another set of eyes.

Here are the tables:

CREATE TABLE [dbo].[CurriculumPersonType]
(
[CurriculumId] BIGINT NOT NULL,
[PersonTypeId] BIGINT NOT NULL,
primary key ([CurriculumId], [PersonTypeId]),
CONSTRAINT [FK_CurriculumPersonType_PersonTypeId] FOREIGN KEY ([PersonTypeId]) REFERENCES [dbo].[PersonType] ([Id]),
CONSTRAINT [FK_CurriculumPersonType_CurriculumId] FOREIGN KEY ([CurriculumId]) REFERENCES [dbo].[Curriculum] ([Id])
)

CREATE TABLE [dbo].[PersonType]
(
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
    [Name] VARCHAR(50) NOT NULL,
)

CREATE TABLE [dbo].[Curriculum]
(
[Id] BIGINT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[Name] varchar(500) NULL,
)

The other 2 entity models:

public class Curriculum
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
}

public class PersonType
{
    [Key]
    public long Id { get; set; }
    public string Name { get; set; }
}

And the DBContext:

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext() : base("ApplicationDbContext")
    {

    }

    public DbSet<Curriculum> Curriculums { get; set; }
    public DbSet<CurriculumPersonType> CurriculumPersonTypes { get; set; }
    public DbSet<PersonType> PersonTypes { get; set; }
}

My application has other tables/models etc, but whenever I try to hit any of them, I get the error above.

Just playing around, I added a PK to the CurriculumPersonType table & model, and everything works fine.  Of course I don't want to do that, because that will allow duplicate values, but it seems to be hung up on the model not having a property named "Id".

New Table/Model:

CREATE TABLE [dbo].[CurriculumPersonType]
(
    [Id] BIGINT NOT NULL IDENTITY(1,1),
    [CurriculumId] BIGINT NOT NULL,
    [PersonTypeId] BIGINT NOT NULL,
    CONSTRAINT [FK_CurriculumPersonType_PersonTypeId] FOREIGN KEY ([PersonTypeId]) REFERENCES [dbo].[PersonType] ([Id]),
    CONSTRAINT [FK_CurriculumPersonType_CurriculumId] FOREIGN KEY ([CurriculumId]) REFERENCES [dbo].[Curriculum] ([Id]),
    CONSTRAINT [PK_CurriculumPersonType] PRIMARY KEY ([Id])
)

public class CurriculumPersonType
{
    [Key]
    public long Id { get; set; }

    //[Key]
    //[Column(Order = 1)]
    public long CurriculumId { get; set; }

    //[Key]
    //[Column(Order = 2)]
    public long PersonTypeId { get; set; }

    [ForeignKey("CurriculumId")]
    public virtual Curriculum Curriculum { get; set; }

    [ForeignKey("PersonTypeId")]
    public virtual PersonType PersonType { get; set; }
}


问:
Segmentation fault in btree implementation
Can anyone please help in removing this segmentation fault. I am working on this code for a week still unable to debug this. This code is a Btree implementation. The insertion part is working properly but there is an segmentation fault in deletion. I am unable to debug it, can anyone please help?

I have given the input based on this link (have converted alphabet value to ASCII value)
http://cis.stvincent.edu/html/tutorials/swd/btree/btree.html

When I delete the first H (equivalent ASCII value) it works properly, but when I delete T (equivalent ASCII value) I will get a segmentation fault.

```<code>    #include<stdio.h>
    #include<stdlib.h>
    #define M 5

    struct node{
        int n; /* n < M No. of keys in node will always less than order of B
              tree */
        int keys[M-1]; /*array of keys*/
        struct node *p[M]; /* (n+1 pointers will be in use) */
    }*root=NULL;

    enum KeyStatus { Duplicate,SearchFailure,Success,InsertIt,LessKeys };

    void insert(int key);
    void display(struct node *root,int);
    void DelNode(int x);
    void search(int x);
    enum KeyStatus ins(struct node *r, int x, int* y, struct node** u);
    int searchPos(int x,int *key_arr, int n);
    enum KeyStatus del(struct node *r, int x);
    int input_array[20]= {65,67,71,78,72,69,75,81,77,70,87,76,84,90,68,80,82,88,89,83};
    int main()
    {

        int choice, i,key = 11;
        printf("Creation of B tree for node %d\n",M);
        while(1)
        {
            printf("1.Insert\n");
            printf("2.Delete\n");
            printf("3.Search\n");
            printf("4.Display\n");
            printf("5.Quit\n");
            printf("Enter your choice : ");
            scanf("%d",&choice);

            switch(choice)
            {
                case 1:
                    //printf("Enter the key : ");
                    //scanf("%d",&key);
                    //for(i=0;i<20;i++)
                     for(i=0;i<20;i++)
                     {
                        key = input_array[i];
                        insert(key);
                     }
                    //insert(key++);
                    //insert(key);
                    break;
                case 2:
                    printf("Enter the key : ");
                    scanf("%d",&key);
                    DelNode(key);
                    break;
                case 3:
                    printf("Enter the key : ");
                    scanf("%d",&key);
                    search(key);
                    break;
                case 4:
                    printf("Btree is :\n");
                    display(root,0);
                    break;
                case 5:
                    exit(1);
                default:
                    printf("Wrong choice\n");
                    break;
            }/*End of switch*/
        }/*End of while*/
        return 0;
    }/*End of main()*/

    void insert(int key)
    {
        struct node *newnode;
        int upKey;
        enum KeyStatus value;
        value = ins(root, key, &upKey, &newnode);
        if (value == Duplicate)
            printf("Key already available\n");
        if (value == InsertIt)
        {
            struct node *uproot = root;
            root=malloc(sizeof(struct node));
            root->n = 1;
            root->keys[0] = upKey;
            root->p[0] = uproot;
            root->p[1] = newnode;
        }/*End of if */
    }/*End of insert()*/

    enum KeyStatus ins(struct node *ptr, int key, int *upKey,struct node **newnode)
    {
        struct node *newPtr, *lastPtr;
        int pos, i, n,splitPos;
        int newKey, lastKey;
        enum KeyStatus value;
        if (ptr == NULL)
        {
            *newnode = NULL;
            *upKey = key;
            return InsertIt;
        }
        n = ptr->n;
        pos = searchPos(key, ptr->keys, n);

        if (pos < n && key == ptr->keys[pos])
            return Duplicate;
        value = ins(ptr->p[pos], key, &newKey, &newPtr);
        if (value != InsertIt)
            return value;
        /*If keys in node is less than M-1 where M is order of B tree*/
        if (n < M - 1)
        {
            pos = searchPos(newKey, ptr->keys, n);
            /*Shifting the key and pointer right for inserting the new key*/
            for (i=n; i>pos; i--)
            {
                ptr->keys[i] = ptr->keys[i-1];
                ptr->p[i+1] = ptr->p[i];
            }
            /*Key is inserted at exact location*/
            ptr->keys[pos] = newKey;
            ptr->p[pos+1] = newPtr;
            ++ptr->n; /*incrementing the number of keys in node*/
            return Success;
        }/*End of if */
        /*If keys in nodes are maximum and position of node to be inserted is
          last*/
        if (pos == M - 1)
        {
            lastKey = newKey;
            lastPtr = newPtr;
        }
        else /*If keys in node are maximum and position of node to be inserted
               is not last*/
        {
            lastKey = ptr->keys[M-2];
            lastPtr = ptr->p[M-1];
            for (i=M-2; i>pos; i--)
            {
                ptr->keys[i] = ptr->keys[i-1];
                ptr->p[i+1] = ptr->p[i];
            }
            ptr->keys[pos] = newKey;
            ptr->p[pos+1] = newPtr;
        }
        splitPos = (M - 1)/2;
        (*upKey) = ptr->keys[splitPos];

        (*newnode)=malloc(sizeof(struct node));/*Right node after split*/
        ptr->n = splitPos; /*No. of keys for left splitted node*/
        (*newnode)->n = M-1-splitPos;/*No. of keys for right splitted node*/
        for (i=0; i < (*newnode)->n; i++)
        {
            (*newnode)->p[i] = ptr->p[i + splitPos + 1];
            if(i < (*newnode)->n - 1)
                (*newnode)->keys[i] = ptr->keys[i + splitPos + 1];
            else
                (*newnode)->keys[i] = lastKey;
        }
        (*newnode)->p[(*newnode)->n] = lastPtr;
        return InsertIt;
    }/*End of ins()*/

    void display(struct node *ptr, int blanks)
    {
        if (ptr)
        {
            int i;
            for(i=1;i<=blanks;i++)
                printf(" ");
            for (i=0; i < ptr->n; i++)
                printf("%d ",ptr->keys[i]);
            printf("\n");
            for (i=0; i <= ptr->n; i++)
                display(ptr->p[i], blanks+10);
        }/*End of if*/
    }/*End of display()*/

    void search(int key)
    {
        int pos, i, n;
        struct node *ptr = root;
        printf("Search path:\n");
        while (ptr)
        {
            n = ptr->n;
            for (i=0; i < ptr->n; i++)
                printf(" %d",ptr->keys[i]);
            printf("\n");
            pos = searchPos(key, ptr->keys, n);
            if (pos < n && key == ptr->keys[pos])
            {
                printf("Key %d found in position %d of last dispalyednode\n",key,i);
                return;
            }
            ptr = ptr->p[pos];
        }
        printf("Key %d is not available\n",key);
    }/*End of search()*/

    int searchPos(int key, int *key_arr, int n)
    {
        int pos=0;
        while (pos < n && key > key_arr[pos])
            pos++;
        return pos;
    }/*End of searchPos()*/

    void DelNode(int key)
    {
        struct node *uproot;
        enum KeyStatus value;
        value = del(root,key);
        switch (value)
        {
            case SearchFailure:
                printf("Key %d is not available\n",key);
                break;
            case LessKeys:
                uproot = root;
                root = root->p[0];
                free(uproot);
                break;
        }/*End of switch*/
    }/*End of delnode()*/

    enum KeyStatus del(struct node *ptr, int key)
    {
        int pos, i, pivot, n ,min;
        int *key_arr;
        enum KeyStatus value;
        struct node **p,*lptr,*rptr;

        if (ptr == NULL)
            return SearchFailure;
        /*Assigns values of node*/
        n=ptr->n;
        key_arr = ptr->keys;
        p = ptr->p;
        min = (M - 1)/2;/*Minimum number of keys*/

        pos = searchPos(key, key_arr, n);
        if (p[0] == NULL)
        {
            if (pos == n || key < key_arr[pos])
                return SearchFailure;
            /*Shift keys and pointers left*/
            for (i=pos+1; i < n; i++)
            {
                key_arr[i-1] = key_arr[i];
                p[i] = p[i+1];
            }
            return --ptr->n >= (ptr==root ? 1 : min) ? Success : LessKeys;
        }/*End of if */

        if (pos < n && key == key_arr[pos])
        {
            struct node *qp = p[pos], *qp1;
            int nkey;
            while(1)
            {
                nkey = qp->n;
                qp1 = qp->p[nkey];
                if (qp1 == NULL)
                    break;
                qp = qp1;
            }/*End of while*/
            key_arr[pos] = qp->keys[nkey-1];
            qp->keys[nkey - 1] = key;
        }/*End of if */
        value = del(p[pos], key);
        if (value != LessKeys)
            return value;

        if (pos > 0 && p[pos-1]->n > min)
        {
            pivot = pos - 1; /*pivot for left and right node*/
            lptr = p[pivot];
            rptr = p[pos];
            /*Assigns values for right node*/
            rptr->p[rptr->n + 1] = rptr->p[rptr->n];
            for (i=rptr->n; i>0; i--)
            {
                rptr->keys[i] = rptr->keys[i-1];
                rptr->p[i] = rptr->p[i-1];
            }
            rptr->n++;
            rptr->keys[0] = key_arr[pivot];
            rptr->p[0] = lptr->p[lptr->n];
            key_arr[pivot] = lptr->keys[--lptr->n];
            return Success;
        }/*End of if */
        if (pos > min)
        {
            pivot = pos; /*pivot for left and right node*/
            lptr = p[pivot];
            rptr = p[pivot+1];
            /*Assigns values for left node*/
            lptr->keys[lptr->n] = key_arr[pivot];
            lptr->p[lptr->n + 1] = rptr->p[0];
            key_arr[pivot] = rptr->keys[0];
            lptr->n++;
            rptr->n--;
            for (i=0; i < rptr->n; i++)
            {
                rptr->keys[i] = rptr->keys[i+1];
                rptr->p[i] = rptr->p[i+1];
            }/*End of for*/
            rptr->p[rptr->n] = rptr->p[rptr->n + 1];
            return Success;
        }/*End of if */

        if(pos == n)
            pivot = pos-1;
        else
            pivot = pos;

        lptr = p[pivot];
        rptr = p[pivot+1];
        /*merge right node with left node*/
        lptr->keys[lptr->n] = key_arr[pivot];
        lptr->p[lptr->n + 1] = rptr->p[0];
        for (i=0; i < rptr->n; i++)
        {
            lptr->keys[lptr->n + 1 + i] = rptr->keys[i];
            lptr->p[lptr->n + 2 + i] = rptr->p[i+1];
        }
        lptr->n = lptr->n + rptr->n +1;
        free(rptr); /*Remove right node*/
        for (i=pos+1; i < n; i++)
        {
            key_arr[i-1] = key_arr[i];
            p[i] = p[i+1];
        }
        return --ptr->n >= (ptr == root ? 1 : min) ? Success : LessKeys;
    }/*End of del()*/
</code>```

What could be the problem?

答:
Without knowing exactly how this should work I can say that you write outside of the  p vector on

```<code>    for (i=0; i < rptr->n; i++)
    {
        lptr->keys[lptr->n + 1 + i] = rptr->keys[i];
        // When you delete key 84, rptr->n is 4 at one point which takes you outside
        // p[M]
        lptr->p[lptr->n + 2 + i] = rptr->p[i+1];
    }
</code>```

Valgrind is a good tool to use, and I found this problem by valgrind -v --leak-check=full <your executable>

Body:
Can anyone please help in removing this segmentation fault. I am working on this code for a week still unable to debug this. This code is a Btree implementation. The insertion part is working properly but there is an segmentation fault in deletion. I am unable to debug it, can anyone please help?

I have given the input based on this link (have converted alphabet value to ASCII value)
http://cis.stvincent.edu/html/tutorials/swd/btree/btree.html

When I delete the first H (equivalent ASCII value) it works properly, but when I delete T (equivalent ASCII value) I will get a segmentation fault.

    #include<stdio.h>
    #include<stdlib.h>
    #define M 5

    struct node{
        int n; /* n < M No. of keys in node will always less than order of B
              tree */
        int keys[M-1]; /*array of keys*/
        struct node *p[M]; /* (n+1 pointers will be in use) */
    }*root=NULL;

    enum KeyStatus { Duplicate,SearchFailure,Success,InsertIt,LessKeys };

    void insert(int key);
    void display(struct node *root,int);
    void DelNode(int x);
    void search(int x);
    enum KeyStatus ins(struct node *r, int x, int* y, struct node** u);
    int searchPos(int x,int *key_arr, int n);
    enum KeyStatus del(struct node *r, int x);
    int input_array[20]= {65,67,71,78,72,69,75,81,77,70,87,76,84,90,68,80,82,88,89,83};
    int main()
    {

        int choice, i,key = 11;
        printf("Creation of B tree for node %d\n",M);
        while(1)
        {
            printf("1.Insert\n");
            printf("2.Delete\n");
            printf("3.Search\n");
            printf("4.Display\n");
            printf("5.Quit\n");
            printf("Enter your choice : ");
            scanf("%d",&choice);

            switch(choice)
            {
                case 1:
                    //printf("Enter the key : ");
                    //scanf("%d",&key);
                    //for(i=0;i<20;i++)
                     for(i=0;i<20;i++)
                     {
                        key = input_array[i];
                        insert(key);
                     }
                    //insert(key++);
                    //insert(key);
                    break;
                case 2:
                    printf("Enter the key : ");
                    scanf("%d",&key);
                    DelNode(key);
                    break;
                case 3:
                    printf("Enter the key : ");
                    scanf("%d",&key);
                    search(key);
                    break;
                case 4:
                    printf("Btree is :\n");
                    display(root,0);
                    break;
                case 5:
                    exit(1);
                default:
                    printf("Wrong choice\n");
                    break;
            }/*End of switch*/
        }/*End of while*/
        return 0;
    }/*End of main()*/

    void insert(int key)
    {
        struct node *newnode;
        int upKey;
        enum KeyStatus value;
        value = ins(root, key, &upKey, &newnode);
        if (value == Duplicate)
            printf("Key already available\n");
        if (value == InsertIt)
        {
            struct node *uproot = root;
            root=malloc(sizeof(struct node));
            root->n = 1;
            root->keys[0] = upKey;
            root->p[0] = uproot;
            root->p[1] = newnode;
        }/*End of if */
    }/*End of insert()*/

    enum KeyStatus ins(struct node *ptr, int key, int *upKey,struct node **newnode)
    {
        struct node *newPtr, *lastPtr;
        int pos, i, n,splitPos;
        int newKey, lastKey;
        enum KeyStatus value;
        if (ptr == NULL)
        {
            *newnode = NULL;
            *upKey = key;
            return InsertIt;
        }
        n = ptr->n;
        pos = searchPos(key, ptr->keys, n);

        if (pos < n && key == ptr->keys[pos])
            return Duplicate;
        value = ins(ptr->p[pos], key, &newKey, &newPtr);
        if (value != InsertIt)
            return value;
        /*If keys in node is less than M-1 where M is order of B tree*/
        if (n < M - 1)
        {
            pos = searchPos(newKey, ptr->keys, n);
            /*Shifting the key and pointer right for inserting the new key*/
            for (i=n; i>pos; i--)
            {
                ptr->keys[i] = ptr->keys[i-1];
                ptr->p[i+1] = ptr->p[i];
            }
            /*Key is inserted at exact location*/
            ptr->keys[pos] = newKey;
            ptr->p[pos+1] = newPtr;
            ++ptr->n; /*incrementing the number of keys in node*/
            return Success;
        }/*End of if */
        /*If keys in nodes are maximum and position of node to be inserted is
          last*/
        if (pos == M - 1)
        {
            lastKey = newKey;
            lastPtr = newPtr;
        }
        else /*If keys in node are maximum and position of node to be inserted
               is not last*/
        {
            lastKey = ptr->keys[M-2];
            lastPtr = ptr->p[M-1];
            for (i=M-2; i>pos; i--)
            {
                ptr->keys[i] = ptr->keys[i-1];
                ptr->p[i+1] = ptr->p[i];
            }
            ptr->keys[pos] = newKey;
            ptr->p[pos+1] = newPtr;
        }
        splitPos = (M - 1)/2;
        (*upKey) = ptr->keys[splitPos];

        (*newnode)=malloc(sizeof(struct node));/*Right node after split*/
        ptr->n = splitPos; /*No. of keys for left splitted node*/
        (*newnode)->n = M-1-splitPos;/*No. of keys for right splitted node*/
        for (i=0; i < (*newnode)->n; i++)
        {
            (*newnode)->p[i] = ptr->p[i + splitPos + 1];
            if(i < (*newnode)->n - 1)
                (*newnode)->keys[i] = ptr->keys[i + splitPos + 1];
            else
                (*newnode)->keys[i] = lastKey;
        }
        (*newnode)->p[(*newnode)->n] = lastPtr;
        return InsertIt;
    }/*End of ins()*/

    void display(struct node *ptr, int blanks)
    {
        if (ptr)
        {
            int i;
            for(i=1;i<=blanks;i++)
                printf(" ");
            for (i=0; i < ptr->n; i++)
                printf("%d ",ptr->keys[i]);
            printf("\n");
            for (i=0; i <= ptr->n; i++)
                display(ptr->p[i], blanks+10);
        }/*End of if*/
    }/*End of display()*/

    void search(int key)
    {
        int pos, i, n;
        struct node *ptr = root;
        printf("Search path:\n");
        while (ptr)
        {
            n = ptr->n;
            for (i=0; i < ptr->n; i++)
                printf(" %d",ptr->keys[i]);
            printf("\n");
            pos = searchPos(key, ptr->keys, n);
            if (pos < n && key == ptr->keys[pos])
            {
                printf("Key %d found in position %d of last dispalyednode\n",key,i);
                return;
            }
            ptr = ptr->p[pos];
        }
        printf("Key %d is not available\n",key);
    }/*End of search()*/

    int searchPos(int key, int *key_arr, int n)
    {
        int pos=0;
        while (pos < n && key > key_arr[pos])
            pos++;
        return pos;
    }/*End of searchPos()*/

    void DelNode(int key)
    {
        struct node *uproot;
        enum KeyStatus value;
        value = del(root,key);
        switch (value)
        {
            case SearchFailure:
                printf("Key %d is not available\n",key);
                break;
            case LessKeys:
                uproot = root;
                root = root->p[0];
                free(uproot);
                break;
        }/*End of switch*/
    }/*End of delnode()*/

    enum KeyStatus del(struct node *ptr, int key)
    {
        int pos, i, pivot, n ,min;
        int *key_arr;
        enum KeyStatus value;
        struct node **p,*lptr,*rptr;

        if (ptr == NULL)
            return SearchFailure;
        /*Assigns values of node*/
        n=ptr->n;
        key_arr = ptr->keys;
        p = ptr->p;
        min = (M - 1)/2;/*Minimum number of keys*/

        pos = searchPos(key, key_arr, n);
        if (p[0] == NULL)
        {
            if (pos == n || key < key_arr[pos])
                return SearchFailure;
            /*Shift keys and pointers left*/
            for (i=pos+1; i < n; i++)
            {
                key_arr[i-1] = key_arr[i];
                p[i] = p[i+1];
            }
            return --ptr->n >= (ptr==root ? 1 : min) ? Success : LessKeys;
        }/*End of if */

        if (pos < n && key == key_arr[pos])
        {
            struct node *qp = p[pos], *qp1;
            int nkey;
            while(1)
            {
                nkey = qp->n;
                qp1 = qp->p[nkey];
                if (qp1 == NULL)
                    break;
                qp = qp1;
            }/*End of while*/
            key_arr[pos] = qp->keys[nkey-1];
            qp->keys[nkey - 1] = key;
        }/*End of if */
        value = del(p[pos], key);
        if (value != LessKeys)
            return value;

        if (pos > 0 && p[pos-1]->n > min)
        {
            pivot = pos - 1; /*pivot for left and right node*/
            lptr = p[pivot];
            rptr = p[pos];
            /*Assigns values for right node*/
            rptr->p[rptr->n + 1] = rptr->p[rptr->n];
            for (i=rptr->n; i>0; i--)
            {
                rptr->keys[i] = rptr->keys[i-1];
                rptr->p[i] = rptr->p[i-1];
            }
            rptr->n++;
            rptr->keys[0] = key_arr[pivot];
            rptr->p[0] = lptr->p[lptr->n];
            key_arr[pivot] = lptr->keys[--lptr->n];
            return Success;
        }/*End of if */
        if (pos > min)
        {
            pivot = pos; /*pivot for left and right node*/
            lptr = p[pivot];
            rptr = p[pivot+1];
            /*Assigns values for left node*/
            lptr->keys[lptr->n] = key_arr[pivot];
            lptr->p[lptr->n + 1] = rptr->p[0];
            key_arr[pivot] = rptr->keys[0];
            lptr->n++;
            rptr->n--;
            for (i=0; i < rptr->n; i++)
            {
                rptr->keys[i] = rptr->keys[i+1];
                rptr->p[i] = rptr->p[i+1];
            }/*End of for*/
            rptr->p[rptr->n] = rptr->p[rptr->n + 1];
            return Success;
        }/*End of if */

        if(pos == n)
            pivot = pos-1;
        else
            pivot = pos;

        lptr = p[pivot];
        rptr = p[pivot+1];
        /*merge right node with left node*/
        lptr->keys[lptr->n] = key_arr[pivot];
        lptr->p[lptr->n + 1] = rptr->p[0];
        for (i=0; i < rptr->n; i++)
        {
            lptr->keys[lptr->n + 1 + i] = rptr->keys[i];
            lptr->p[lptr->n + 2 + i] = rptr->p[i+1];
        }
        lptr->n = lptr->n + rptr->n +1;
        free(rptr); /*Remove right node*/
        for (i=pos+1; i < n; i++)
        {
            key_arr[i-1] = key_arr[i];
            p[i] = p[i+1];
        }
        return --ptr->n >= (ptr == root ? 1 : min) ? Success : LessKeys;
    }/*End of del()*/

What could be the problem?

Body:
Without knowing exactly how this should work I can say that you write outside of the  p vector on

    for (i=0; i < rptr->n; i++)
    {
        lptr->keys[lptr->n + 1 + i] = rptr->keys[i];
        // When you delete key 84, rptr->n is 4 at one point which takes you outside
        // p[M]
        lptr->p[lptr->n + 2 + i] = rptr->p[i+1];
    }

Valgrind is a good tool to use, and I found this problem by valgrind -v --leak-check=full <your executable>


问:
Is there any way to compile code ( C/ C++ ) with in browser?
This question may sound crazy.Is there anything browser based compiler out there
?</p>

答:
It is possible to run native binaries in a browser using an x86 emulator in JavaScript, so a C compiler could run in a browser in this way.

It is also possible to write a "self-hosting" C-to-WebAssembly compiler that runs in a browser, such as emception.


问:
Can someone help explain why it returns a different sum?
var x = 10 + Number("1"+"6");
console.log(x);

returns: 26

var y = 10 + 1 + 6;
console.log(y);

returns: 17

答:
You're adding two strings together inside Number(...):

```<code>"1" + "6" = "16"
</code>```

So the line basically comes down to:

```<code>var x = 10 + Number( "16" )
> 26
</code>```

Body:
You're adding two strings together inside Number(...):

"1" + "6" = "16"

So the line basically comes down to:

var x = 10 + Number( "16" )
> 26


问:
When autofilter returns nothing, clear filter and end macro
I have this macro that runs a filter and delete the results, but today the filter results brought back nothing and i got an error.
I want to make it so that when the filter in the AV range results in nothing, just clear the filter and end sub

this problem occurs after the "Em Aberto- 00" filter.

I have tried some suggestions, but being a noob that i am, most of them i could'nt understand what was going on

```<code>Columns("J:J").Select
Selection.TextToColumns Destination:=Range("J1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True
Columns("K:K").Select
Selection.TextToColumns Destination:=Range("K1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True

Columns("BD:BF").Select
Selection.Replace What:="", Replacement:="0", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

Range("A1").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.AutoFilter
ActiveWindow.SmallScroll ToRight:=31
Range("AV3").Select
ActiveSheet.Range("$A$1:$BK$3018").AutoFilter Field:=48, Criteria1:= _
    "Em Aberto- 00"

Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
End Sub
</code>```

答:
Do something like this:

```<code>Dim myRange As Range

On Error Resume Next
Set myRange = Range("your range here").SpecialCells(xlVisible)
On Error GoTo 0

If myRange Is Nothing Then
    Exit Sub
Else
'do stuff
End If
</code>```

You should avoid  using SELECT, just Google "how to avoid using SELECT VBA"

Body:
I have this macro that runs a filter and delete the results, but today the filter results brought back nothing and i got an error.
I want to make it so that when the filter in the AV range results in nothing, just clear the filter and end sub

this problem occurs after the "Em Aberto- 00" filter.

I have tried some suggestions, but being a noob that i am, most of them i could'nt understand what was going on

Columns("J:J").Select
Selection.TextToColumns Destination:=Range("J1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True
Columns("K:K").Select
Selection.TextToColumns Destination:=Range("K1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True

Columns("BD:BF").Select
Selection.Replace What:="", Replacement:="0", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

Range("A1").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.AutoFilter
ActiveWindow.SmallScroll ToRight:=31
Range("AV3").Select
ActiveSheet.Range("$A$1:$BK$3018").AutoFilter Field:=48, Criteria1:= _
    "Em Aberto- 00"

Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.EntireRow.Delete
ActiveSheet.ShowAllData
End Sub

Body:
Do something like this:

Dim myRange As Range

On Error Resume Next
Set myRange = Range("your range here").SpecialCells(xlVisible)
On Error GoTo 0

If myRange Is Nothing Then
    Exit Sub
Else
'do stuff
End If

You should avoid  using SELECT, just Google "how to avoid using SELECT VBA"