问:
How do I remove this listener in OnDestroy (Android Firebase)?
This is my ValueEventListener in OnCreate method. I want to destroy this is OnDestroy method because it might be causing memory leak and also I've read it that it's a good practice to do so. </p>

```<code>mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            display_author = (String) dataSnapshot.child("author").getValue();
            display_quote = (String) dataSnapshot.child("quote").getValue();
            display_pic_url = (String) dataSnapshot.child("pic_url").getValue();
            categoryData=(String) dataSnapshot.child("catg").getValue();
            display_prof=(String) dataSnapshot.child("prof").getValue();
            copyQuote = (display_quote + " - " +display_author);
            try {
                author.setText(display_author);
                quote.setText(display_quote);
                category.setText(categoryData);
                profession.setText(display_prof);
                Glide.with(SingleExploreQuotes.this).load(display_pic_url).override(192, 192).into(profile_img);

            } catch (Exception e) {
                finish();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
</code>```

答:
With reference of @Frank van Puffelen's answer. Change code to:

```<code>private ValueEventListener mListener;
mListener = mDatabaseRef.addValueEventListener(new ValueEventListener()
{...}
</code>```

in onDestry() :

```<code>@Override
    protected void onDestroy() {
        super.onDestroy();
        mDatabaseRef.removeEventListener(mListener);
    }
</code>```

Body:
This is my ValueEventListener in OnCreate method. I want to destroy this is OnDestroy method because it might be causing memory leak and also I've read it that it's a good practice to do so.

mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            display_author = (String) dataSnapshot.child("author").getValue();
            display_quote = (String) dataSnapshot.child("quote").getValue();
            display_pic_url = (String) dataSnapshot.child("pic_url").getValue();
            categoryData=(String) dataSnapshot.child("catg").getValue();
            display_prof=(String) dataSnapshot.child("prof").getValue();
            copyQuote = (display_quote + " - " +display_author);
            try {
                author.setText(display_author);
                quote.setText(display_quote);
                category.setText(categoryData);
                profession.setText(display_prof);
                Glide.with(SingleExploreQuotes.this).load(display_pic_url).override(192, 192).into(profile_img);

            } catch (Exception e) {
                finish();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

Body:
With reference of @Frank van Puffelen's answer. Change code to:

private ValueEventListener mListener;
mListener = mDatabaseRef.addValueEventListener(new ValueEventListener()
{...}

in onDestry() :

@Override
    protected void onDestroy() {
        super.onDestroy();
        mDatabaseRef.removeEventListener(mListener);
    }


来源: stackexchange

问:
Multiple Views - One ViewModel MVVM Light in SL4
Greetings -

I am writing an app that ultimately will need two UI implementations. The first will be the standard app that the majority of our clients will use. The second is a custom implementation that our biggest client is asking us to design for them. This is more than just swapping out a style or skin... in some instances, we use an Accordion (RadPanelBar, truly) for one version, but will be using a TabControl in the other.

Because I'm using EventToCommand, the ViewModel code is identical. I just modeled this using a tab control & a RadPanelBar, and the effect was the same... simply wire my EventToCommand to the proper controls, and everything worked as expected.

I understand that the View to ViewModel relationship is typically 1:1. In my scenario, I want it to be 2:1, where every viewModel has 2 associated views. With about 50 views required per app, that's 100 Views total to 50 ViewModels.

First question - can this be done?
Second question - am I on the right track?
Third question - Given a "yes" to first question, How does implemention work? Do i need to duplicate code in my Locator to wire up ViewModel1 with View1A and View1B?

Thanks,

Scott

答:
I think that your approach is correct.

I think that is really stupid if we need to have 2 VM for 2 Views that does the same thing.

The 1:1 scenario is when you have views-vm that does different things not for two representations of the same thing.

How to do that? You don't have to duplicate code in the locator. Just wire the two views to the same ViewModel (already on the Locator) in the DataContext property.

ContentLicense: CC BY-SA 2.5


问:
DQL Doctrine query translation
I have my scores table where I have multiple scores for 1 user. What I am trying to do is to select all highest scores for each user.

I am trying to do the fallowing in Doctrine DQL:

```<code>        SELECT * FROM scores s1
        LEFT OUTER JOIN scores s2 ON
          s1.user_id = s2.user_id
          AND ((s1.score < s2.score) OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        WHERE s2.score IS NULL
        ORDER BY s1.score DESC
        LIMIT 10
</code>```

My current state is:

```<code>    $rowQuery = $this->getEntityManager()->createQuery('
        SELECT s1 FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
            LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
        ON (
            s1.user = s2.user
            AND
            (s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        )
        WHERE s2.score IS NULL
        AND s1.date_added BETWEEN :monday AND :sunday
        ORDER BY s1.score DESC
    ');

    $rowQuery->setParameter('monday', $startDate->format('Y-m-d'))
             ->setParameter('sunday', $endDate->format('Y-m-d'));
    $rowQuery->setMaxResults($limit);

    return $rowQuery->getResult();
</code>```

And I am getting the following error:

```<code>[Syntax Error] line 0, col 188: Error: Expected Literal, got '�'
</code>```

What am I doing wrong?

答:
This should work in DQL, ON part handles by doctrine if you have defined any mapping for your entities if not and still want to join 2 entities with a common attribute you can use WITH clause

```<code>SELECT s1
FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
    LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
    WITH s1.user = s2.user
    AND CASE WHEN s1.score = s2.score
            THEN s1.date_added < s2.date_added
            ELSE s1.score < s2.score
    END
WHERE s2.score IS NULL
AND s1.date_added BETWEEN :monday AND :sunday
ORDER BY s1.score DESC
</code>```

OR

```<code>SELECT s1
FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
    LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
    WITH s1.user = s2.user
    AND (
        s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added)
    )
WHERE s2.score IS NULL
AND s1.date_added BETWEEN :monday AND :sunday
ORDER BY s1.score DESC
</code>```

ContentLicense: CC BY-SA 3.0

Title: DQL Doctrine query translation

Body:
I have my scores table where I have multiple scores for 1 user. What I am trying to do is to select all highest scores for each user.

I am trying to do the fallowing in Doctrine DQL:

        SELECT * FROM scores s1
        LEFT OUTER JOIN scores s2 ON
          s1.user_id = s2.user_id
          AND ((s1.score < s2.score) OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        WHERE s2.score IS NULL
        ORDER BY s1.score DESC
        LIMIT 10

My current state is:

    $rowQuery = $this->getEntityManager()->createQuery('
        SELECT s1 FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
            LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
        ON (
            s1.user = s2.user
            AND
            (s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added))
        )
        WHERE s2.score IS NULL
        AND s1.date_added BETWEEN :monday AND :sunday
        ORDER BY s1.score DESC
    ');

    $rowQuery->setParameter('monday', $startDate->format('Y-m-d'))
             ->setParameter('sunday', $endDate->format('Y-m-d'));
    $rowQuery->setMaxResults($limit);

    return $rowQuery->getResult();

And I am getting the following error:

[Syntax Error] line 0, col 188: Error: Expected Literal, got '�'

What am I doing wrong?

Body:
This should work in DQL, ON part handles by doctrine if you have defined any mapping for your entities if not and still want to join 2 entities with a common attribute you can use WITH clause

SELECT s1
FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
    LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
    WITH s1.user = s2.user
    AND CASE WHEN s1.score = s2.score
            THEN s1.date_added < s2.date_added
            ELSE s1.score < s2.score
    END
WHERE s2.score IS NULL
AND s1.date_added BETWEEN :monday AND :sunday
ORDER BY s1.score DESC

OR

SELECT s1
FROM \Digital\ApplicationBundle\Entity\ChallengeScore s1
    LEFT OUTER JOIN \Digital\ApplicationBundle\Entity\ChallengeScore s2
    WITH s1.user = s2.user
    AND (
        s1.score < s2.score OR (s1.score = s2.score AND s1.date_added < s2.date_added)
    )
WHERE s2.score IS NULL
AND s1.date_added BETWEEN :monday AND :sunday
ORDER BY s1.score DESC

ContentLicense: CC BY-SA 4.0


问:
ASP.Net MVC Exporting WebGrid to PDF
I am trying to export a WebGrid to PDF and I have the following code in my controller:

```<code>public FileStreamResult CreatePdf()
{
    List<CertificationListViewModel> all = new List<CertificationListViewModel>();

    using (DBEntities db = new DBEntities())
    {
        all = db.Certifications.ToList();
    }

    WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);

    string gridHtml = grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Name", "Nome"),
            grid.Column("Classification", "Classificação"),
            grid.Column("Date", "Data de Realização")
        )
    ).ToString();
    string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
    var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
    using (var input = new MemoryStream(bytes))
    {
        var output = new MemoryStream();
        var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;
        document.Open();

        var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
        xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
        document.Close();
        output.Position = 0;
        return new FileStreamResult(output, "application/pdf");
    }
}
</code>```

The code is giving me a error in this line:

```<code>all = db.Certifications.ToList();
</code>```

This is the error that shows up:

Cannot implicitly convert type 'System.Collections.Generic.List<HIQTraining.Model.Certification>' to 'System.Collections.Generic.List<HIQTrainingSite.ViewModel.CertificationListViewModel>'

I am not sure what the error is if someone has an ideia of what it could be I would appreciate !

P.S : I have the following iTextSharp libraries exported in the project:

```<code>using iTextSharp.text;
using iTextSharp.text.pdf;
</code>```

答:
The error is telling you that your values are of different types.  (Which makes sense, I wouldn't expect "view" models to be stored in the database.)  So you'll need to in some way convert from one to the other.

For example, if your view model can be simply built with an object initializer, then you can construct it in a .Select() projection:

```<code>all = db.Certifications.ToList()
      .Select(c => new CertificationListViewModel {
          SomeProperty = c.SomeProperty,
          AnotherProperty = c.AnotherProperty
      });
</code>```

If there are many properties, libraries like AutoMapper can help with that.

Conversely, if you actually wanted the list of database models, then you'd need to change the type of your variable to match that:

```<code>List<Certification> all = new List<Certification>();
</code>```

Title: ASP.Net MVC Exporting WebGrid to PDF

Body:
I am trying to export a WebGrid to PDF and I have the following code in my controller:

public FileStreamResult CreatePdf()
{
    List<CertificationListViewModel> all = new List<CertificationListViewModel>();

    using (DBEntities db = new DBEntities())
    {
        all = db.Certifications.ToList();
    }

    WebGrid grid = new WebGrid(source: all, canPage: false, canSort: false);

    string gridHtml = grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Name", "Nome"),
            grid.Column("Classification", "Classificação"),
            grid.Column("Date", "Data de Realização")
        )
    ).ToString();
    string exportData = String.Format("{0}{1}", "", gridHtml);
    var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
    using (var input = new MemoryStream(bytes))
    {
        var output = new MemoryStream();
        var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
        var writer = PdfWriter.GetInstance(document, output);
        writer.CloseStream = false;
        document.Open();

        var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
        xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
        document.Close();
        output.Position = 0;
        return new FileStreamResult(output, "application/pdf");
    }
}

The code is giving me a error in this line:

all = db.Certifications.ToList();

This is the error that shows up:

Cannot implicitly convert type 'System.Collections.Generic.List<HIQTraining.Model.Certification>' to 'System.Collections.Generic.List<HIQTrainingSite.ViewModel.CertificationListViewModel>'

I am not sure what the error is if someone has an ideia of what it could be I would appreciate !

P.S : I have the following iTextSharp libraries exported in the project:

using iTextSharp.text;
using iTextSharp.text.pdf;

Body:
The error is telling you that your values are of different types.  (Which makes sense, I wouldn't expect "view" models to be stored in the database.)  So you'll need to in some way convert from one to the other.

For example, if your view model can be simply built with an object initializer, then you can construct it in a .Select() projection:

all = db.Certifications.ToList()
      .Select(c => new CertificationListViewModel {
          SomeProperty = c.SomeProperty,
          AnotherProperty = c.AnotherProperty
      });

If there are many properties, libraries like AutoMapper can help with that.

Conversely, if you actually wanted the list of database models, then you'd need to change the type of your variable to match that:

List<Certification> all = new List<Certification>();


问:
Everything in my javascript file requires two clicks to trigger
This is my whole JS.

```<code>$(document).ready(function () {

$('#ee_2_').css('fill', '#F26522');
$('#lt_2_').css('fill', '#F26522');
$('#lv_2_').css('fill', '#F26522');

//    $(".items .plusDelivered").hover(function(){
//        $(this).closest('.deliveredCategory');
//    })

$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});

$("#menu-primary-menu li").hover(function () {
    $('.navItems .menu-item a:before').css("display", 'inline-block');
});

$(window).on('mailsent.wpcf7', function () {
    $('.formFill').addClass('hide');
    $('.formSuccess').removeClass('hide')
});

$(window).on('wpcf7:invalid', function () {
    var epasts = $("input.epasts").val();
    var vards = $("input.vards").val();
    var uzvards = $("input.uzvards").val();
    var zina = $("textarea.zina").val();
    var talrunis = $("input.numurs").val();
    if (/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i.test(epasts) == !1) {
        $('input.epasts').css("border-color", 'red');
        $('input.epasts').css("color", 'red');
    }
    if (vards.length <= 2) {
        $('input.vards').css("border-color", 'red');
        $('input.vards').css("color", 'red');
    }
    if (uzvards.length <= 2) {
        $('input.uzvards').css("border-color", 'red');
        $('input.uzvards').css("color", 'red');
    }
    if (talrunis.length !== 0) {
        if (/^(0|[1-9][0-9]*)$/i.test(talrunis) == !1) {
            $('input.numurs').css("border-color", 'red');
            $('input.numurs').css("color", 'red');
        }
    }
    if (zina.length >= 10) {
       $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');
    } else {

        $('.formContent .zina').css("border-color", 'red');
        $('.formContent .zina').css("color", 'red');
    }
    if ($(this).val().length > 10) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'red');
        $(this).css("color", 'red');
    }
});

$("img.exit").click(function () {
    $('.popUpForm').addClass('hide')
});

$('.formContent input').click(function () {
    $(this).css("border-color", '#fed051');

});

$('.formContent input').blur(function () {

    if ($(this).val()) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'black');
        $(this).css("color", 'black');
    }
});

$('.formContent .zina').blur(function () {

    if ($(this).val().length > 10) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'red');
        $(this).css("color", 'red');
    }
});

$(".apply").click(function () {
    $('.popUpForm').removeClass('hide')
});

$('.accordion-item .heading').on('click mouseenter', function (e) {
    e.preventDefault();
    var $content = $(this).next();
    $content.toggle();
    $('.accordion-item .content').not($content).hide();
    $('.accordion-item .heading').not(this).find('.plus-minus-toggle').addClass('collapsed')
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
});

$('.accordion-item .content').on('mouseleave', function (e) {
    e.preventDefault();
    var $content = $(this).next();
    $content.toggle();
    $('.accordion-item .content').not($content).hide();
    $('.accordion-item .heading').not(this).find('.plus-minus-toggle').addClass('collapsed')
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
});

$(".full-service-cycle .accordion").mouseleave(function () {
    $('.plus-minus-toggle').addClass('collapsed');
    $('.accordion-item .content').hide();
});

$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});
$(".toggledOverlay").click(function () {
    $(this).css("display", 'none');
    $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
    $(".menuContainer").css("display", "none")
});
$(".cls-6, .cls-5, .cls-4").css("fill", '#F26522');
$("#ee_2_").on('click mouseover', function () {
    $(this).css('fill', "#FABC14");
    $('#lv_2_').css('fill', '#F26522');
    $('#lt_2_').css('fill', '#F26522');
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").removeClass("hide")
});
$("#lv_2_").on('click mouseover', function () {
    $(this).css('fill', "#FABC14");
    $(".lv .latvian").removeClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").addClass("hide");
    $('#lt_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
$("#lt_2_").on('click mouseover', function () {
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").removeClass("hide");
    $(".lv .estonian").addClass("hide");
    $(this).css('fill', "#FABC14");
    $('#lv_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
$(".area").mouseleave(function () {
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").addClass("hide");
    $("#lt_2_").css('fill', "#F26522");
    $('#lv_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) {
    return p.toString() === "[object SafariRemoteNotification]"
})(!window.safari || safari.pushNotification);
var isIE = !1 || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
if (isEdge == !0) {
    $(".map svg.chrome").removeClass("chrome").addClass("edge")
}
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isBlink = (isChrome || isOpera) && !!window.CSS
});
</code>```

Bear in mind that this is the javascript file for the whole site, but still, actions such as, opening hamburger menu, require 2 clicks to trigger.

It was working all the time, I did some changes a while ago and only now realized the issue, and now I don't recall what did I change.

Any ideas?

EDIT: I am talking only about the click actions, other actions work just fine.

答:
It's happening because of your if statement in the below code:

```<code>$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});
</code>```

Your original src of the image is /wp-content/themes/balticpremier/assets/menu.png and not http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png

Change it to the following to fix it:

```<code>$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png' || $(".mobNav img").attr('src') == '/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});
</code>```

A tip: when facing issues like these try to open the Chrome Developer Tools and observe what happens when you click the link. In your case you can see the srcchange in the first click.

Body:
This is my whole JS.

$(document).ready(function () {

$('#ee_2_').css('fill', '#F26522');
$('#lt_2_').css('fill', '#F26522');
$('#lv_2_').css('fill', '#F26522');

//    $(".items .plusDelivered").hover(function(){
//        $(this).closest('.deliveredCategory');
//    })

$('.deliveredCategory').on('click mouseenter mouseleave', function () {
    $(this).find(".expandableClient").toggle();
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
    $(this).find('.dotHide').toggle();
});

$("#menu-primary-menu li").hover(function () {
    $('.navItems .menu-item a:before').css("display", 'inline-block');
});

$(window).on('mailsent.wpcf7', function () {
    $('.formFill').addClass('hide');
    $('.formSuccess').removeClass('hide')
});

$(window).on('wpcf7:invalid', function () {
    var epasts = $("input.epasts").val();
    var vards = $("input.vards").val();
    var uzvards = $("input.uzvards").val();
    var zina = $("textarea.zina").val();
    var talrunis = $("input.numurs").val();
    if (/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i.test(epasts) == !1) {
        $('input.epasts').css("border-color", 'red');
        $('input.epasts').css("color", 'red');
    }
    if (vards.length <= 2) {
        $('input.vards').css("border-color", 'red');
        $('input.vards').css("color", 'red');
    }
    if (uzvards.length <= 2) {
        $('input.uzvards').css("border-color", 'red');
        $('input.uzvards').css("color", 'red');
    }
    if (talrunis.length !== 0) {
        if (/^(0|[1-9][0-9]*)$/i.test(talrunis) == !1) {
            $('input.numurs').css("border-color", 'red');
            $('input.numurs').css("color", 'red');
        }
    }
    if (zina.length >= 10) {
       $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');
    } else {

        $('.formContent .zina').css("border-color", 'red');
        $('.formContent .zina').css("color", 'red');
    }
    if ($(this).val().length > 10) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'red');
        $(this).css("color", 'red');
    }
});

$("img.exit").click(function () {
    $('.popUpForm').addClass('hide')
});

$('.formContent input').click(function () {
    $(this).css("border-color", '#fed051');

});

$('.formContent input').blur(function () {

    if ($(this).val()) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'black');
        $(this).css("color", 'black');
    }
});

$('.formContent .zina').blur(function () {

    if ($(this).val().length > 10) {

        $(this).css("border-color", '#fed051');
        $(this).css("color", '#fed051');
        $('input.send').css("color", 'black');

        //           return false;
    } else {

        $(this).css("border-color", 'red');
        $(this).css("color", 'red');
    }
});

$(".apply").click(function () {
    $('.popUpForm').removeClass('hide')
});

$('.accordion-item .heading').on('click mouseenter', function (e) {
    e.preventDefault();
    var $content = $(this).next();
    $content.toggle();
    $('.accordion-item .content').not($content).hide();
    $('.accordion-item .heading').not(this).find('.plus-minus-toggle').addClass('collapsed')
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
});

$('.accordion-item .content').on('mouseleave', function (e) {
    e.preventDefault();
    var $content = $(this).next();
    $content.toggle();
    $('.accordion-item .content').not($content).hide();
    $('.accordion-item .heading').not(this).find('.plus-minus-toggle').addClass('collapsed')
    $(this).find('.plus-minus-toggle').toggleClass('collapsed');
});

$(".full-service-cycle .accordion").mouseleave(function () {
    $('.plus-minus-toggle').addClass('collapsed');
    $('.accordion-item .content').hide();
});

$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});
$(".toggledOverlay").click(function () {
    $(this).css("display", 'none');
    $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
    $(".menuContainer").css("display", "none")
});
$(".cls-6, .cls-5, .cls-4").css("fill", '#F26522');
$("#ee_2_").on('click mouseover', function () {
    $(this).css('fill', "#FABC14");
    $('#lv_2_').css('fill', '#F26522');
    $('#lt_2_').css('fill', '#F26522');
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").removeClass("hide")
});
$("#lv_2_").on('click mouseover', function () {
    $(this).css('fill', "#FABC14");
    $(".lv .latvian").removeClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").addClass("hide");
    $('#lt_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
$("#lt_2_").on('click mouseover', function () {
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").removeClass("hide");
    $(".lv .estonian").addClass("hide");
    $(this).css('fill', "#FABC14");
    $('#lv_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
$(".area").mouseleave(function () {
    $(".lv .latvian").addClass("hide");
    $(".lv .lithuanian").addClass("hide");
    $(".lv .estonian").addClass("hide");
    $("#lt_2_").css('fill', "#F26522");
    $('#lv_2_').css('fill', '#F26522');
    $('#ee_2_').css('fill', '#F26522')
});
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) {
    return p.toString() === "[object SafariRemoteNotification]"
})(!window.safari || safari.pushNotification);
var isIE = !1 || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
if (isEdge == !0) {
    $(".map svg.chrome").removeClass("chrome").addClass("edge")
}
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isBlink = (isChrome || isOpera) && !!window.CSS
});

Bear in mind that this is the javascript file for the whole site, but still, actions such as, opening hamburger menu, require 2 clicks to trigger.

It was working all the time, I did some changes a while ago and only now realized the issue, and now I don't recall what did I change.

Any ideas?

EDIT: I am talking only about the click actions, other actions work just fine.

Body:
It's happening because of your if statement in the below code:

$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});

Your original src of the image is /wp-content/themes/balticpremier/assets/menu.png and not http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png

Change it to the following to fix it:

$(".mobNav img").click(function () {
    if ($(".mobNav img").attr('src') == 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png' || $(".mobNav img").attr('src') == '/wp-content/themes/balticpremier/assets/menu.png') {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/exit.png');
        $(".toggledOverlay").css("display", "block");
        $(".menuContainer").css("display", "block")
    } else {
        $(".mobNav img").attr('src', 'http://balticpremier.sem.lv/wp-content/themes/balticpremier/assets/menu.png');
        $(".toggledOverlay").css("display", "none");
        $(".menuContainer").css("display", "none")
    }
});

A tip: when facing issues like these try to open the Chrome Developer Tools and observe what happens when you click the link. In your case you can see the srcchange in the first click.


问:
How can I toggle classes so that clicking the body will toggle off a dropdown menu and change the background on the remaining item (jquery)?
There is a menu dropdown comprised of the expand/collapse button (#client-select) and the dropdown menu (.client-select-dd). The menu itself works just fine except that I want it to also be collapsible if the user clicks anywhere outside the menu instead of specifically having to click the button again.

Initially the menu is collapsed, so the first click changes the background on the menu button(#client-select) and makes the dropdown options visible(.client-select-dd). This first click also adds a class to the body(.client-deactivate). Clicking on (#client-select) again collapses the menu and restores the button image-background.

In my mind, clicking on the body while the menu is open (and has the class ".client-deactivate") should collapse the menu and remove .client-deactivate, but clicking on the body does absolutely nothing. Thanks for any help all of you can provide.

```<code>$("#client-select").click (function() {
  $("body").toggleClass("client-deactivate");
  $(".client-select-close").toggleClass("client-select-open");
  $(".client-select-dd").toggle();
});

$(".client-deactivate").click (function() {
  $(".client-select-open").toggleClass("client-select-close");
  $(".client-select-dd").toggle();
});
</code>```

答:
This is probably because when the click handler is first read by the browser, there is no ".client-deactivate" class on the body tag. Also, you don't want to toggle anything when you click on the body, because then if the menu is collapsed and you clicked on the body, it would expand the menu. I assume that you only want the body click handler to close the menu if it's already open.

Try changing the second click handler to:

```<code>$("body").click(function() {
  if($("body").hasClass("client-deactivate") {
    $(".client-select-open").toggleClass("client-select-close");
    $(".client-select-dd").toggle();
    $("body").removeClass("client-deactivate");
  }
});
</code>```

You might also consider replacing these toggle functions with removeClass, just to be sure that clicking on the body doesn't expand the menu... Like if another function were to collapse the menu but doesn't remove the "client-deactivate" class to the body, then clicking on the body would then still have the class name and run the above code, toggling the menu to the open position.

Body:
There is a menu dropdown comprised of the expand/collapse button (#client-select) and the dropdown menu (.client-select-dd). The menu itself works just fine except that I want it to also be collapsible if the user clicks anywhere outside the menu instead of specifically having to click the button again.

Initially the menu is collapsed, so the first click changes the background on the menu button(#client-select) and makes the dropdown options visible(.client-select-dd). This first click also adds a class to the body(.client-deactivate). Clicking on (#client-select) again collapses the menu and restores the button image-background.

In my mind, clicking on the body while the menu is open (and has the class ".client-deactivate") should collapse the menu and remove .client-deactivate, but clicking on the body does absolutely nothing. Thanks for any help all of you can provide.

$("#client-select").click (function() {
  $("body").toggleClass("client-deactivate");
  $(".client-select-close").toggleClass("client-select-open");
  $(".client-select-dd").toggle();
});

$(".client-deactivate").click (function() {
  $(".client-select-open").toggleClass("client-select-close");
  $(".client-select-dd").toggle();
});

Body:
This is probably because when the click handler is first read by the browser, there is no ".client-deactivate" class on the body tag. Also, you don't want to toggle anything when you click on the body, because then if the menu is collapsed and you clicked on the body, it would expand the menu. I assume that you only want the body click handler to close the menu if it's already open.

Try changing the second click handler to:

$("body").click(function() {
  if($("body").hasClass("client-deactivate") {
    $(".client-select-open").toggleClass("client-select-close");
    $(".client-select-dd").toggle();
    $("body").removeClass("client-deactivate");
  }
});

You might also consider replacing these toggle functions with removeClass, just to be sure that clicking on the body doesn't expand the menu... Like if another function were to collapse the menu but doesn't remove the "client-deactivate" class to the body, then clicking on the body would then still have the class name and run the above code, toggling the menu to the open position.


问:
Table with position: fixed doesn't scroll with overflow: scroll
I have two tables: the first is a header, the second contains data. I want to see the header when I scroll down, so its table has position: fixed. The tables can be too large to be shown on the screen at once, so I wrapped them in a div with overflow: scroll;.

My problem can be see here: https://jsfiddle.net/xa86wgw9/3/

When I scroll down, the header doesn't move; that's what I want. But when I scroll to the right, the header stay on the left... is there a way to have the two table stay aligned ? css and javascript can be used.

EDIT: I'm currently working on IE10, so position: sticky isn't an option.

答:
As far as I know its impossible to make the table itself scrollable.

As your second table also uses the scrolloptions of #firstDiv, you need to do the same for the first one, since the first one is fixed and so not counted inside the #firstDiv for width properties.

to achieve this I added a wrapperdiv around the first table and made the wrapper fixed with

```<code>overflow: scroll;
</code>```

EDIT:
See the fiddle: - sry forgot to update the link, here you go
https://jsfiddle.net/xa86wgw9/8/

for the second part of your question you probably need some javascript to make both tables scroll at the same time. but you should try this part yourself first (also I lack time to apply the solution now)

Body:
As far as I know its impossible to make the table itself scrollable.

As your second table also uses the scrolloptions of #firstDiv, you need to do the same for the first one, since the first one is fixed and so not counted inside the #firstDiv for width properties.

to achieve this I added a wrapperdiv around the first table and made the wrapper fixed with

overflow: scroll;

EDIT:
See the fiddle: - sry forgot to update the link, here you go
https://jsfiddle.net/xa86wgw9/8/

for the second part of your question you probably need some javascript to make both tables scroll at the same time. but you should try this part yourself first (also I lack time to apply the solution now)


问:
Is there some kind of functionality, where a pointer dereference gives an rvalue?
Is there some kind of functionality, where a pointer dereference gives an rvalue?

So, a usual pointer gives an lvalue:

```<code>Foo *p = ...;

fn(p[42]);    // p[42] is an lvalue
</code>```

I'd like to have p[42] return an rvalue, so a fn(Foo &&) can be called for fn(p[42]):

```<code><some_pointer_type> p = ...;

fn(p[42]);    // I'd like to have p[42] be an rvalue, so an fn(Foo &&) would be called
</code>```

Note: I'd like to have p has this functionality, the pointer type should have this information, that dereferencing it should give an rvalue.

答:
By means of std::move() you can perform an unconditional cast to a rvalue.

```<code>fn(std::move(p[42]));
</code>```

The name move is actually misleading here: nothing is being moved, but a cast is being performed.

Consider then writing a pointer template Ptr whose operators * and [] are overloaded to return a rvalue:

```<code>#include <utility>

class Foo {};

template<typename T>
class Ptr {
public:
    Ptr(T* ptr): ptr_{ptr} {}
    T&& operator*() { return std::move(*ptr_); }
    T&& operator[](int idx) { return std::move(*(ptr_ + idx)); }
private:
    T* ptr_;
};

void fn(Foo&& x) { return; }
void fn(const Foo& x) { return; }

int main()
{
    Foo foo[50];
    Ptr<Foo> p{&foo[0]};

    // call void fn(Foo&&)
    fn(p[42]);
}
</code>```

Body:
Is there some kind of functionality, where a pointer dereference gives an rvalue?

So, a usual pointer gives an lvalue:

Foo *p = ...;

fn(p[42]);    // p[42] is an lvalue

I'd like to have p[42] return an rvalue, so a fn(Foo &&) can be called for fn(p[42]):

<some_pointer_type> p = ...;

fn(p[42]);    // I'd like to have p[42] be an rvalue, so an fn(Foo &&) would be called

Note: I'd like to have p has this functionality, the pointer type should have this information, that dereferencing it should give an rvalue.

Body:
By means of std::move() you can perform an unconditional cast to a rvalue.

fn(std::move(p[42]));

The name move is actually misleading here: nothing is being moved, but a cast is being performed.

Consider then writing a pointer template Ptr whose operators * and [] are overloaded to return a rvalue:

#include <utility>

class Foo {};

template<typename T>
class Ptr {
public:
    Ptr(T* ptr): ptr_{ptr} {}
    T&& operator*() { return std::move(*ptr_); }
    T&& operator[](int idx) { return std::move(*(ptr_ + idx)); }
private:
    T* ptr_;
};

void fn(Foo&& x) { return; }
void fn(const Foo& x) { return; }

int main()
{
    Foo foo[50];
    Ptr<Foo> p{&foo[0]};

    // call void fn(Foo&&)
    fn(p[42]);
}


问:
batch read ini values
I'm started study about batch and i got a problem

i have one ini file

sample.ini

```<code>[Path_Info]
path1=c:\one
path2=c:\two
</code>```

sample.bat

```<code>FOR /F "tokens=*" %%A IN ('type "sample.ini"') DO SET %%A
:True (
 xcopy %path1%\*.* %BU_Temp%\%name1% /e /h /k /y /i /s /d:%M%-%D%-%Y%
 xcopy %path2%\*.* %BU_Temp%\%name2% /e /h /k /y /i /s /d:%M%-%D%-%Y%
 )
</code>```

At that time i want use 'for' to xcopy and make one line?

so i try to xcopy %path%%i%~~ , xcopy %path%%%I and xcopy %path*% .... anyway

but I failed.. please help me/

I'm not good in english.. sorry

答:
Use delims to split at the equal sign = the n tokens should be 1,2 or 1,* meaning %%a will be assigned to the text before the = and %%b will be assigned to the text after =

```<code>@echo off
setlocal enabledelayedexpansion
For /F "tokens=1,*delims==" %%a in ('type "sample.ini"') DO (
    set pathvar=%%b
    echo !pathvar!
)
</code>```

There is more you need to do still to get it to copy to the correct directories as each path seems to go to another %name% in your case.

Title: batch read ini values

Body:
I'm started study about batch and i got a problem

i have one ini file

sample.ini

[Path_Info]
path1=c:\one
path2=c:\two

sample.bat

FOR /F "tokens=*" %%A IN ('type "sample.ini"') DO SET %%A
:True (
 xcopy %path1%\*.* %BU_Temp%\%name1% /e /h /k /y /i /s /d:%M%-%D%-%Y%
 xcopy %path2%\*.* %BU_Temp%\%name2% /e /h /k /y /i /s /d:%M%-%D%-%Y%
 )

At that time i want use 'for' to xcopy and make one line?

so i try to xcopy %path%%i%~~ , xcopy %path%%%I and xcopy %path*% .... anyway

but I failed.. please help me/

I'm not good in english.. sorry

Body:
Use delims to split at the equal sign = the n tokens should be 1,2 or 1,* meaning %%a will be assigned to the text before the = and %%b will be assigned to the text after =

@echo off
setlocal enabledelayedexpansion
For /F "tokens=1,*delims==" %%a in ('type "sample.ini"') DO (
    set pathvar=%%b
    echo !pathvar!
)

There is more you need to do still to get it to copy to the correct directories as each path seems to go to another %name% in your case.


问:
Protractor : Click on webpage to save number input
I am trying to automate application using the protractor (for angular application), I am providing some numbers in the input field (type=number) but have to click anywhere on the webpage to save changes. How to click anywhere on the webpage.</p>

答:
Please provide html.

I usually click on footer if there is id by which I can select it.

But you can click on any element on page.


问:
How to get ansible to stay on the machine after finishing a task?
I am using ansible to run a task which starts up build engines. Once they have all started, ansible returns control to me and I see that they all stop at once. When I add an async: 10 flag to the running of the script it works, but the problem is when there are multiple build engines it takes longer than 10 seconds for them to start, which makes the async kind of null.

I have tried using a

```<code>- pause:
  seconds: 10
</code>```

task below the running of the script, but the build engines stop, then it does the pause.

What I am asking is - Is there a way to make ansible stick around on the machine for a few seconds after it has finished running the command (i.e. after control has been returned to user)?

答: While it's unclear what kind of build system you are using and why it can't properly daemonize itself, i think wait_for module is perfectly suited for your needs. You can wait for tcp port to come up, if your build system opens one, wait for some file to be created, parse log files for string, indicating that build has started successfully or simply wait for some time.</p>

Body:
I am using ansible to run a task which starts up build engines. Once they have all started, ansible returns control to me and I see that they all stop at once. When I add an async: 10 flag to the running of the script it works, but the problem is when there are multiple build engines it takes longer than 10 seconds for them to start, which makes the async kind of null.

I have tried using a

- pause:
  seconds: 10

task below the running of the script, but the build engines stop, then it does the pause.

What I am asking is - Is there a way to make ansible stick around on the machine for a few seconds after it has finished running the command (i.e. after control has been returned to user)?


问:
How can I set a proxy server for gem?
I am unable to install SASS through command prompt.

I tried below steps

```<code>c:\gem install sass
</code>```

I am getting below error:

```<code>ERROR:  Could not find a valid gem 'sass' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it. - connect(2) (https://rubygems.org/latest_specs.4.8.gz)
</code>```

Please help me,

答:
In Addition to @Yifei answer. If you have special character like @, &, $

You have to go with percent-encode | encode the special characters. E.g. instead of this:

```<code>http://foo:B@r@http-gateway.domain.org:80
</code>```

you write this:

```<code>http://foo:B%40r@http-gateway.domain.org:80
</code>```

So @ gets replaced with %40.

Title: How can I set a proxy server for gem?

Body:
I am unable to install SASS through command prompt.

I tried below steps

c:\gem install sass

I am getting below error:

ERROR:  Could not find a valid gem 'sass' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - Errno::ECONNREFUSED: No connection could be made because the target machine actively refused it. - connect(2) (https://rubygems.org/latest_specs.4.8.gz)

Please help me,

Body:
In Addition to @Yifei answer. If you have special character like @, &, $

You have to go with percent-encode | encode the special characters. E.g. instead of this:

http://foo:B@r@http-gateway.domain.org:80

you write this:

http://foo:B%40r@http-gateway.domain.org:80

So @ gets replaced with %40.


问:
Customize window.open
Hi I am using Electron and I want to change the window.open function so that, by default, it opens popups hidden/invisible, minimized and some other things.

I found this code:
window.open(url, windowName, 'toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,left=10000, top=10000, width=10, height=10, visible=none', '');

But I want to make it so that all calls of window.open have these windowFeatures by default, but still accepts the original url and windowName parameters.

答:
You can do something like this:

const {app, BrowserWindow, webContents} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow() // you may create more
  // general callback
  const onWindowOpen = (event, url, frameName) => {
    event.preventDefault()
    const win = new BrowserWindow({
      show: false,
      frame: false,
      resizable: false,
      title: frameName
    })
    win.loadURL(url)
    win.webContents.on('new-window', onWindowOpen)
    event.newGuest = win
  }
  // wait every dom-ready
  Promise.all(BrowserWindow.getAllWindows().map(br => {
    return new Promise((resolve) => {
      br.webContents.once('dom-ready', () => { resolve() })
    })
  })).then(() => {
    // register every new-window callback
    webContents.getAllWebContents().forEach(wc => {
      wc.on('new-window', onWindowOpen)
    })
  })
  // load URL(s) for BrowserWindow(s)
  win.loadURL(path.resolve(__dirname, 'your.html'))
})
```

Here we add listeners to new-window event for every initially created BrowserWindows and for every BrowserWindow created by window.open calls. Newly created BrowserWindow is frameless, invisible and not resizable as it seems to be your goal altogether.

Hope this helps!

Title: Customize window.open

Body:
You can do something like this:

const {app, BrowserWindow, webContents} = require('electron')
const path = require('path')

app.once('ready', () => {
  let win = new BrowserWindow() // you may create more
  // general callback
  const onWindowOpen = (event, url, frameName) => {
    event.preventDefault()
    const win = new BrowserWindow({
      show: false,
      frame: false,
      resizable: false,
      title: frameName
    })
    win.loadURL(url)
    win.webContents.on('new-window', onWindowOpen)
    event.newGuest = win
  }
  // wait every dom-ready
  Promise.all(BrowserWindow.getAllWindows().map(br => {
    return new Promise((resolve) => {
      br.webContents.once('dom-ready', () => { resolve() })
    })
  })).then(() => {
    // register every new-window callback
    webContents.getAllWebContents().forEach(wc => {
      wc.on('new-window', onWindowOpen)
    })
  })
  // load URL(s) for BrowserWindow(s)
  win.loadURL(path.resolve(__dirname, 'your.html'))
})

Here we add listeners to new-window event for every initially created BrowserWindows and for every BrowserWindow created by window.open calls. Newly created BrowserWindow is frameless, invisible and not resizable as it seems to be your goal altogether.

Hope this helps!


问:
Where's FrameworkPropertyMetadata in UWP?
And/Or how do I define a DependencyProperty on my control that sepcifies AffectsMeasure?

EDIT: oh, just saw this - do I have to call InvalidateMeasure on this in the propertychangedhandler?

答:
Sorry. For UWP AffectsMeasure is not supported. For Framework 3+ it works. For default UWP binding I am working with CodeSnipped functionality. WIth the eventhandling you can act transparent. The result of my codeSnippet for UWP looks like this for my Model:

```<code>    #region IsSelected

    public static readonly DependencyProperty IsSelectedProperty =
        DependencyProperty.Register("IsSelected", typeof(bool), typeof(PositionModel),
            new PropertyMetadata((bool)false,
                new PropertyChangedCallback(OnIsSelectedChanged)));

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set { SetValue(IsSelectedProperty, value); }
    }

    private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PositionModel target = (PositionModel)d;
        bool oldIsSelected = (bool)e.OldValue;
        bool newIsSelected = target.IsSelected;
        target.OnIsSelectedChanged(oldIsSelected, newIsSelected);
    }

    protected virtual void OnIsSelectedChanged(bool oldIsSelected, bool newIsSelected)
    {
       // Do what your need in your property changed event
       // In my case, I just raise the PropertyChanged for PropertyChangedEventHandler
       // RaisePropertyChanged(nameof(IsSelected));
    }
    #endregion
</code>```

XAML:

```<code><Rectangle Fill="Black" Visibility="{x:Bind IsSelected, Mode=OneWay, Converter={StaticResource BoolToVis}}" />
</code>```

Windows 10, Store, VS 2017,
Microsoft.NETCore.UniversalWindowsPlatform Version 5.2.3

Body:
Sorry. For UWP AffectsMeasure is not supported. For Framework 3+ it works. For default UWP binding I am working with CodeSnipped functionality. WIth the eventhandling you can act transparent. The result of my codeSnippet for UWP looks like this for my Model:

    #region IsSelected

    public static readonly DependencyProperty IsSelectedProperty =
        DependencyProperty.Register("IsSelected", typeof(bool), typeof(PositionModel),
            new PropertyMetadata((bool)false,
                new PropertyChangedCallback(OnIsSelectedChanged)));

    public bool IsSelected
    {
        get { return (bool)GetValue(IsSelectedProperty); }
        set { SetValue(IsSelectedProperty, value); }
    }

    private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        PositionModel target = (PositionModel)d;
        bool oldIsSelected = (bool)e.OldValue;
        bool newIsSelected = target.IsSelected;
        target.OnIsSelectedChanged(oldIsSelected, newIsSelected);
    }

    protected virtual void OnIsSelectedChanged(bool oldIsSelected, bool newIsSelected)
    {
       // Do what your need in your property changed event
       // In my case, I just raise the PropertyChanged for PropertyChangedEventHandler
       // RaisePropertyChanged(nameof(IsSelected));
    }
    #endregion

XAML:

<Rectangle Fill="Black" Visibility="{x:Bind IsSelected, Mode=OneWay, Converter={StaticResource BoolToVis}}" />

Windows 10, Store, VS 2017,
Microsoft.NETCore.UniversalWindowsPlatform Version 5.2.3


问:
Calculation based on user input (c++ school project)
Hi everyone I am creating a simple c++ program to write user input to a text file in addition to calculating the information received. So far I am trying to convert dollars to yen, but for some reason I am at a roadblock where I am unable to figure out what is preventing the program from compiling the information.

```<code>//Dollars to Yen Project

#include <cstring>
#include <climits>
#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

class A
{
private:
    float dollars, yen;

public:
    void store(float);
    float convert();
};

void A::store(float dollars1)

{
    dollars = dollars1;
}

float A::convert() //mutators used

{
    yen = dollars*0.0089;
    return yen;
}

int main()

{

    float dollars;
    float yen;
    cout << "Welcome to Japan, you will need to convert Dollars into Yen to spend money here\n" << endl;
    string b;
    while (1)

    {

        cout << "Enter the amount in dollars to be converted\n";
        cin >> b;
        system("pause");
        if (b.find_first_not_of("1234567890.-") != string::npos) //input check validity
        {

            cout << "invalid number:" << b << endl;

        }

        else

        {

            break;

        }
    }

    float r = atof(b.c_str());
    A a;
    a.store(r);
    float c = a.convert();

    stringstream ss;
    ss << c;

    string s1 = ss.str();
    ofstream prog;

    prog.open("money.txt");
    prog << "The required amount of Yen is " + s1;
    prog.close();
    return 0;

}
</code>```

Any help would be appreciated. Thanks!!

答:
You first create the object for Class 'A' and then call the method.

```<code>A a; // object declaration
a=new A(); // object Creation

     or
A a=new A();
</code>```

and then call the methods like,
    a.store(r); a.convert();

Body:
Hi everyone I am creating a simple c++ program to write user input to a text file in addition to calculating the information received. So far I am trying to convert dollars to yen, but for some reason I am at a roadblock where I am unable to figure out what is preventing the program from compiling the information.

//Dollars to Yen Project

#include <cstring>
#include <climits>
#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

class A
{
private:
    float dollars, yen;

public:
    void store(float);
    float convert();
};

void A::store(float dollars1)

{
    dollars = dollars1;
}

float A::convert() //mutators used

{
    yen = dollars*0.0089;
    return yen;
}

int main()

{

    float dollars;
    float yen;
    cout << "Welcome to Japan, you will need to convert Dollars into Yen to spend money here\n" << endl;
    string b;
    while (1)

    {

        cout << "Enter the amount in dollars to be converted\n";
        cin >> b;
        system("pause");
        if (b.find_first_not_of("1234567890.-") != string::npos) //input check validity
        {

            cout << "invalid number:" << b << endl;

        }

        else

        {

            break;

        }
    }

    float r = atof(b.c_str());
    A a;
    a.store(r);
    float c = a.convert();

    stringstream ss;
    ss << c;

    string s1 = ss.str();
    ofstream prog;

    prog.open("money.txt");
    prog << "The required amount of Yen is " + s1;
    prog.close();
    return 0;

}

Any help would be appreciated. Thanks!!

Body:
You first create the object for Class 'A' and then call the method.

A a; // object declaration
a=new A(); // object Creation

     or
A a=new A();

and then call the methods like,
    a.store(r); a.convert();


问:
Python: OSError: [Errno 22] Invalid argument: '*.txt'
I have a script that I want to use in order to enumerate all file types in a folder:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import argparse
import magic
import os

# Argparse starts here
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None)
args = parser.parse_args()

for files in args.input:
    if magic.from_file(files,mime=True) == "text/plain":
        print (files, "=" , magic.from_file(files,mime=True) )
</code>```

it works pretty well when I input a file:

even when I input two files:

but not when I input ALL files:

The error says:

```<code>Traceback (most recent call last):
  File "Test.py", line 15, in <module>
    if magic.from_file(files,mime=True) == "text/plain":
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 135, in from_file
    return m.from_file(filename)
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 85, in from_file
    with open(filename):
OSError: [Errno 22] Invalid argument: '*.txt'
</code>```

But *.txt is exactly what I want to input; I also would like to input whatever file *.*

Is this a problem related to python-magic or caused by the way I input the files?

答:
If you want to use things like * then you have to "glob" the files. This can be confusing because the globbing can happen in many places. I'm not familiar with the shell you are using, but if you were using bash then bash would perform the glob before it gets passed to Python. In other words, if *.txt actually matches something, bash replaces it with the list of files and then passes that list to Python (as separate arguments). It's then your job to deal with an arbitrary number of arguments in Python (probably using argparse). If *.txt doesn't match anything then it doesn't get expanded and Python sees *.txt and you have to handle that as an error.

Here it looks like the globbing isn't happening which either means there is nothing for your shell to match or your shell doesn't do globbing. If it doesn't do globbing then you can do the globbing in Python using the glob module. Usually globbing is something that is done by the shell, though.

Body:
I have a script that I want to use in order to enumerate all file types in a folder:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import argparse
import magic
import os

# Argparse starts here
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None)
args = parser.parse_args()

for files in args.input:
    if magic.from_file(files,mime=True) == "text/plain":
        print (files, "=" , magic.from_file(files,mime=True) )

it works pretty well when I input a file:

even when I input two files:

but not when I input ALL files:

The error says:

Traceback (most recent call last):
  File "Test.py", line 15, in <module>
    if magic.from_file(files,mime=True) == "text/plain":
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 135, in from_file
    return m.from_file(filename)
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 85, in from_file
    with open(filename):
OSError: [Errno 22] Invalid argument: '*.txt'

But *.txt is exactly what I want to input; I also would like to input whatever file *.*

Is this a problem related to python-magic or caused by the way I input the files?


问:
Issue in 301 Redirect in Laravel 5.4
I update the route of my category pages from /listing/category1 to /products/category1

Old Route:

```<code>Route::get('/listing/{slug}', 'ProductsController@listing');
</code>```

New Route:

```<code>Route::get('/products/{slug}', 'ProductsController@listing');
</code>```

Now I want to permanently redirect (301) my Old Routes to New Routes.

There are just 4-5 categories so I have added below code in .htaccess file in public folder to redirect all old URL's to New URL's manually with Redirect 301 script but it didn't work.

```<code>Redirect 301 /listing/category1 https://www.example.com/products/category1
Redirect 301 /listing/category2 https://www.example.com/products/category2
</code>```

Please note website is having SSL certificate so links are starting with https.

There might be solution lying somewhere in Stack Overflow or some other website that I unable to found.

I tried adding below code in .htaccess file as well but of no use.

```<code>RewriteRule listing/category1 /products/category1 [R=301,L]
RewriteRule ^listing/([a-zA-Z0-9_-]+)$ products/category1
</code>```

Complete code of .htaccess file is below:

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteRule ^/?listing/([\w-]+)/?$ /products/$1 [L,NC,NE,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

So Please help me telling How to permanently redirect Old Routes to New Routes in Laravel 5.4?

Thanks in advance!

答:
This should work,</p>

```<code>Route::any('listing/{any?}', function ($any = null) {
    return Redirect::to('/products/'.$any, 301);
})->where('any', '.*');
</code>```

Title: Issue in 301 Redirect in Laravel 5.4

Body:
I update the route of my category pages from /listing/category1 to /products/category1

Old Route:

Route::get('/listing/{slug}', 'ProductsController@listing');

New Route:

Route::get('/products/{slug}', 'ProductsController@listing');

Now I want to permanently redirect (301) my Old Routes to New Routes.

There are just 4-5 categories so I have added below code in .htaccess file in public folder to redirect all old URL's to New URL's manually with Redirect 301 script but it didn't work.

Redirect 301 /listing/category1 https://www.example.com/products/category1
Redirect 301 /listing/category2 https://www.example.com/products/category2

Please note website is having SSL certificate so links are starting with https.

There might be solution lying somewhere in Stack Overflow or some other website that I unable to found.

I tried adding below code in .htaccess file as well but of no use.

RewriteRule listing/category1 /products/category1 [R=301,L]
RewriteRule ^listing/([a-zA-Z0-9_-]+)$ products/category1

Complete code of .htaccess file is below:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    RewriteRule ^/?listing/([\w-]+)/?$ /products/$1 [L,NC,NE,R=301]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

So Please help me telling How to permanently redirect Old Routes to New Routes in Laravel 5.4?

Thanks in advance!

Body:
This should work,

Route::any('listing/{any?}', function ($any = null) {
    return Redirect::to('/products/'.$any, 301);
})->where('any', '.*');


问:
Visual Studio Resources: Default Location for Add Existing File
In the Visual Studio Resources area, is there a way to set the default location in the file select dialog, when selecting "Add Existing File..."?

 Add Existing File...">

The default location, when clicking on that menu is:

C:\Program Files (x86)\Microsoft\Visual Studio\2017\Enterprise\Common7\IDE

True, it is a small thing, as selecting my Downloads folder or something else is easy, but I keep having to go somewhere else, usually my Downloads folder, and it would definitely save time to have the default location go somewhere else.

I know that the Open File common dialog, which Visual Studio uses, has the option in the initial structure to specify the initial (default) directory, so the only question is, if it is possible for the default directory to point somewhere else.

I am using Visual Studio 2017.

答:
You can use my Visual Commander extension to monitor for the Resources.AddExistingFile command and set your preferred directory before its execution. See the following C# extension example:

```<code>public class E : VisualCommanderExt.IExtension
{
    public void SetSite(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        events = DTE.Events;
        commandEvents = events.get_CommandEvents(null, 0);
        commands = DTE.Commands as EnvDTE80.Commands2;
        commandEvents.BeforeExecute += OnBeforeExecute;
    }

    public void Close()
    {
        commandEvents.BeforeExecute -= OnBeforeExecute;
    }

    private void OnBeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
    {
        string name = GetCommandName(Guid, ID);
        if (name == "Resources.AddExistingFile")
            System.IO.Directory.SetCurrentDirectory(@"c:\downloads");
    }

    private string GetCommandName(string Guid, int ID)
    {
        if (Guid == null)
            return "null";
        try
        {
            return commands.Item(Guid, ID).Name;
        }
        catch (System.Exception)
        {
        }
        return "";
    }

    private EnvDTE.Events events;
    private EnvDTE.CommandEvents commandEvents;
    private EnvDTE80.Commands2 commands;
}
</code>```

Body:
You can use my Visual Commander extension to monitor for the Resources.AddExistingFile command and set your preferred directory before its execution. See the following C# extension example:

public class E : VisualCommanderExt.IExtension
{
    public void SetSite(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
    {
        events = DTE.Events;
        commandEvents = events.get_CommandEvents(null, 0);
        commands = DTE.Commands as EnvDTE80.Commands2;
        commandEvents.BeforeExecute += OnBeforeExecute;
    }

    public void Close()
    {
        commandEvents.BeforeExecute -= OnBeforeExecute;
    }

    private void OnBeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
    {
        string name = GetCommandName(Guid, ID);
        if (name == "Resources.AddExistingFile")
            System.IO.Directory.SetCurrentDirectory(@"c:\downloads");
    }

    private string GetCommandName(string Guid, int ID)
    {
        if (Guid == null)
            return "null";
        try
        {
            return commands.Item(Guid, ID).Name;
        }
        catch (System.Exception)
        {
        }
        return "";
    }

    private EnvDTE.Events events;
    private EnvDTE.CommandEvents commandEvents;
    private EnvDTE80.Commands2 commands;
}


问:
Install4j - embedding jar into generated launcher
I have 'generated launcher' which executes my java application - aplication is in jar package.
Is there any way how to include jar into generated EXE file(launcher)? Customer wants to have only exe file, not jar in installed folder. Is there any way how to do it?</p>

答: There is no way to do that with install4j. You can do it with exe4j, by using the "JAR in EXE" mode and add the generated executable to the distribution tree instead of using the generated launcher. This only works for Windows, though.</p>


问:
How to handle image file download across multiple timezone?
I'm downloading an image file from a server, everyday after 9am in morning as per my Timezone. I also wish to display the file next day sharp at 9am

So I'll update that image file before 9am as per my Timezone, that'll make sure I get updated image file everyday. And all users get enough time to download that same image file i.e 23hrs and 45 minutes max.
* 15 mins are considered for updation purpose

Now the app works fine if users are from my Timezone, but it won't work if user are ahead then my Timezone. Chances are more of getting same image file twice.

Also if I choose to update file as per Timezone where 9am occurs first then users in other part won't get 23hrs and 45 mintues time to download.

I'd like to know any other solution rather than having seperate server for each timezone, as it is also difficult to implement in app too.

UPDATE
I think there is no way to provide a window of 23hrs and 45 mins max and displaying image next day at 9am. Both things can't be achieved in multiple timezones.

I'm using an image with hotlink i.e direct download link with same address.

答:
As I understand your requirements

Image upload happens every day between 8:45 and 9 AM in the uploader’s (your) time zone. Download is possible at all other times.

Each client should display the image from the previous day every day at 9 AM in the client’s time zone.

The client should be allowed a window of 23 h 45 min for downloading the image.

I also understand that it works nicely with clients in your own time zone.

Let’s look at the example from your comment to another answer: Upload happens from Asia/Kolkata time zone (India), and there is a client in Asia/Tokyo time zone (Japan). When the upload is finished at 9 in India, the time is already 12:30 in Japan. There are websites that will make such time zone conversions for you, for example Time Zone Converter – Time Difference Calculator. At 12:30 in Japan there are only 20 h 30 min left until the image should be displayed at 9 the next morning. So we cannot fulfil the requirements.

Let’s for a moment imagine that you settle with a 20 h 30 window (which you may not want to). For the client to find out when and how long that window is, it just needs to know the uploader’s time zone. It then converts 9:00 Asia/Kolkata to 12:30 Asia/Tokyo to discover that the window opens at 12:30. How to do the conversion in the client program, you can find that in other questions and answers, for example Timezone conversion.

If the client in Tokyo needs a 23 h 45 window, you will need to upload the image earlier. More precisely, it needs to be uploaded no later than 9:15 Japanese time. Again, convert this time to your own time zone to find out when that is.

We’re not done yet. While Japanese time (UTC+9) is ahead of Indian time, some time zones are even further ahead. According to Time Zone Abbreviations – Worldwide List some time zones are at UTC+14, either all year or in summer. And the list isn’t static. To prepare for future changes, you may want to add another couple of hours. Zone offsets in java.time go to UTC+18.

If you upload your image before 9:15 at, say, UTC+16, you are creating a challenge for clients in your own time zone and other time zones that are not that far ahead. Clients may be able to cope with the challenge if they know when the upload happens. It just means that very often they will have to save more pictures for the days to come, and they will need to convert the upload time to their own time zone. A more practical way to handle the latter is probably to announce and handle upload time in UTC, as Abdul Waheed said in another answer.

ThreeTenABP

For your time zone conversions I recommend JSR-310, the modern Java date and time API also known as java.time. This is not built-in on most Android devices yet (it will come), so you need the ThreeTenABP, the backport of JSR-310 to Android. There is a thorough explanation in this question: How to use ThreeTenABP in Android Project. Then you may for instance code your time zone conversion using this answer.

To learn more about the modern API, visit the Oracle tutorial or find other resources on the net.


问:
How to split String before first comma?
I have an overriding method with String which returns String in format of:

```<code> "abc,cde,def,fgh"
</code>```

I want to split the string content into two parts:

String before first comma and

String after first comma

My overriding method is :

@Override
protected void onPostExecute(String addressText) {

    placeTitle.setText(addressText);
}
```

Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?

答:
:In this case you can use replaceAll with some regex to get this input so you can use :

```<code> System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));
</code>```

If the key is just an String you can use (\\D?),.*

```<code>System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
</code>```

Title: How to split String before first comma?

Body:
I have an overriding method with String which returns String in format of:

 "abc,cde,def,fgh"

I want to split the string content into two parts:

String before first comma and

String after first comma

My overriding method is :

@Override
protected void onPostExecute(String addressText) {

    placeTitle.setText(addressText);
}

Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?

Body:
:In this case you can use replaceAll with some regex to get this input so you can use :

 System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));

If the key is just an String you can use (\\D?),.*

System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));


问:
Set max-execution-time on a function
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

```<code>runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);
</code>```

答:
I am sorry this solution is not as generic as you or future readers might want it to be, but it does work, and I can't come with a better idea yet...

The WebWorker interface as a terminate method, which will stop the Worker's execution immediately once called by the main thread.

We can use this to start a timer on the main thread that will call this Worker.terminate method when the timeout threshold has been reached.

This is not really generic, because it implies that your code must be able to run inside a Worker.

But you are lucky since it seems pdfmake library can.

So you could write it like this:

pdfmakeWorkerScript.js

```<code>// first import needed assets
self.importScripts('pdfmake.min.js');
self.importScripts('vfs_fonts.js');

self.onmessage = function(e) {
  if(e.data.docDefinition){
    pdfMake.createPdf(e.data.docDefinition).getBase64(function(b64) {
      self.postMessage(b64);
    });
  }
};
</code>```

in main page

```<code>function generatePDFinLessThan(docDefinition, maxTimeInSec, onsuccess, ontimeout){
  var worker = new Worker('pdfmakeWorkerScript.js');
  var timer = setTimeout(stopWorker, maxTimeInSec * 1000);
  worker.onmessage = function(e) {
      clearTimeout(timer);
      if(typeof onsuccess === 'function')
        onsuccess(e.data);
  }
  function stopWorker() {
    worker.terminate();
    if(typeof ontimeout === 'function')
        ontimeout();
  }
  worker.postMessage({docDefinition: docDefinition});
}

// usage
var docDefinition = {...};
generatePDFinLessThan(docDefinition, 10, function onsuccess(data) {...}, function ontimeout() {...});
</code>```

And a modified version so that it works in StackSnippets:

const workerURL = generateWorkerURL(); // should normally just be a string url pointing to your worker's .js

const docDefinition = {
  content: 'This is an sample PDF printed with pdfMake'
};

function generatePDFinLessThan(max_duration, onsuccess, ontimeout) {
  let timer = null;
  const worker = new Worker(workerURL);
  worker.onmessage = e => {
    if (e.data === "assets ready") { // for slow connections
      startTimer();
      return;
    }
    if (e.data.type === "success"){
      clearTimeout(timer);
      if(typeof onsuccess === 'function') {
        onsuccess(e.data.data);
      }
    }
  };
  worker.postMessage({
    docDefinition: docDefinition,
    // demo only!
    waitingTime: waitingInput.value * 1000
    // end demo only
  });

  function startTimer() {
    console.log('assets ready'); // rawgit is really long for me...
    timer = setTimeout(() => {
      worker.terminate();
      if (typeof ontimeout === 'function') {
        ontimeout();
      }
    }, max_duration * 1000);
  }
}

btn.onclick = e => generatePDFinLessThan(+maxTimeInput.value, onsuccess, ontimeout);

function onsuccess(data) {
  console.log(data);
}

function ontimeout() {
  console.error('operation timed out');
}

// demo only!
function generateWorkerURL() {
  const script = document.querySelector('script[type="worker-script"]');
  const blob = new Blob([script.textContent], {
    type: 'application/javascript'
  });
  return URL.createObjectURL(blob);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="worker-script">
  /* pdfmake generation in a worker */
  const pdfmake_baseURI = "https://cdn.jsdelivr.net/gh/bpampuch/pdfmake/build/";
  // first import needed assets
  self.importScripts(pdfmake_baseURI + 'pdfmake.min.js');
  self.importScripts(pdfmake_baseURI + 'vfs_fonts.js');

  self.postMessage('assets ready');

  onmessage = e => {
    if(e.data.docDefinition){
      // for demo only!
      wait(e.data.waitingTime);
      // end for demo only
      pdfMake.createPdf(e.data.docDefinition).getBase64(b64 => {
        self.postMessage({type: 'success', data: b64});
      });
    }
  };

  // for demo only!
  function wait(dur) {
    const now = performance.now();
    while(performance.now() - now < dur){}
  }
</script>
<button id="btn">generate pdf</button><br>
<label>Maximum execution time (in sec) <input type="number" id="maxTimeInput" value="5"></label><br>
<label>Waiting time in worker (in sec) <input type="number" id="waitingInput" value="0"></label></code>```

Title: Set max-execution-time on a function

Body:
I am generating PDF files using pdfmake on client side (a cordova app).

The more complex the document definition is the longer pdfmake takes to produce the document.

Thus, my intention is to put a hard limit on how long it takes for pdfmake to produce the document, something like what timeout command do in bash, and indicate to user if it failed to complete.

Here's a snippet of what I'm trying to do:

runFor(10, function(){  // run this function for a maximum of 10s
  pdfMake.createPdf(documentDefinition).getBase64(function(b64buff){
     //do something with the result
  });
}, ontimeout);

Body:
I am sorry this solution is not as generic as you or future readers might want it to be, but it does work, and I can't come with a better idea yet...

The WebWorker interface as a terminate method, which will stop the Worker's execution immediately once called by the main thread.

We can use this to start a timer on the main thread that will call this Worker.terminate method when the timeout threshold has been reached.

This is not really generic, because it implies that your code must be able to run inside a Worker.

But you are lucky since it seems pdfmake library can.

So you could write it like this:

pdfmakeWorkerScript.js

// first import needed assets
self.importScripts('pdfmake.min.js');
self.importScripts('vfs_fonts.js');

self.onmessage = function(e) {
  if(e.data.docDefinition){
    pdfMake.createPdf(e.data.docDefinition).getBase64(function(b64) {
      self.postMessage(b64);
    });
  }
};

in main page

function generatePDFinLessThan(docDefinition, maxTimeInSec, onsuccess, ontimeout){
  var worker = new Worker('pdfmakeWorkerScript.js');
  var timer = setTimeout(stopWorker, maxTimeInSec * 1000);
  worker.onmessage = function(e) {
      clearTimeout(timer);
      if(typeof onsuccess === 'function')
        onsuccess(e.data);
  }
  function stopWorker() {
    worker.terminate();
    if(typeof ontimeout === 'function')
        ontimeout();
  }
  worker.postMessage({docDefinition: docDefinition});
}

// usage
var docDefinition = {...};
generatePDFinLessThan(docDefinition, 10, function onsuccess(data) {...}, function ontimeout() {...});

And a modified version so that it works in StackSnippets:

const workerURL = generateWorkerURL(); // should normally just be a string url pointing to your worker's .js

const docDefinition = {
  content: 'This is an sample PDF printed with pdfMake'
};

function generatePDFinLessThan(max_duration, onsuccess, ontimeout) {
  let timer = null;
  const worker = new Worker(workerURL);
  worker.onmessage = e => {
    if (e.data === "assets ready") { // for slow connections
      startTimer();
      return;
    }
    if (e.data.type === "success"){
      clearTimeout(timer);
      if(typeof onsuccess === 'function') {
        onsuccess(e.data.data);
      }
    }
  };
  worker.postMessage({
    docDefinition: docDefinition,
    // demo only!
    waitingTime: waitingInput.value * 1000
    // end demo only
  });

  function startTimer() {
    console.log('assets ready'); // rawgit is really long for me...
    timer = setTimeout(() => {
      worker.terminate();
      if (typeof ontimeout === 'function') {
        ontimeout();
      }
    }, max_duration * 1000);
  }
}

btn.onclick = e => generatePDFinLessThan(+maxTimeInput.value, onsuccess, ontimeout);

function onsuccess(data) {
  console.log(data);
}

function ontimeout() {
  console.error('operation timed out');
}

// demo only!
function generateWorkerURL() {
  const script = document.querySelector('script[type="worker-script"]');
  const blob = new Blob([script.textContent], {
    type: 'application/javascript'
  });
  return URL.createObjectURL(blob);
}

<script type="worker-script">
  /* pdfmake generation in a worker */
  const pdfmake_baseURI = "https://cdn.jsdelivr.net/gh/bpampuch/pdfmake/build/";
  // first import needed assets
  self.importScripts(pdfmake_baseURI + 'pdfmake.min.js');
  self.importScripts(pdfmake_baseURI + 'vfs_fonts.js');

  self.postMessage('assets ready');

  onmessage = e => {
    if(e.data.docDefinition){
      // for demo only!
      wait(e.data.waitingTime);
      // end for demo only
      pdfMake.createPdf(e.data.docDefinition).getBase64(b64 => {
        self.postMessage({type: 'success', data: b64});
      });
    }
  };

  // for demo only!
  function wait(dur) {
    const now = performance.now();
    while(performance.now() - now < dur){}
  }
</script>
<button id="btn">generate pdf</button><br>
<label>Maximum execution time (in sec) <input type="number" id="maxTimeInput" value="5"></label><br>
<label>Waiting time in worker (in sec) <input type="number" id="waitingInput" value="0"></label>


问:
Haskell Type Signatures
I am new to haskell and I read some stuff about this thing called type signatures, but there are a few things that I dont understand.

Here is the the code am looking at:

```<code>--mult applies product
mult :: Num a => [a] -> a
mult  = foldr (*) 1

--posList filters positive numbers out
posList :: (Ord a, Num a) => [a] -> [a]
posList = filter (>0)

--trueList determines whether all of the members of a list are T or not
trueList :: [Bool] -> Bool
trueList  =  foldr(&&) True

--evenList determines where all of the members of a list are even or not
evenList :: (Integral a, Foldable t) => t a -> Bool
evenList x = if (((foldr (+) 2 x ) `mod` 2) == 0) then True else False
</code>```

So, I know you can do those functions easier in a different way, but I had assignments to use higher order functions map, filter and foldr, so I had to do them that way. Anyway, I understand how the functions work since I am the one who wrote them , what I dont understand is those terms Integral, Foldable, what do they mean? and what are they called in terms of Haskell?

答:
Those are constraints to a polymorphic type.

Haskell, despite being statically typed, makes it very easy to write function that can work with different types, through a system called parametric polymorphism. I'll first give all your functions concrete (monomorphic) signatures instead:

```<code>mult :: [Integer] -> Integer
mult  = foldl' (*) 1  -- foldl' is better for performance/memory than foldr

posList :: [Integer] -> [Integer]
posList = filter (>0)

trueList :: [Bool] -> Bool
trueList  =  foldl' (&&) True

evenList :: [Integer] -> Bool
evenList x = foldl' (+) 2 x `mod` 2 == 0
            -- `if True then True else False` is tautological
</code>```

All of these signatures work (both with the improved implementation and with your original ones).

But they only work with lists of Integer. That's not always sufficiently general; for instance, it's perfectly reasonable to compute the product of a list of fractional numbers. But with the monomorphic signature, mult [1.5, 2.4, 20] does not work: these numbers aren't compatible with Integer. You don't want to restrict the function to integers, you just want it to work with any number type and always get a result of the same type as the elements. I.e., you basically want the signature

```<code>mult :: ∀ a . [a] -> a
</code>```

...to be read "for all types a, the function mult takes a list whose elements have type a, and gives a single a-value as the result. The ∀ is implicit in Haskell when you have such type variables, i.e. you could as well make it

```<code>mult :: [a] -> a
</code>```

That doesn't work yet though, because the function must be able to multiply elements. But that is not possible for all types, only for number types. Hence you add the constraint

```<code>mult :: Num a => [a] -> a
</code>```

For posList it's much the same thing: the signature is essentially

```<code>posList :: [a] -> [a]
</code>```

but you also need to be able to compare (Ord) the elements with 0 (Num). Thus the constraint

```<code>posList :: (Num a, Ord a) => [a] -> [a]
</code>```

In case of evenList, the numerical operations are (+), (==) and mod. So in principle we need Num, Eq and Integral, but Integral has Num and Eq as superclasses anyway, so that alone is sufficient:

```<code>evenList :: Integral a => [a] -> Bool
</code>```

...which is not the most general form yet, though. You reduce that list with a fold, but lists aren't the only thing that can be folded, for instance you can also fold arrays, maps and Maybe values. The type class for all containers that can be folded is called, you won't guess it, Foldable. So we end up with

```<code>evenList :: (Integral a, Foldable t) => t a -> Bool
</code>```

You could apply the same generalisation to mult and trueList:

```<code>mult :: (Num a, Foldable t) => t a -> a
trueList :: Foldable t => t Bool -> Bool
</code>```

Title: Haskell Type Signatures

Body:
I am new to haskell and I read some stuff about this thing called type signatures, but there are a few things that I dont understand.

Here is the the code am looking at:

--mult applies product
mult :: Num a => [a] -> a
mult  = foldr (*) 1

--posList filters positive numbers out
posList :: (Ord a, Num a) => [a] -> [a]
posList = filter (>0)

--trueList determines whether all of the members of a list are T or not
trueList :: [Bool] -> Bool
trueList  =  foldr(&&) True

--evenList determines where all of the members of a list are even or not
evenList :: (Integral a, Foldable t) => t a -> Bool
evenList x = if (((foldr (+) 2 x ) `mod` 2) == 0) then True else False

So, I know you can do those functions easier in a different way, but I had assignments to use higher order functions map, filter and foldr, so I had to do them that way. Anyway, I understand how the functions work since I am the one who wrote them , what I dont understand is those terms Integral, Foldable, what do they mean? and what are they called in terms of Haskell?

Body:
Those are constraints to a polymorphic type.

Haskell, despite being statically typed, makes it very easy to write function that can work with different types, through a system called parametric polymorphism. I'll first give all your functions concrete (monomorphic) signatures instead:

mult :: [Integer] -> Integer
mult  = foldl' (*) 1  -- foldl' is better for performance/memory than foldr

posList :: [Integer] -> [Integer]
posList = filter (>0)

trueList :: [Bool] -> Bool
trueList  =  foldl' (&&) True

evenList :: [Integer] -> Bool
evenList x = foldl' (+) 2 x `mod` 2 == 0
            -- `if True then True else False` is tautological

All of these signatures work (both with the improved implementation and with your original ones).

But they only work with lists of Integer. That's not always sufficiently general; for instance, it's perfectly reasonable to compute the product of a list of fractional numbers. But with the monomorphic signature, mult [1.5, 2.4, 20] does not work: these numbers aren't compatible with Integer. You don't want to restrict the function to integers, you just want it to work with any number type and always get a result of the same type as the elements. I.e., you basically want the signature

mult :: ∀ a . [a] -> a

...to be read "for all types a, the function mult takes a list whose elements have type a, and gives a single a-value as the result. The ∀ is implicit in Haskell when you have such type variables, i.e. you could as well make it

mult :: [a] -> a

That doesn't work yet though, because the function must be able to multiply elements. But that is not possible for all types, only for number types. Hence you add the constraint

mult :: Num a => [a] -> a

For posList it's much the same thing: the signature is essentially

posList :: [a] -> [a]

but you also need to be able to compare (Ord) the elements with 0 (Num). Thus the constraint

posList :: (Num a, Ord a) => [a] -> [a]

In case of evenList, the numerical operations are (+), (==) and mod. So in principle we need Num, Eq and Integral, but Integral has Num and Eq as superclasses anyway, so that alone is sufficient:

evenList :: Integral a => [a] -> Bool

...which is not the most general form yet, though. You reduce that list with a fold, but lists aren't the only thing that can be folded, for instance you can also fold arrays, maps and Maybe values. The type class for all containers that can be folded is called, you won't guess it, Foldable. So we end up with

evenList :: (Integral a, Foldable t) => t a -> Bool

You could apply the same generalisation to mult and trueList:

mult :: (Num a, Foldable t) => t a -> a
trueList :: Foldable t => t Bool -> Bool


问:
Split Data where no obvious consistent delimiter: Excel - VBA
I'm trying to split my Excel data into various columns. The data I have a acquired is inconsistent, in terms of a delimiter, but there are certain attributes to the data that would help separate them into columns. The problem is, I have limited knowledge in Excel and VBA. Below is a sample from the column I want to split into several columns.

As you can see from the picture above, just using a simple script, which splits the data by a single delimiter, won't work because the addresses can be in a building, a unit or just a single property. However, I did notice that the Suburbs, States and Country are all uppercase. This means there is something I can work with.

So far, all my code does is split the active cell into several cells using a comma delimiter.

```<code>Sub SplitColoumn()

    Dim rng As range
    s = Split(ActiveCell, ",")

    Set rng = ActiveCell
    rng.Select

    Set rng = rng.Resize(1, 1 + UBound(s) + 1)
    rng.Select

    rng = s

End Sub
</code>```

The results are as expected, because all this code will do is split up the active cell, but I can't seem to figure out how to use a loop and have more control of the constraints.

I want to split the addresses into separate columns for Street, Suburb, State and Postcode.

Thanks

EDIT: I have now added the image, I'm not sure why it didn't appear the first time.

答:
I want to split the addresses into separate columns for Street,
  Suburb, State and Postcode

I assume you meant separate columns for Street, city, county, country and postcode?

Set a reference to Microsoft VBScript RegularExpression 5.5.
Adjust the following code (Range):

```<code>Dim rex As RegExp
Dim m As Match, mc As MatchCollection
Dim ran As Range, cel As Range

Set rex = New RegExp
rex.Pattern = "([\w\d\s\,]+?)\,([A-Z\s]+?)\,([A-Z\s]+?)\,([A-Z\s]+?)\,([\d\s]+?)$"

Set ran = Range("A1:A3")

For Each cel In ran
    Set mc = rex.Execute(CStr(cel.Value))
    Set m = mc.Item(0)
    cel = m.SubMatches(0)
    cel.Offset(0, 1) = m.SubMatches(1)
    cel.Offset(0, 2) = m.SubMatches(2)
    cel.Offset(0, 3) = m.SubMatches(3)
    cel.Offset(0, 4) = m.SubMatches(4)
Next cel
</code>```

This will split the contents of each cell into columns.

Body:
I'm trying to split my Excel data into various columns. The data I have a acquired is inconsistent, in terms of a delimiter, but there are certain attributes to the data that would help separate them into columns. The problem is, I have limited knowledge in Excel and VBA. Below is a sample from the column I want to split into several columns.

As you can see from the picture above, just using a simple script, which splits the data by a single delimiter, won't work because the addresses can be in a building, a unit or just a single property. However, I did notice that the Suburbs, States and Country are all uppercase. This means there is something I can work with.

So far, all my code does is split the active cell into several cells using a comma delimiter.

Sub SplitColoumn()

    Dim rng As range
    s = Split(ActiveCell, ",")

    Set rng = ActiveCell
    rng.Select

    Set rng = rng.Resize(1, 1 + UBound(s) + 1)
    rng.Select

    rng = s

End Sub

The results are as expected, because all this code will do is split up the active cell, but I can't seem to figure out how to use a loop and have more control of the constraints.

I want to split the addresses into separate columns for Street, Suburb, State and Postcode.

Thanks

EDIT: I have now added the image, I'm not sure why it didn't appear the first time.

Body:
I want to split the addresses into separate columns for Street,
  Suburb, State and Postcode

I assume you meant separate columns for Street, city, county, country and postcode?

Set a reference to Microsoft VBScript RegularExpression 5.5.
Adjust the following code (Range):

Dim rex As RegExp
Dim m As Match, mc As MatchCollection
Dim ran As Range, cel As Range

Set rex = New RegExp
rex.Pattern = "([\w\d\s\,]+?)\,([A-Z\s]+?)\,([A-Z\s]+?)\,([A-Z\s]+?)\,([\d\s]+?)$"

Set ran = Range("A1:A3")

For Each cel In ran
    Set mc = rex.Execute(CStr(cel.Value))
    Set m = mc.Item(0)
    cel = m.SubMatches(0)
    cel.Offset(0, 1) = m.SubMatches(1)
    cel.Offset(0, 2) = m.SubMatches(2)
    cel.Offset(0, 3) = m.SubMatches(3)
    cel.Offset(0, 4) = m.SubMatches(4)
Next cel

This will split the contents of each cell into columns.