问:
jquery scrollpane ms ajax updatepanel doesn’t work after post back
I have received a new design for a website and in the design the designer used jquery. I'm implementing the design no into an ASP.NET Ajax application.

But I ran into a problem. I have a page with an update panel and a menu. When a menu item is clicked a user control is loaded dynamically into a placeholder on the update panel. This makes that the page is not totally refreshed but only the update panel.

Now the content in the user control contains a scrollpane that extends to the maximum height of the window. The first time that runs fine, but when a menu item is clicked and the new user control is loaded which has content witch includes the same scrollpane. The height isn't extended to the maximum height of the window, it then only uses the height it needs. The same thing happens when I don't include the jquery files so it has to do something with the jscript library.

The scripts that are used in the page:

```<code>scripts/jquery.js
jquery.watermark.js
scripts/jquery.customSelect.js
scripts/jquery.easing.js
scripts/jquery.logger.js
scripts/jquery.sizes.min.js
scripts/jquery.mousewheel.js
scripts/jquery.em.js
scripts/jquery.core.js
scripts/jquery.accordion.js
scripts/jquery.tabs.js
scripts/jquery.scroll.js
scripts/jquery.datepick.js
scripts/jquery.datepick-nl.js
scripts/jquery.scripts.js
</code>```

Main code of the page that loads the main page:

```<code><body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="container">

<div id="logo"></div>
    <uc2:Menu ID="ucMenu" runat="server" />
    <uc3:Kruimelpad ID="ucKruimelpad" runat="server" />
    <asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Always">
    <ContentTemplate>
 <asp:PlaceHolder ID="phMain" runat="server" />
 </ContentTemplate>
 </asp:UpdatePanel>
<div id="sideBar">
   <uc1:Login ID="ucLogin" runat="server" />
</div>
<div class="clearboth"></div>
</div>

<uc4:Footer ID="ucFooter" runat="server" />

</div>
</form>
</body>
</html>
</code>```

main code of the user control:

```<code><div class="editMenu">
</div>
 <div id="content" class="orange-bar">
   <div id="contentVlak" class="scroll_pane">
<h1><asp:Label ID="lblNoAccount" runat="server" Text="<%$ Resources:Login, no_account %>"></asp:Label></h1>

<p><asp:Label ID="lblMainText" runat="server" Text="<%$ Resources:Login, main_text %>"></asp:Label> <asp:LinkButton
                    ID="lbAccountAanvragen" runat="server"
                    Text="<%$ Resources:Login, demo_account_aanvragen %>"
                    onclick="lbAccountAanvragen_Click"></asp:LinkButton>.</p>
            </div>
    </div>
</code>```

CSS code:

```<code> #content {
 background: url(../images/contentBg.png) repeat-y left top;
 position: relative;
 top: 58px;
 margin: 0px 0px 0px 11px !important;
 width: 886px;
 padding: 20px 20px 10px 20px;
 }

  #contentVlak {
  width: 676px;
  height:100%;
  padding: 0px 20px;
  }

   #contentVlak p {
   line-height: 20px;
   margin-bottom: 10px;
   font-size: 11.5px;
   }

   #contentVlak a {
   font-weight: bold;
   text-decoration: none;
   }

    #contentVlak a:hover {
    text-decoration: underline;
    }

/* Scrollpane styles */

.scroll_pane {
 overflow: auto;
}

.jScrollPaneContainer {
 position: relative;
 overflow: hidden;
 z-index: 1;
}

.jScrollPaneTrack {
 position: absolute;
 cursor: pointer;
 right: 0;
 top: 0;
 height: 100%;
 background: url(../images/scrollTrack.png) repeat-y left top;
}

.jScrollPaneDrag {
 position: absolute;
 background: #666;
 cursor: pointer;
 overflow: hidden;
 height: 20px !important;
 width: 20px;
 background: url(../images/scrollPane.png) no-repeat left top;
}
.jScrollPaneDragTop {
 position: absolute;
 top: 0;
 left: 0;
 overflow: hidden;
}
.jScrollPaneDragBottom {
 position: absolute;
 bottom: 0;
 left: 0;
 overflow: hidden;
}
a.jScrollArrowUp {
 display: block;
 position: absolute;
 z-index: 1;
 top: 0;
 right: 0;
 text-indent: -2000px;
 overflow: hidden;
 background: url(../images/scrollUp.png) no-repeat left top;
 height: 16px;
 width: 16px;
}

a.jScrollArrowDown {
 display: block;
 position: absolute;
 z-index: 1;
 bottom: 0;
 right: 0;
 text-indent: -2000px;
 overflow: hidden;
 background: url(../images/scrollDown.png) no-repeat left top;
 height: 16px;
 width: 16px;
}
</code>```

What am I doing wrong?

Code for resizing the block:

```<code>function resizeBlock(object) {

var windowHeight = $(window).height();
var start = object.offset().top;
var margin = object.margin().bottom + object.margin().top;
var padding = object.padding().bottom + object.padding().top;

var totalHeight = windowHeight - start - padding - 9;

object.height(totalHeight);

// Hoogtes van scroll-ding fixen
object.find(".scroll_pane").height(totalHeight);
object.find(".jScrollPaneContainer").height(totalHeight);
object.find(".jScrollPaneTrack").height(totalHeight);
object.find(".jScrollPaneDrag").height(totalHeight - 32);

// Object opnieuw toevoegen
$(".scroll_pane").jScrollPane({ showArrows: true, scrollbarWidth: 16 });
}

$(document).ready(function () {

    // Functie zie hierboven
    resizeBlock($("#content"));
    $(".scroll_pane").jScrollPane({ showArrows: true, scrollbarWidth: 16 });

    $(window).resize(function() {
        resizeBlock($("#content"));
    });

    // Custom selectboxes

    if($(".default-usage-select").length > 0) {
        $(".default-usage-select").selectbox();
    }

    // Watermarks op homepage

    if($("#relatiecode").length > 0) {
        $("#relatiecode").Watermark("relatiecode", "#808285");
    }

    if($("#wachtwoord").length > 0) {
        $("#wachtwoord").Watermark("wachtwoord", "#808285");
    }

    // Accordion box

    if($(".accordion").length > 0) {
        $('.accordion').accordion({
            header: '.accordionTrigger',
            autoheight: true,
            animate: '100'
        });

        if($(".accordionTrigger").hasClass("selected")) {
            $("#accordionLastTrigger").addClass  ("activeLastTrigger");
        }
    }

    // Tabbladen

    if($("#tabContainer").length > 0) {
        $('#tabContainer > ul').tabs();
    }

    // IE 6 Hover fix voor menu's

    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 6) {
        $('ul li').hover(function() {
            $(this).addClass('ie6hover');
        }, function() {
            $(this).removeClass('ie6hover');
        });
    }

}
});if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
</code>```

答:
Thanks RSolberg, your solution worked for me..I am using JScrollpane for Apple devices..and it works with update panel. Here is my updated code:</p>

```<code>    if ((navigator.userAgent.indexOf('AppleWebKit') != -1) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.indexOf('android') != -1) || (navigator.userAgent.indexOf('BlackBerry') != -1)) {
        $('#<%=iWrapper1.clientID%>').jScrollPane();
        $('#<%=iWrapper2.clientID%>').jScrollPane();
        $('.videoDisplay').jScrollPane();
    }

    if (navigator.userAgent.indexOf("MSIE") != -1)
        window.attachEvent("onload", pageLoad)
    else
        window.addEventListener("load", pageLoad, false);

    function pageLoad() {
        if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

        }
    }

    function endRequestHandler(sender, args) {
         if ((navigator.userAgent.indexOf('AppleWebKit') != -1) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.indexOf('android') != -1) || (navigator.userAgent.indexOf('BlackBerry') != -1)) {
            $('#<%=iWrapper1.clientID%>').jScrollPane();
            $('#<%=iWrapper2.clientID%>').jScrollPane();
            $('.videoDisplay').jScrollPane();
        }
    }
</code>```

Body:
I have received a new design for a website and in the design the designer used jquery. I'm implementing the design no into an ASP.NET Ajax application.

But I ran into a problem. I have a page with an update panel and a menu. When a menu item is clicked a user control is loaded dynamically into a placeholder on the update panel. This makes that the page is not totally refreshed but only the update panel.

Now the content in the user control contains a scrollpane that extends to the maximum height of the window. The first time that runs fine, but when a menu item is clicked and the new user control is loaded which has content witch includes the same scrollpane. The height isn't extended to the maximum height of the window, it then only uses the height it needs. The same thing happens when I don't include the jquery files so it has to do something with the jscript library.

The scripts that are used in the page:

scripts/jquery.js
jquery.watermark.js
scripts/jquery.customSelect.js
scripts/jquery.easing.js
scripts/jquery.logger.js
scripts/jquery.sizes.min.js
scripts/jquery.mousewheel.js
scripts/jquery.em.js
scripts/jquery.core.js
scripts/jquery.accordion.js
scripts/jquery.tabs.js
scripts/jquery.scroll.js
scripts/jquery.datepick.js
scripts/jquery.datepick-nl.js
scripts/jquery.scripts.js

Main code of the page that loads the main page:

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

    <uc2:Menu ID="ucMenu" runat="server" />
    <uc3:Kruimelpad ID="ucKruimelpad" runat="server" />
    <asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Always">
    <ContentTemplate>
 <asp:PlaceHolder ID="phMain" runat="server" />
 </ContentTemplate>
 </asp:UpdatePanel>

   <uc1:Login ID="ucLogin" runat="server" />

<uc4:Footer ID="ucFooter" runat="server" />

</form>

main code of the user control:

<asp:Label ID="lblNoAccount" runat="server" Text="<%$ Resources:Login, no_account %>"></asp:Label>

<asp:Label ID="lblMainText" runat="server" Text="<%$ Resources:Login, main_text %>"></asp:Label> <asp:LinkButton
                    ID="lbAccountAanvragen" runat="server"
                    Text="<%$ Resources:Login, demo_account_aanvragen %>"
                    onclick="lbAccountAanvragen_Click"></asp:LinkButton>.

CSS code:

 #content {
 background: url(../images/contentBg.png) repeat-y left top;
 position: relative;
 top: 58px;
 margin: 0px 0px 0px 11px !important;
 width: 886px;
 padding: 20px 20px 10px 20px;
 }

  #contentVlak {
  width: 676px;
  height:100%;
  padding: 0px 20px;
  }

   #contentVlak p {
   line-height: 20px;
   margin-bottom: 10px;
   font-size: 11.5px;
   }

   #contentVlak a {
   font-weight: bold;
   text-decoration: none;
   }

    #contentVlak a:hover {
    text-decoration: underline;
    }

/* Scrollpane styles */

.scroll_pane {
 overflow: auto;
}

.jScrollPaneContainer {
 position: relative;
 overflow: hidden;
 z-index: 1;
}

.jScrollPaneTrack {
 position: absolute;
 cursor: pointer;
 right: 0;
 top: 0;
 height: 100%;
 background: url(../images/scrollTrack.png) repeat-y left top;
}

.jScrollPaneDrag {
 position: absolute;
 background: #666;
 cursor: pointer;
 overflow: hidden;
 height: 20px !important;
 width: 20px;
 background: url(../images/scrollPane.png) no-repeat left top;
}
.jScrollPaneDragTop {
 position: absolute;
 top: 0;
 left: 0;
 overflow: hidden;
}
.jScrollPaneDragBottom {
 position: absolute;
 bottom: 0;
 left: 0;
 overflow: hidden;
}
a.jScrollArrowUp {
 display: block;
 position: absolute;
 z-index: 1;
 top: 0;
 right: 0;
 text-indent: -2000px;
 overflow: hidden;
 background: url(../images/scrollUp.png) no-repeat left top;
 height: 16px;
 width: 16px;
}

a.jScrollArrowDown {
 display: block;
 position: absolute;
 z-index: 1;
 bottom: 0;
 right: 0;
 text-indent: -2000px;
 overflow: hidden;
 background: url(../images/scrollDown.png) no-repeat left top;
 height: 16px;
 width: 16px;
}

What am I doing wrong?

Code for resizing the block:

function resizeBlock(object) {

var windowHeight = $(window).height();
var start = object.offset().top;
var margin = object.margin().bottom + object.margin().top;
var padding = object.padding().bottom + object.padding().top;

var totalHeight = windowHeight - start - padding - 9;

object.height(totalHeight);

// Hoogtes van scroll-ding fixen
object.find(".scroll_pane").height(totalHeight);
object.find(".jScrollPaneContainer").height(totalHeight);
object.find(".jScrollPaneTrack").height(totalHeight);
object.find(".jScrollPaneDrag").height(totalHeight - 32);

// Object opnieuw toevoegen
$(".scroll_pane").jScrollPane({ showArrows: true, scrollbarWidth: 16 });
}

$(document).ready(function () {

    // Functie zie hierboven
    resizeBlock($("#content"));
    $(".scroll_pane").jScrollPane({ showArrows: true, scrollbarWidth: 16 });

    $(window).resize(function() {
        resizeBlock($("#content"));
    });

    // Custom selectboxes

    if($(".default-usage-select").length > 0) {
        $(".default-usage-select").selectbox();
    }

    // Watermarks op homepage

    if($("#relatiecode").length > 0) {
        $("#relatiecode").Watermark("relatiecode", "#808285");
    }

    if($("#wachtwoord").length > 0) {
        $("#wachtwoord").Watermark("wachtwoord", "#808285");
    }

    // Accordion box

    if($(".accordion").length > 0) {
        $('.accordion').accordion({
            header: '.accordionTrigger',
            autoheight: true,
            animate: '100'
        });

        if($(".accordionTrigger").hasClass("selected")) {
            $("#accordionLastTrigger").addClass  ("activeLastTrigger");
        }
    }

    // Tabbladen

    if($("#tabContainer").length > 0) {
        $('#tabContainer > ul').tabs();
    }

    // IE 6 Hover fix voor menu's

    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 6) {
        $('ul li').hover(function() {
            $(this).addClass('ie6hover');
        }, function() {
            $(this).removeClass('ie6hover');
        });
    }

}
});if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Body:
Thanks RSolberg, your solution worked for me..I am using JScrollpane for Apple devices..and it works with update panel. Here is my updated code:

    if ((navigator.userAgent.indexOf('AppleWebKit') != -1) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.indexOf('android') != -1) || (navigator.userAgent.indexOf('BlackBerry') != -1)) {
        $('#<%=iWrapper1.clientID%>').jScrollPane();
        $('#<%=iWrapper2.clientID%>').jScrollPane();
        $('.videoDisplay').jScrollPane();
    }

    if (navigator.userAgent.indexOf("MSIE") != -1)
        window.attachEvent("onload", pageLoad)
    else
        window.addEventListener("load", pageLoad, false);

    function pageLoad() {
        if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);

        }
    }

    function endRequestHandler(sender, args) {
         if ((navigator.userAgent.indexOf('AppleWebKit') != -1) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.indexOf('android') != -1) || (navigator.userAgent.indexOf('BlackBerry') != -1)) {
            $('#<%=iWrapper1.clientID%>').jScrollPane();
            $('#<%=iWrapper2.clientID%>').jScrollPane();
            $('.videoDisplay').jScrollPane();
        }
    }


来源: stackexchange

问:
How do I return a list with newly added objects from a method (Beginner) C#
I am having trouble returning a list from a method called "omvandlaBetyg" which translates to "convert grades". I have added a total of 5 'char' to my list. I wish to return the list from the method.

With many attempts I have not been able to solve this issue.
I am sorry for having set the names of the lists/variables to another language.

If it is too difficult to try and find a solution for my issue then I will translate it as soon as possible.

Thanks in advance.

```<code>    static void Main(string[] args)
    {
        string[] ämnen = { "Matematik", "Svenska", "Engelska", "Historia", "Fysik" };
        int[] poäng = new int[5];
        List<char> betyg = new List<char>(); // This is the list that is currently empty

        Program.LäsPoäng(poäng);

        Program.omvandlaBetyg(poäng, betyg);

        Program.skrivUtBetyg(betyg, ämnen);

    }
    static int LäsPoäng(int[] poäng)
    {
        Console.Write("Ange totalpoäng för matematik:");
        int matPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för svenska:");
        int svePoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för engelska:");
        int engPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för historia:");
        int hisPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för fysik:");
        int fysPoäng = Convert.ToInt32(Console.ReadLine());

        poäng[0] = matPoäng;
        poäng[1] = svePoäng;
        poäng[2] = engPoäng;
        poäng[3] = hisPoäng;
        poäng[4] = fysPoäng;

        return poäng[4];
    }
    static char omvandlaBetyg(int[] poäng, List <char> betyg)
    {

        foreach (int i in poäng)
        {
            if (i < 50)
            {
                betyg.Add('F');
            }
            else if (i >= 50 && i < 60)
            {
                betyg.Add('E');
            }
            else if (i > 60 && i < 75)
            {
                betyg.Add('D');
            }
            else if (i > 75 && i < 90)
            {
                betyg.Add('C');
            }
            else if (i > 90 && i < 100)
            {
                betyg.Add('B');
            }
            else if (i == 100)
            {
                betyg.Add('A');
            }
        }
        return betyg; // This is the list that has been updated with newly added char's
                      // that i wish to return from this method
    }
    static void skrivUtBetyg(List<char> betyg, string[] ämnen)
    {
        foreach (char item in betyg)
        {
             Console.WriteLine("Betyg i : " + item );
        }
    }
    static void Statistik()
    {

    }

}
</code>```

}

答:
You can just change the return type of the method omvandlaBetyg from char to List<char>

Here I fixed your code:

```<code>static List<char> omvandlaBetyg(int[] poäng, List <char> betyg)
{
    foreach (int i in poäng)
    {
        if (i < 50)
        {
            betyg.Add('F');
        }
        else if (i >= 50 && i < 60)
        {
            betyg.Add('E');
        }
        else if (i > 60 && i < 75)
        {
            betyg.Add('D');
        }
        else if (i > 75 && i < 90)
        {
            betyg.Add('C');
        }
        else if (i > 90 && i < 100)
        {
            betyg.Add('B');
        }
        else if (i == 100)
        {
            betyg.Add('A');
        }
    }
    return betyg;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble returning a list from a method called "omvandlaBetyg" which translates to "convert grades". I have added a total of 5 'char' to my list. I wish to return the list from the method.

With many attempts I have not been able to solve this issue.
I am sorry for having set the names of the lists/variables to another language.

If it is too difficult to try and find a solution for my issue then I will translate it as soon as possible.

Thanks in advance.

    static void Main(string[] args)
    {
        string[] ämnen = { "Matematik", "Svenska", "Engelska", "Historia", "Fysik" };
        int[] poäng = new int[5];
        List<char> betyg = new List<char>(); // This is the list that is currently empty

        Program.LäsPoäng(poäng);

        Program.omvandlaBetyg(poäng, betyg);

        Program.skrivUtBetyg(betyg, ämnen);

    }
    static int LäsPoäng(int[] poäng)
    {
        Console.Write("Ange totalpoäng för matematik:");
        int matPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för svenska:");
        int svePoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för engelska:");
        int engPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för historia:");
        int hisPoäng = Convert.ToInt32(Console.ReadLine());

        Console.Write("Ange totalpoäng för fysik:");
        int fysPoäng = Convert.ToInt32(Console.ReadLine());

        poäng[0] = matPoäng;
        poäng[1] = svePoäng;
        poäng[2] = engPoäng;
        poäng[3] = hisPoäng;
        poäng[4] = fysPoäng;

        return poäng[4];
    }
    static char omvandlaBetyg(int[] poäng, List <char> betyg)
    {

        foreach (int i in poäng)
        {
            if (i < 50)
            {
                betyg.Add('F');
            }
            else if (i >= 50 && i < 60)
            {
                betyg.Add('E');
            }
            else if (i > 60 && i < 75)
            {
                betyg.Add('D');
            }
            else if (i > 75 && i < 90)
            {
                betyg.Add('C');
            }
            else if (i > 90 && i < 100)
            {
                betyg.Add('B');
            }
            else if (i == 100)
            {
                betyg.Add('A');
            }
        }
        return betyg; // This is the list that has been updated with newly added char's
                      // that i wish to return from this method
    }
    static void skrivUtBetyg(List<char> betyg, string[] ämnen)
    {
        foreach (char item in betyg)
        {
             Console.WriteLine("Betyg i : " + item );
        }
    }
    static void Statistik()
    {

    }

}

}

Body:
You can just change the return type of the method omvandlaBetyg from char to List<char>

Here I fixed your code:

static List<char> omvandlaBetyg(int[] poäng, List <char> betyg)
{
    foreach (int i in poäng)
    {
        if (i < 50)
        {
            betyg.Add('F');
        }
        else if (i >= 50 && i < 60)
        {
            betyg.Add('E');
        }
        else if (i > 60 && i < 75)
        {
            betyg.Add('D');
        }
        else if (i > 75 && i < 90)
        {
            betyg.Add('C');
        }
        else if (i > 90 && i < 100)
        {
            betyg.Add('B');
        }
        else if (i == 100)
        {
            betyg.Add('A');
        }
    }
    return betyg;
}


问:
Restricting the size of widgets programmatically
I'd like to create the layout shown in the picture below. This shows up fine:

```<code>Column( Row, ListView()))
</code>```

While this renders errors:

```<code>Column( Row, Row( ListView(), Column ))
</code>```

As soon as I replace the inner ListView() with Row( ListView(), Column ), nothing shows up and I get varying error messages, based on various changes I did.

Most often, I see a 'viewport has unlimited horizontal size'.

I guess Listview to be the source of the problem. That said, I'm no aware how to fix it.

Furthermore, I did find various hints on SO, but none fixed the problem.

How do I fix the problem?

Update 1

While the right Column() may be fixed width, the ListView() should take all remaining space of the screen [= availableWidth - WidhtOf(Column())].

答:
Both Row and Column have a mainAxisSizeparameter where you can set it to MainAxisSize.min so they will take their children's size.
Now, about the ListView, there is a shrinkWrap parameter that makes it so its max size will be its children's size. Another idea might be using a Flexible widget around the ListView, it does almost the same as Expanded, but the difference is: Expanded forces the child to occupy the remaining space, while Flexible allows the children to have any given size smaller than that, and that's because of its fit parameter that by default is FlexFit.loose.

Body:
I'd like to create the layout shown in the picture below. This shows up fine:

Column( Row, ListView()))

While this renders errors:

Column( Row, Row( ListView(), Column ))

As soon as I replace the inner ListView() with Row( ListView(), Column ), nothing shows up and I get varying error messages, based on various changes I did.

Most often, I see a 'viewport has unlimited horizontal size'.

I guess Listview to be the source of the problem. That said, I'm no aware how to fix it.

Furthermore, I did find various hints on SO, but none fixed the problem.

How do I fix the problem?

Update 1

While the right Column() may be fixed width, the ListView() should take all remaining space of the screen [= availableWidth - WidhtOf(Column())].


问:
Reverse order of bits (like Long.reverse())
I have a Long and want to reverse the order of the bits. I can call java.lang.Long.reverse(myLong), but is there a Kotlin builtin to accomplish the same thing? The closest I can find is BitSet.flip

答:
If using the full java path seems verbose, one way would be to create an extension function.

```<code>fun Long.myReverse() = java.lang.Long.reverse(this)
</code>```

And this would be called like this:

```<code>myLong.myReverse()
</code>```

Since kotlin doesn't actually use the java .reverse() you could probably name it that directly, but I would avoid that in case they add it in the future.

Body:
If using the full java path seems verbose, one way would be to create an extension function.

fun Long.myReverse() = java.lang.Long.reverse(this)

And this would be called like this:

myLong.myReverse()

Since kotlin doesn't actually use the java .reverse() you could probably name it that directly, but I would avoid that in case they add it in the future.


问:
Hive DDL Parser using Beeline or Spark's internal classes or methods
Is it possible to use Hive/Beeline/Spark's DDL parsing capabilities within our custom programs preferably in Java or Scala?. I have already looked at the project https://github.com/xnuinside/simple-ddl-parser and it does exactly what I want. The concern I have with this project is, it is not using Hive or Spark's own internal classes for the parsing. They have come up with their own regex pattern to parse the given DDL statements.

I know beeline or spark-shell accepts the create table statements and it creates the table. I am thinking it must have internal classes which does the parsing and then it creates the table. If they are public classes or methods can we not use these instead of reinventing the wheel?. I do not know what are those internal classes or methods that parses the DDL statements. Please let me know if you know more about it. For my use case, I need to extract TableName, ColumnNames, DataTypes, PartitionKeys, SerDe, InputFormat, OutputFormat from the given Create Table Statement.

答: One of my friends suggested me to use the Apache-Hive library itself, specifically the class org.apache.hadoop.hive.ql.parse.HiveParser. Example programs can be found in the link1 or link2.


问:
Centering weird/misplaced for text in CSS
I am working on a project that has a part where I need text to be centered, but when I use text-align:center; this is what happens

Where the Hosting for school projects is off the line of being inline of Independent Study text.

答:
Note that the width styles of both containers are equal in the example below.

body {
  background-color: black;
}
.first {
  width: 400px;   /* the widht style of the first container is set to 400px. */
  text-align: center;
  border: 1px solid red;
  color: white;
}
.second {
  width: 400px;   /* the widht style of the second container is set to 400px. */
  text-align: center;
  border: 1px solid blue;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="first">
    <h1>Independent Study</h1>
  </div><br>

  <div class="second">
    <h3>Hosting for school projects</h3>
  </div>
</body></code>```

Body:
Note that the width styles of both containers are equal in the example below.

body {
  background-color: black;
}
.first {
  width: 400px;   /* the widht style of the first container is set to 400px. */
  text-align: center;
  border: 1px solid red;
  color: white;
}
.second {
  width: 400px;   /* the widht style of the second container is set to 400px. */
  text-align: center;
  border: 1px solid blue;
  color: white;
}

<body>
  <div class="first">
    <h1>Independent Study</h1>
  </div><br>

  <div class="second">
    <h3>Hosting for school projects</h3>
  </div>
</body>


问:
Avoiding write skews in Spring Data MongoDB
I am trying to use Spring Data MongoDB transactions to avoid write skew errors. This diagram explains the flow that happens in my example. I also posted the source code as a whole in this repository.

My service method that reads and updates the same document is @Transactional:

fun nextMessage(id: Int, text: String) = transactionReadWrite(id, text)
    ?.let { messages.save(it) }

@Transactional
fun transactionReadWrite(id: Int, text: String) = threads.findById(id)
    ?.write(text)
    ?.let { (threadUpdate, previousLatest) ->
        threads.save(threadUpdate)
        log.info("Replacing \"${previousLatest.text}\" with \"${threadUpdate.latestMessage.text}\"")
        previousLatest
    }
```
<p>But when I call <code>nextMessage()</code> with 5 different inputs in parallel, I can see some of them reading the same values at the same time, and then successfully updating the document:</p>
```15:37:06.964 : Opened connection [connectionId{localValue:3, serverValue:1264}] to localhost:27017
15:37:07.308 : Replacing "0" with "3"
15:37:07.308 : Replacing "0" with "4"
15:37:07.310 : Replacing "0" with "1"
15:37:07.430 : Opened connection [connectionId{localValue:5, serverValue:1265}] to localhost:27017
15:37:07.430 : Opened connection [connectionId{localValue:6, serverValue:1266}] to localhost:27017
15:37:07.435 : Replacing "1" with "2"
15:37:07.440 : Replacing "1" with "5"
15:37:07.447 : Replacing "5" with "another one"
```

How do you avoid write skew errors with Spring Data MongoDB transactions?

答:
According to the diagram, B3.update should not succeed, you need to use optmistic locking in the update, like updateOne({_id:xx, text:"1"}, $set: { text: "3" }) that will return 0 modified

Then Bobby needs to find the current entity and attempt the update again.

Body:
I am trying to use Spring Data MongoDB transactions to avoid write skew errors. This diagram explains the flow that happens in my example. I also posted the source code as a whole in this repository.

My service method that reads and updates the same document is @Transactional:

fun nextMessage(id: Int, text: String) = transactionReadWrite(id, text)
    ?.let { messages.save(it) }

@Transactional
fun transactionReadWrite(id: Int, text: String) = threads.findById(id)
    ?.write(text)
    ?.let { (threadUpdate, previousLatest) ->
        threads.save(threadUpdate)
        log.info("Replacing \"${previousLatest.text}\" with \"${threadUpdate.latestMessage.text}\"")
        previousLatest
    }

But when I call nextMessage() with 5 different inputs in parallel, I can see some of them reading the same values at the same time, and then successfully updating the document:

15:37:06.964 : Opened connection [connectionId{localValue:3, serverValue:1264}] to localhost:27017
15:37:07.308 : Replacing "0" with "3"
15:37:07.308 : Replacing "0" with "4"
15:37:07.310 : Replacing "0" with "1"
15:37:07.430 : Opened connection [connectionId{localValue:5, serverValue:1265}] to localhost:27017
15:37:07.430 : Opened connection [connectionId{localValue:6, serverValue:1266}] to localhost:27017
15:37:07.435 : Replacing "1" with "2"
15:37:07.440 : Replacing "1" with "5"
15:37:07.447 : Replacing "5" with "another one"

How do you avoid write skew errors with Spring Data MongoDB transactions?


问:
Loop in R to read Files in multiple folders with no name pattern
I have folders for each day of each month, each containing 5-40 CSV files. The files have paths like

rootfolder/2/20/CSV/date-field-num.csv
```

and I want to read them all into R at once instead of individually. Is there a way to use a loop to do this if the files are in separate folders? The folder names have an obvious pattern. The actual CSV file names are of the form date-field-num.csv, where field could be anything and num could be any number.

答:
If you want all of the CSV files under rootfolder, then something like this should work:

## Get character vector listing paths to CSV files
fn <- list.files("path/to/rootfolder", pattern = "[.]csv$", full.names = TRUE, recursive = TRUE)

## Construct list of data frames
l <- lapply(fn, read.csv, ...)
```
<p>with <code>...</code> listing optional arguments to <code>read.csv</code>. Otherwise, you need to filter <code>fn</code> before the <code>lapply</code> call. Maybe:</p>
<pre class="lang-r prettyprint-override"><code>fn_full <- fn
fn <- grep("^rootfolder/\\d+/\\d+/CSV/date-[^-]+-\\d+[.]csv$", fn_full, value = TRUE)
</code>```

I'd be somewhat worried about memory usage with ~1000 CSV files. You might need to process fn in batches.

Body:
I have folders for each day of each month, each containing 5-40 CSV files. The files have paths like

rootfolder/2/20/CSV/date-field-num.csv

and I want to read them all into R at once instead of individually. Is there a way to use a loop to do this if the files are in separate folders? The folder names have an obvious pattern. The actual CSV file names are of the form date-field-num.csv, where field could be anything and num could be any number.

Body:
If you want all of the CSV files under rootfolder, then something like this should work:

## Get character vector listing paths to CSV files
fn <- list.files("path/to/rootfolder", pattern = "[.]csv$", full.names = TRUE, recursive = TRUE)

## Construct list of data frames
l <- lapply(fn, read.csv, ...)

with ... listing optional arguments to read.csv. Otherwise, you need to filter fn before the lapply call. Maybe:

fn_full <- fn
fn <- grep("^rootfolder/\\d+/\\d+/CSV/date-[^-]+-\\d+[.]csv$", fn_full, value = TRUE)

I'd be somewhat worried about memory usage with ~1000 CSV files. You might need to process fn in batches.


问:
Pass data from one window to another in React
Hello everyone I have the following code to take the location I need to use those values to send them to another page or component if someone could help me it would be very useful greetings</p>
```<code>      const processManualLocation = () => {
        const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.........`;
        const http = new XMLHttpRequest();
        http.open("POST", url);
        http.onreadystatechange = function(){
          if(this.readyState == 4 && this.status == 200){
           let resultado = JSON.parse(this.responseText);
           let latitude = resultado.location.lat;
           let longitude = resultado.location.lng;
           console.log(latitude, longitude);
          }
        }
        http.send();
    }
</code>```

答:
It seems like you're trying to use the Google Geolocation API.

Here's an example of a asynchronous function for fetching data from that endpoint:

TS Playground

// Ref: https://developers.google.com/maps/documentation/geolocation/overview

const API_KEY = `Your actual API key`;

async function processManualLocation () {
  const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=${API_KEY}`;
  const request = new Request(url, {method: 'POST'});
  const response = await fetch(request);
  if (!response.ok) throw new Error('Response not OK');
  const data = await response.json();
  const {accuracy, location: {lat, lng}} = data;
  const result = {accuracy, lat, lng};
  console.log(result);
  return result; // or whatever want to return from the response data
}
```

Body:
Hello everyone I have the following code to take the location I need to use those values to send them to another page or component if someone could help me it would be very useful greetings

      const processManualLocation = () => {
        const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=.........`;
        const http = new XMLHttpRequest();
        http.open("POST", url);
        http.onreadystatechange = function(){
          if(this.readyState == 4 && this.status == 200){
           let resultado = JSON.parse(this.responseText);
           let latitude = resultado.location.lat;
           let longitude = resultado.location.lng;
           console.log(latitude, longitude);
          }
        }
        http.send();
    }

Body:
It seems like you're trying to use the Google Geolocation API.

Here's an example of a asynchronous function for fetching data from that endpoint:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/PTAECUFMDMC5QBYBckAcDOsQBNIDdIAbAe1UgCd0A6Ac2OJsMioGNiBbYdgQw2G2IsAru0gA7JNyQBLYmOA1IxEiymz5xAuTzTIAdwCwAKGNsx6JKACCABQCSAfQDSAUQCaoALygABm+JC5KDcLEhC3ITW9qAA1pAAnj4A3MbG3OjxYiyg0EJZMnKgqOSCkOjoALLcYuGEADKCaoUAFACUoADexqCgZhY9gZHePshomCB6k7T0jJC80tRsnIrKjQXyeACMCkoqUpAA-HHxngAkHbaOrm4AvsndvXL95JAAjkJllt5i+hBvHxZmoMADSdURIBDEbDwADkNgA8gBlAAqMJurRSRh6fUsL3QqCekC8wT03GklmgkCQLAQzRe70+GIe0mgoGaAEI8QTzMxiDF2hCSnpQD9hS5yCVyM0YVB8YSRcRLPCnDCmVjHuZLNgpNxidxSeTQFzCVQAFboORtTHYp6WDohYTkELxUF7dbwDqEKSusQ0G43YnayTWjXPMpCQhfToOwLO13e0CEX03EN9ZTMEg0OnhyNqnovMLkMRGnNIJKgECgYhBPQIfZaUCkiSgJDEEuF4vQErsFsIInGnmgIPcYw3IA" rel="nofollow noreferrer">TS Playground

// Ref: https://developers.google.com/maps/documentation/geolocation/overview

const API_KEY = `Your actual API key`;

async function processManualLocation () {
  const  url = `https://www.googleapis.com/geolocation/v1/geolocate?key=${API_KEY}`;
  const request = new Request(url, {method: 'POST'});
  const response = await fetch(request);
  if (!response.ok) throw new Error('Response not OK');
  const data = await response.json();
  const {accuracy, location: {lat, lng}} = data;
  const result = {accuracy, lat, lng};
  console.log(result);
  return result; // or whatever want to return from the response data
}


问:
Flutter Decorate Drop Down Button
I have a dropdown button, and im trying to decorate or customize the dropdown but only the list of items that is shown when trying to select the item in the list of items, i want the inside to look like this

```<code>Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(40),
        padding: const EdgeInsets.symmetric(
          horizontal: 12,
        ),
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          borderRadius: BorderRadius.circular(15),
        ),
        child: DropdownButtonFormField<String>(
          iconSize: 28,
          iconEnabledColor: Colors.blue,
          isDense: false,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text(
            'Select your project',
            style: TextStyle(fontSize: 15, color: Colors.blue),
          ),
          isExpanded: true,
          items: workingData!.map((account) {
            return DropdownMenuItem(
              child: Text(
                account.name + ' (${account.location})',
              ),
              value: account.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }
</code>```

答:
You can achieve that using DropdownButton2.

Also, For adding dividers with different height than other items, check out Example 3.

Disclaimer: I am the author of the package mentioned above.

Title: Flutter Decorate Drop Down Button

Body:
I have a dropdown button, and im trying to decorate or customize the dropdown but only the list of items that is shown when trying to select the item in the list of items, i want the inside to look like this

Center locationDropDown() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(40),
        padding: const EdgeInsets.symmetric(
          horizontal: 12,
        ),
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          borderRadius: BorderRadius.circular(15),
        ),
        child: DropdownButtonFormField<String>(
          iconSize: 28,
          iconEnabledColor: Colors.blue,
          isDense: false,
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please select a location';
            }
          },
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.transparent),
            ),
          ),
          value: chooseLocation,
          hint: const Text(
            'Select your project',
            style: TextStyle(fontSize: 15, color: Colors.blue),
          ),
          isExpanded: true,
          items: workingData!.map((account) {
            return DropdownMenuItem(
              child: Text(
                account.name + ' (${account.location})',
              ),
              value: account.id,
            );
          }).toList(),
          onChanged: (String? displayedValue) {
            setState(
              () {
                chooseLocation = displayedValue!;
              },
            );
          },
        ),
      ),
    );
  }


问:
Hiding sensitive information with Docker Compose
Went through a crash course in Docker and Compose to learn how to deploy a small automated application with security in mind.  Problem is, I needed to feed the script sensitive values and did not want to hardcode them in.  After a lot of research, I settled on Compose and setting my env var's at runtime rather than using the standard Docker build.  I also have some JSON files that contain web cookies as a form of login that are passed as volumes.  My understanding was that the values would not be visible while inspecting the container.  Yet, when I inspect it, they are clearly visible along with the contents of the JSON files.  Unless I am the only one that knows how to access the specific container, I am pretty sure that this is NOT a safe option.

From the yaml:

```<code>services:
  frontend:
    image: SOME IMAGE
    build: .
    volumes:
      - ./script.py:/app/script.py
      - ./words.txt:/app/words.txt
      - ./.some.json:/app/.some.json
      - ./.another.json:/app/.another.json
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    env_file:
      - ./some.env
    container_name: name
volumes:
  .:
    external: true
</code>```

Why are the values and files clearly visible?  I do not want to go the Swarm direction and its SECRETS at this time.

EDIT: this is not being pushed to Hub or a repository, so I am not worried about security in that regard.

答:
Unless I am the only one that knows how to access the specific container, I am pretty sure that this is NOT a safe option

If someone else knows how to access container he/she will be able to run:

# to get contents of JSON file
docker exec container_name cat /app/.some.json

# to print all env vars inside container
docker exec container_name env
```

I am pretty sure that this is NOT a safe option

Not safe option is an allowing to control/access server side for unknown persons. Container contents is a last destination, if someone get access to it here is game over and no reasons to hide information

Setting variables and secrets inside ENVs and config files only helps to

reuse same code at different configurations/environments without changing itself

share code at public places (like GitHub) without leaking sensitive information (I recommend to add all config file paths inside .gitignore)

Also this article may be helpful for you

Body:
Went through a crash course in Docker and Compose to learn how to deploy a small automated application with security in mind.  Problem is, I needed to feed the script sensitive values and did not want to hardcode them in.  After a lot of research, I settled on Compose and setting my env var's at runtime rather than using the standard Docker build.  I also have some JSON files that contain web cookies as a form of login that are passed as volumes.  My understanding was that the values would not be visible while inspecting the container.  Yet, when I inspect it, they are clearly visible along with the contents of the JSON files.  Unless I am the only one that knows how to access the specific container, I am pretty sure that this is NOT a safe option.

From the yaml:

services:
  frontend:
    image: SOME IMAGE
    build: .
    volumes:
      - ./script.py:/app/script.py
      - ./words.txt:/app/words.txt
      - ./.some.json:/app/.some.json
      - ./.another.json:/app/.another.json
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    env_file:
      - ./some.env
    container_name: name
volumes:
  .:
    external: true

Why are the values and files clearly visible?  I do not want to go the Swarm direction and its SECRETS at this time.

EDIT: this is not being pushed to Hub or a repository, so I am not worried about security in that regard.

Body:
Unless I am the only one that knows how to access the specific container, I am pretty sure that this is NOT a safe option

If someone else knows how to access container he/she will be able to run:

# to get contents of JSON file
docker exec container_name cat /app/.some.json

# to print all env vars inside container
docker exec container_name env

I am pretty sure that this is NOT a safe option

Not safe option is an allowing to control/access server side for unknown persons. Container contents is a last destination, if someone get access to it here is game over and no reasons to hide information

Setting variables and secrets inside ENVs and config files only helps to

reuse same code at different configurations/environments without changing itself

share code at public places (like GitHub) without leaking sensitive information (I recommend to add all config file paths inside .gitignore)

Also this article may be helpful for you


问:
Blackberry: Adding a contact with fields filled in by app
I have implemented an ActiveRichTextField to my app, which allows user to select a phone number and choose "Add Contact" to add it inside the user's phonebook. However, when it is directed to the phonebook 'add a contact' page, the only field which is filled in is the phone number. I wonder whether it is possible to include fields which are filled like the Name and the phone number, plus the email? Extracting it from my website. </p>

答:
Below, there is code to add name "John Doe" to address book.

```<code>ContactList contactList =
            (ContactList)PIM.getInstance().
                              openPIMList(PIM.CONTACT_LIST, PIM.WRITE_ONLY);

    if (contactList.isSupportedField(Contact.NAME)) {
       String[] name = new String[contactList.stringArraySize(Contact.NAME)];

       name[Contact.NAME_GIVEN] =  "John";
       name[Contact.NAME_FAMILY] = "Doe";

       contact.addStringArray(Contact.NAME, Contact.ATTR_NONE, name);
    }
</code>```

Use this approach to add email (use Contact.EMAIL) and other fields.

ContentLicense: CC BY-SA 3.0

Body:
Below, there is code to add name "John Doe" to address book.

ContactList contactList =
            (ContactList)PIM.getInstance().
                              openPIMList(PIM.CONTACT_LIST, PIM.WRITE_ONLY);

    if (contactList.isSupportedField(Contact.NAME)) {
       String[] name = new String[contactList.stringArraySize(Contact.NAME)];

       name[Contact.NAME_GIVEN] =  "John";
       name[Contact.NAME_FAMILY] = "Doe";

       contact.addStringArray(Contact.NAME, Contact.ATTR_NONE, name);
    }

Use this approach to add email (use Contact.EMAIL) and other fields.


问:
Limit on the number of NPCs
Such an idea, for which I don't even have any ideas how to do it right. In general, the thought is:
There are, say, three NPCs on the stage (Conditionally), and there is also one building (Conditionally). Each NPC has its own task, but I do not know how to take an NPC who does not have a task and send one NPC to work in the building, and not several at once. Namely, each NPC has work statuses, and there is also a status 0, meaning that the NPC is not busy, there may be several such "free" ones, and if one is assigned the status of work - go to the building, then everyone who has this status will go, but how can we make sure that only one free NPC is taken and sent there?
I know the question is as incomprehensible and terrible as possible, but maybe someone will understand...</p>

答:
I made, so, to begin with, the code:

File WorkingPlace:

```<code>public static bool SignalFreeNPCPoint = false;
public static int WorkingPlaceNPC = 0;
public void ProductBoardNPC()
{
    SignalFreeNPCPoint = true;
    WorkingPlaceNPC += 1;
}
public void ProductBoard_Stop()
{
    WorkingPlaceNPC -= 1;
    SignalFreeNPCPoint = true;
}
</code>```

This "ProductBoardNPC()" and "ProductBoard_Stop()" method's for button in Unity.

File NPCSctipt:

```<code>public List<GameObject> ListGM = new List<GameObject>();
public int TaskNumber = 0;
void Update()
{
    TaskManager();
    LogicNPC();
}
private void TaskManager()
{
    switch (TaskNumber)
    {
        case 0:
            //You code
            break;
        case 1:
            ListGM.Remove(gameObject);
            break;
        case 2:
            ListGM.Remove(gameObject);
            break;
        case 3:
            ListGM.Remove(gameObject);
            break;
        case 4:
            ListGM.Remove(gameObject);
            break;
    }
}
private void LogicNPC()
{
    if (WorkingPlace.SignalFreeNPCPoint == true)
    {
        if (TaskNumber == 0 & WorkingPlace.WorkingPlaceNPC == 1)
        {
            ListGM.Add(gameObject);
            TaskNumber = 4;
        }
        if (TaskNumber == 4 & WorkingPlace.WorkingPlaceNPC == 0)
        {
            TaskNumber = 0;
        }
        WorkingPlace.SignalFreeNPCPoint = false;
    }
}
</code>```

How the code works:
When you click on the button, an NPC with the status 0 is searched, the last NPC with this status is taken and entered into the array, after which it is given a different status to perform "work", after which it is removed from the array to make room for another NPC.
In this case, the array is a buffer and is simply necessary. If you have better ideas than mine, I will be happy to listen)
The implementation is a clean bike made of crutches, but it works flawlessly. Yes, about FPS drawdowns, it doesn't seem to load the system much, if there are drawdowns, then write what to fix.

Title: Limit on the number of NPCs

Body:
I made, so, to begin with, the code:

File WorkingPlace:

public static bool SignalFreeNPCPoint = false;
public static int WorkingPlaceNPC = 0;
public void ProductBoardNPC()
{
    SignalFreeNPCPoint = true;
    WorkingPlaceNPC += 1;
}
public void ProductBoard_Stop()
{
    WorkingPlaceNPC -= 1;
    SignalFreeNPCPoint = true;
}

This "ProductBoardNPC()" and "ProductBoard_Stop()" method's for button in Unity.

File NPCSctipt:

public List<GameObject> ListGM = new List<GameObject>();
public int TaskNumber = 0;
void Update()
{
    TaskManager();
    LogicNPC();
}
private void TaskManager()
{
    switch (TaskNumber)
    {
        case 0:
            //You code
            break;
        case 1:
            ListGM.Remove(gameObject);
            break;
        case 2:
            ListGM.Remove(gameObject);
            break;
        case 3:
            ListGM.Remove(gameObject);
            break;
        case 4:
            ListGM.Remove(gameObject);
            break;
    }
}
private void LogicNPC()
{
    if (WorkingPlace.SignalFreeNPCPoint == true)
    {
        if (TaskNumber == 0 & WorkingPlace.WorkingPlaceNPC == 1)
        {
            ListGM.Add(gameObject);
            TaskNumber = 4;
        }
        if (TaskNumber == 4 & WorkingPlace.WorkingPlaceNPC == 0)
        {
            TaskNumber = 0;
        }
        WorkingPlace.SignalFreeNPCPoint = false;
    }
}

How the code works:
When you click on the button, an NPC with the status 0 is searched, the last NPC with this status is taken and entered into the array, after which it is given a different status to perform "work", after which it is removed from the array to make room for another NPC.
In this case, the array is a buffer and is simply necessary. If you have better ideas than mine, I will be happy to listen)
The implementation is a clean bike made of crutches, but it works flawlessly. Yes, about FPS drawdowns, it doesn't seem to load the system much, if there are drawdowns, then write what to fix.


问:
Having issue publishing Node.js project to azure web service
I got this error when I publish to Azure web service.
I installed and see that package mentioned in the error ipaddr.js in the node_modules folder though

Severity  Code    Description Project File    Line    Suppression State
Error TS6053  File
'C:/CodingProjects/OrderPickUp_App/OrderPickUp_App/node_modules/ipaddr.js'
not found.   The file is in the program because:
Root file specified for compilation   OrderPickUp_App JavaScript Content Files        1   Active

答:
Few of the workarounds to solve the Severity Code Description Project File Line Suppression State Error TS6053 File .js' not found.

Restarting the Visual Studio / Visual Studio Code / IDE

Remove %temp% data

If Restarting the IDE appears the same error, try Opening the IDE > file - Folder Close and re-open File - Open Folder

Please check the workarounds which is a kind of similar error from Ref1, Ref2 which resolves this kind of errors.


问:
My first CSS animation with SVG works but not the second
I am not able to more think it over, I tried so many variations playing with delay, fill options, etc... it is impossible (unfortunately not impossible) that the same kind of thing does not work than the other.
I have a page title composed by two SVG. I hide the two SVG until preloader opens the page, then with Jquery I display them, then the first SVG appears and plays the animation, then some second later the other one plays the same kind of animation.
Jquery works well, also the first animation plays well, but the second one does not.
I made a jsfiddle, there both animations work well : https://jsfiddle.net/igorlaszlo/r2gtwpmb/37/, so I just guess that a plugin/script can block the second animation.
Here is my test website : http://feketekutya.com/test/

HTML (I shortened paths)

```<code><section class="welcome">
    <svg xmlns="http://www.w3.org/2000/svg" width="1e3pt" height="350pt" viewBox="0 0 1e3 350" id="title">
        <path fill="none" stroke="#fff" class="go" d="..." />
    </svg>
    <svg xmlns="http://www.w3.org/2000/svg" width="400pt" height="70pt" viewBox="0 0 400 70" id="subtitle">
        <path fill="none" stroke="#2b4462" class="go2" d="..." />
</section>
</code>```

CSS

```<code>#title {
  position:relative;
  display:none;
  margin:20% 0 0;
  padding:0 0 0 30px;
  width: 48%;
  max-width:1000px;
  height: auto;
  max-height:350px;
  filter: drop-shadow(1px 1px 0px rgba(0, 0, 0, 0.5));
  z-index:2
}
.go {
  stroke: #fff;
  stroke-dasharray: 1800;
  stroke-dashoffset: 1800;
  animation:go 3s linear forwards;
}
@keyframes go {
  0% {
      stroke-width: 4;
      stroke-dashoffset: 1800;
      fill: rgba(255,255,255,0);
  }
  100% {
    stroke-width: 1;
    stroke-dashoffset: 0;
    fill: rgba(255,255,255,1);
  }
}
#subtitle {
  position:relative;
  display:none;
  margin:50px 0 0;
  padding:0 0 0 32%;
  width: 20%;
  max-width:400px;
  height: auto;
  max-height:70px;
  z-index:2
}
.go2 {
  stroke: #2b4462;
  stroke-dasharray: 700;
  stroke-dashoffset: 700;
  animation:go2 3s linear forwards;
  fill: rgba(43,68,98,1);
}
@keyframes go2 {
  0% {
      stroke-width: 4;
      stroke-dashoffset: 700;
      fill: rgba(43,68,98,0);
  }
  100% {
    stroke-width: 1;
    stroke-dashoffset: 0;
    fill: rgba(43,68,98,1);
  }
}
</code>```

Jquery

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

    $('body').hide();

    //calling jPreLoader
    $('body').jpreLoader({
        showSplash: false,
        showPercentage: false,
        splashVPos: null,
        loaderVPos: null,
        autoClose: true,
    }, function() { //callback function
        $('body').fadeIn(0);
        $('#title').css('display', 'block');
        $('#subtitle').css('display', 'block');
    });
});
</code>```

答:
I can't see the subtitle on your website. Please change your padding in css.</p>
```<code>#subtitle {
 padding:0;
...
...
}
</code>```

Body:
I am not able to more think it over, I tried so many variations playing with delay, fill options, etc... it is impossible (unfortunately not impossible) that the same kind of thing does not work than the other.
I have a page title composed by two SVG. I hide the two SVG until preloader opens the page, then with Jquery I display them, then the first SVG appears and plays the animation, then some second later the other one plays the same kind of animation.
Jquery works well, also the first animation plays well, but the second one does not.
I made a jsfiddle, there both animations work well : https://jsfiddle.net/igorlaszlo/r2gtwpmb/37/, so I just guess that a plugin/script can block the second animation.
Here is my test website : http://feketekutya.com/test/

HTML (I shortened paths)

    <svg xmlns="http://www.w3.org/2000/svg" width="1e3pt" height="350pt" viewBox="0 0 1e3 350" id="title">
        <path fill="none" stroke="#fff" class="go" d="..." />
    </svg>
    <svg xmlns="http://www.w3.org/2000/svg" width="400pt" height="70pt" viewBox="0 0 400 70" id="subtitle">
        <path fill="none" stroke="#2b4462" class="go2" d="..." />

CSS

#title {
  position:relative;
  display:none;
  margin:20% 0 0;
  padding:0 0 0 30px;
  width: 48%;
  max-width:1000px;
  height: auto;
  max-height:350px;
  filter: drop-shadow(1px 1px 0px rgba(0, 0, 0, 0.5));
  z-index:2
}
.go {
  stroke: #fff;
  stroke-dasharray: 1800;
  stroke-dashoffset: 1800;
  animation:go 3s linear forwards;
}
@keyframes go {
  0% {
      stroke-width: 4;
      stroke-dashoffset: 1800;
      fill: rgba(255,255,255,0);
  }
  100% {
    stroke-width: 1;
    stroke-dashoffset: 0;
    fill: rgba(255,255,255,1);
  }
}
#subtitle {
  position:relative;
  display:none;
  margin:50px 0 0;
  padding:0 0 0 32%;
  width: 20%;
  max-width:400px;
  height: auto;
  max-height:70px;
  z-index:2
}
.go2 {
  stroke: #2b4462;
  stroke-dasharray: 700;
  stroke-dashoffset: 700;
  animation:go2 3s linear forwards;
  fill: rgba(43,68,98,1);
}
@keyframes go2 {
  0% {
      stroke-width: 4;
      stroke-dashoffset: 700;
      fill: rgba(43,68,98,0);
  }
  100% {
    stroke-width: 1;
    stroke-dashoffset: 0;
    fill: rgba(43,68,98,1);
  }
}

Jquery

$(document).ready(function() {

    $('body').hide();

    //calling jPreLoader
    $('body').jpreLoader({
        showSplash: false,
        showPercentage: false,
        splashVPos: null,
        loaderVPos: null,
        autoClose: true,
    }, function() { //callback function
        $('body').fadeIn(0);
        $('#title').css('display', 'block');
        $('#subtitle').css('display', 'block');
    });
});

Body:
I can't see the subtitle on your website. Please change your padding in css.

#subtitle {
 padding:0;
...
...
}


问:
How to get an alien to die when it hits a laser beam in python game?
I'm pretty new to python and I am currently taking a computer programming course in high school and I'm having trouble with my Galaga/Space Invaders knockoff. I'm trying to make so if the laser beam is in the same x range as an "alive" alien that it will change the alien to a "dead" one.(changing which pixels are visible). I can't seem to get the alive/visible parameter from my variable to the onMouseClick function and just get an error of
if alien1.visible==True:
AttributeError: 'NoneType' object has no attribute 'visible
whenever I click. We are using a version of python called CMU CS Academy which seems to function almost identically to python. I attached the full code below with the condensed parts just being the drawing of aliens or movement of the spaceship.

https://docs.google.com/document/d/1pmaTq8uvrGfDLkxPdxa1gc9dOr4Qd6f9TLrwtJ6mGmo/edit?usp=sharing

Image:
https://i.stack.imgur.com/DXdX7.png

答: You should claim aliens before you call it. Just put the part of #Aliens before #Spaceship Movement Left. It should be fine then.</p>


问:
Merge two variable values to get a new variable name (not value)
is possible in php to merge the first variable value with the second variable value to get a new variable name (not value).

```<code>$1 = test
$2 = 5
//do magic results in new variable name eg. $($1+$2)
$test5 = true
</code>```

So if $2 is dynamic we get a dynamic variable name, not a dynamic value. The value "true" is just an example value. I don't know If it is possible, because I'm completely new to PHP and found nothing by searching.

答:
Yes. Use {} after the $ sign to interpret the inner content as the variable name.

```<code>$a = "test";
$b = 5;

${$a . $b} = "new value";
echo "test5 = " . $test5; // prints test5 = new value
</code>```

See manual page for more details.

Body:
is possible in php to merge the first variable value with the second variable value to get a new variable name (not value).

$1 = test
$2 = 5
//do magic results in new variable name eg. $($1+$2)
$test5 = true

So if $2 is dynamic we get a dynamic variable name, not a dynamic value. The value "true" is just an example value. I don't know If it is possible, because I'm completely new to PHP and found nothing by searching.

Body:
Yes. Use {} after the $ sign to interpret the inner content as the variable name.

$a = "test";
$b = 5;

${$a . $b} = "new value";
echo "test5 = " . $test5; // prints test5 = new value

See manual page for more details.


问:
How to detect the object being double released with Xcode - message sent to deallocated instance?
I am relatively new to Xcode4 and I would like to know how can I identify a double release with it.

In the debugger I see a line like *** -[NSConcreteMutableData release]: message sent to deallocated instance 0x60b63fe0.

The problem is that knowing the address doesn't help a lot identifying the object and also the object type doesn't help too much identifying it.

I read http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/ but I did not found this to be too successful.

答: You are sending a release message to something which already is released or having retainCount 0. Hence, its giving such an error message. Actually, my answer over here might help.</p>


问:
discord py bot has no attribute slash_command
That is all of the imports I have, it works on my pc however when I tried to run it on my pi4 I got the error saying no attribute slash_command, I installed all the packages I thought I needed which was, py-cord, discord.py. Any help would be appreciated.

答:
I figured it out I had to install py-cord through this command:

```<code>pip install -U git+https://github.com/Pycord-Development/pycord
</code>```

Body:
I figured it out I had to install py-cord through this command:

pip install -U git+https://github.com/Pycord-Development/pycord


问:
EJS in Express.js - Express Helpers not working - (app) in require
I'm using the EJS template engine with express.js and I want to use the view helpers. I found this on github: https://github.com/tanema/express-helpers, but when I try to use it I get this error:

```<code>TypeError: object is not a function
at Object.CALL_NON_FUNCTION (native)
at Object. (/home/node/app/app.js:12:40)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at Array. (module.js:421:10)
at EventEmitter._tickCallback (node.js:126:26)
</code>```

whereas this line is line 12 on app.js:

```<code>var helpers = require('express-helpers')(app);
</code>```

and if I make it

```<code>var helpers = require('express-helpers');
</code>```

it does throw the error, but also does not work.

My top of the app.js file is as follows:

```<code>var express = require('express');
var app = express.createServer();
app.listen(34573);

// !Requires
var helpers = require('express-helpers')(app);
</code>```

Ideas?

Thanks in advance!

答:
My bad.

It turns out that I had my links mixed, and the usage I was trying was meant for a forked branch. I cloned the branch, and overwrote the default https://github.com/masahiroh/express-helpers and the code worked as it was supposed to with the correct branch.

Thanks anyway!

Body:
I'm using the EJS template engine with express.js and I want to use the view helpers. I found this on github: https://github.com/tanema/express-helpers, but when I try to use it I get this error:

TypeError: object is not a function
at Object.CALL_NON_FUNCTION (native)
at Object. (/home/node/app/app.js:12:40)
at Module._compile (module.js:402:26)
at Object..js (module.js:408:10)
at Module.load (module.js:334:31)
at Function._load (module.js:293:12)
at Array. (module.js:421:10)
at EventEmitter._tickCallback (node.js:126:26)

whereas this line is line 12 on app.js:

var helpers = require('express-helpers')(app);

and if I make it

var helpers = require('express-helpers');

it does throw the error, but also does not work.

My top of the app.js file is as follows:

var express = require('express');
var app = express.createServer();
app.listen(34573);

// !Requires
var helpers = require('express-helpers')(app);

Ideas?

Thanks in advance!


问:
Reshaping an array of matrices into one matrix without a for-loop
I want to reshape an array of matrices into a single matrix, so that if the original array has shape (n, m, N) the new matrix, X, has shape (N, nxm) and in a way so that if we look at X[i,:].reshape(n,m) we would get back the original i-th matrix.

This can be done with a for-loop and ravel:

```<code>X = np.zeros((N, n*m))
for i in range(N):
  X[i, :]=Y[:,:,i].ravel() # Y is the original array with shape (n,m,N)
print(X.shape)
</code>```

Question
Is there a way to do this without using a for-loop, perhaps with just reshape and some other functions? I did not quite find this case when I tried to search online, and doing simply X=Y.reshape((N, n*m)) does not preserve the matrix structure when we check an entry as described above.

答: Before np.reshape, you can use np.moveaxis (e.g. np.moveaixs(Y, -1, 0)) to move the last axis of Y to the first and make its size to (N, n, m) with the matrix stucture preserved.

Body:
I want to reshape an array of matrices into a single matrix, so that if the original array has shape (n, m, N) the new matrix, X, has shape (N, nxm) and in a way so that if we look at X[i,:].reshape(n,m) we would get back the original i-th matrix.

This can be done with a for-loop and ravel:

X = np.zeros((N, n*m))
for i in range(N):
  X[i, :]=Y[:,:,i].ravel() # Y is the original array with shape (n,m,N)
print(X.shape)

Question
Is there a way to do this without using a for-loop, perhaps with just reshape and some other functions? I did not quite find this case when I tried to search online, and doing simply X=Y.reshape((N, n*m)) does not preserve the matrix structure when we check an entry as described above.


问:
exec vs import, why errors only in one of them
I downloaded the code from here https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions, specifically using model 1. I downloaded the weights corresponding and created the following file to load the model and test. First, I copy the Unet part in main.py into a separate file umodel.py and the test file as follows

```<code>import torch
exec(open("./umodel.py").read())
network_data = torch.load('snapshot_fold_8_best')

print(network_data.keys())
import sys
sys.path.append("geffnet")

class Namespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
args = Namespace(extra_num = 1,
                 dec_ch =  [32, 64, 128, 256, 1024],
                 stride=32,
                 net='b5',
                 bot1x1=True,
                 glob=True,
                 bn=True,
                 aspp=True,
                 ocr=True,
                 aux_scale=True)

def load_state_dict(model, state_dict):
    missing_keys = []

# from UnetOS.umodel import Unet
exec(open("./umodel.py").read())
try:
    from torch.hub import load_state_dict_from_url
except ImportError:
    from torch.utils.model_zoo import load_url as load_state_dict_from_url

# from UnetOS.umodel import *

model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
        ocr=args.ocr, aux = args.aux_scale > 0).cuda()

load_state_dict(model, network_data)
</code>```

My question is, why exec(open("./umodel.py").read()) works nicely but whenever I tried to import from umodel import Unet it has errors

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_10492/1282530406.py in <module>
      9 # ah
     10 model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
---> 11         ocr=args.ocr, aux = args.aux_scale > 0).cuda()
     12 #model = Unet()
     13 #print(network_data.key())

D:\hines\Pretrained\1-zbigniewwojna\UnetOS\umodel.py in __init__(self, extra_num, dec_ch, stride, net, bot1x1, glob, bn, aspp, ocr, aux)
    238             ['ir_r4_k5_s2_e6_c192_se0.25'],
    239             ['ir_r1_k3_s1_e6_c320_se0.25']]
--> 240         enc = GenEfficientNet(in_chans=3, block_args=decode_arch_def(arch_def, depth_multiplier),
    241                               num_features=round_channels(1280, channel_multiplier, 8, None), stem_size=32,
    242                               channel_multiplier=channel_multiplier, act_layer=resolve_act_layer({}, 'swish'),

NameError: name 'decode_arch_def' is not defined```

The main file is as follow https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions/blob/master/1-zbigniewwojna/main.py

答:
From the error message, it appears that decode_arch_def is not available and looking at your imports, that has to come from from geffnet.efficientnet_builder import * (it does https://github.com/rwightman/gen-efficientnet-pytorch/blob/master/geffnet/efficientnet_builder.py)

Your exec must have worked because it followed a similar import, that brought decode_arch_def in scope - exec() executes code in the current scope, so it will work because in that scope decode_arch_def is already defined.

However, when you import, the imported module itself doesn't have the function you need in scope. You should add the required import statements to the file you're importing to bring them into scope and it should work.

For example, with a mod.py containing this:

```<code>def my_func():
    print(datetime.now())
</code>```

This works:

```<code>from datetime import datetime

exec(open("./mod.py").read())
my_func()
</code>```

But this does not:

```<code>from datetime import datetime
import mod

mod.my_func()
</code>```

To make that work, mod.py would have to be:

```<code>from datetime import datetime

def my_func():
    print(datetime.now())

</code>```

And the import of datetime wouldn't be needed in the main program, since it's not referenced there. Your code has a similar issue - you need to determine all the dependencies of your Unet class and import them.

Body:
I downloaded the code from here https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions, specifically using model 1. I downloaded the weights corresponding and created the following file to load the model and test. First, I copy the Unet part in main.py into a separate file umodel.py and the test file as follows

import torch
exec(open("./umodel.py").read())
network_data = torch.load('snapshot_fold_8_best')

print(network_data.keys())
import sys
sys.path.append("geffnet")

class Namespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
args = Namespace(extra_num = 1,
                 dec_ch =  [32, 64, 128, 256, 1024],
                 stride=32,
                 net='b5',
                 bot1x1=True,
                 glob=True,
                 bn=True,
                 aspp=True,
                 ocr=True,
                 aux_scale=True)

def load_state_dict(model, state_dict):
    missing_keys = []

# from UnetOS.umodel import Unet
exec(open("./umodel.py").read())
try:
    from torch.hub import load_state_dict_from_url
except ImportError:
    from torch.utils.model_zoo import load_url as load_state_dict_from_url

# from UnetOS.umodel import *

model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
        ocr=args.ocr, aux = args.aux_scale > 0).cuda()

load_state_dict(model, network_data)

My question is, why exec(open("./umodel.py").read()) works nicely but whenever I tried to import from umodel import Unet it has errors

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

~\AppData\Local\Temp/ipykernel_10492/1282530406.py in <module>
      9 # ah
     10 model = Unet(extra_num = args.extra_num, dec_ch = args.dec_ch, stride=args.stride, net=args.net, bot1x1 = args.bot1x1, glob=args.glob, bn=args.bn, aspp=args.aspp,
---> 11         ocr=args.ocr, aux = args.aux_scale > 0).cuda()
     12 #model = Unet()
     13 #print(network_data.key())

D:\hines\Pretrained\1-zbigniewwojna\UnetOS\umodel.py in __init__(self, extra_num, dec_ch, stride, net, bot1x1, glob, bn, aspp, ocr, aux)
    238             ['ir_r4_k5_s2_e6_c192_se0.25'],
    239             ['ir_r1_k3_s1_e6_c320_se0.25']]
--> 240         enc = GenEfficientNet(in_chans=3, block_args=decode_arch_def(arch_def, depth_multiplier),
    241                               num_features=round_channels(1280, channel_multiplier, 8, None), stem_size=32,
    242                               channel_multiplier=channel_multiplier, act_layer=resolve_act_layer({}, 'swish'),

NameError: name 'decode_arch_def' is not defined

The main file is as follow https://github.com/SpaceNetChallenge/SpaceNet_SAR_Buildings_Solutions/blob/master/1-zbigniewwojna/main.py

Body:
From the error message, it appears that decode_arch_def is not available and looking at your imports, that has to come from from geffnet.efficientnet_builder import * (it does https://github.com/rwightman/gen-efficientnet-pytorch/blob/master/geffnet/efficientnet_builder.py)

Your exec must have worked because it followed a similar import, that brought decode_arch_def in scope - exec() executes code in the current scope, so it will work because in that scope decode_arch_def is already defined.

However, when you import, the imported module itself doesn't have the function you need in scope. You should add the required import statements to the file you're importing to bring them into scope and it should work.

For example, with a mod.py containing this:

def my_func():
    print(datetime.now())

This works:

from datetime import datetime

exec(open("./mod.py").read())
my_func()

But this does not:

from datetime import datetime
import mod

mod.my_func()

To make that work, mod.py would have to be:

from datetime import datetime

def my_func():
    print(datetime.now())

And the import of datetime wouldn't be needed in the main program, since it's not referenced there. Your code has a similar issue - you need to determine all the dependencies of your Unet class and import them.


问:
Angular/TypeScript treats array as object and throws an Error: Cannot find a differ supporting object
My code is the following in my component, I defined this:

```<code>public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];
</code>```

In my template:

```<code>  <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
     <button class="dropdown-item" *ngFor="let format of outputFormats"
         (click)="onOutputFormatChanged(format)">{{format}}
     </button>
  </div>
</code>```

But I get the following error on init.

```<code>  ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.ngDoCheck (common.js:3323:1)
      at callHook (core.js:2536:1)
      at callHooks (core.js:2495:1)
      at executeInitAndCheckHooks (core.js:2446:1)
      at selectIndexInternal (core.js:8447:1)
      at Module.ɵɵadvance (core.js:8430:1)
      at PrintComponent_Template (print.component.html:41:48)
      at executeTemplate (core.js:9598:1)
      at refreshView (core.js:9464:1)
      at refreshComponent (core.js:10635:1)
  defaultErrorLogger @ core.js:6479
  handleError @ core.js:6527
  (anonymous) @ core.js:29723
  invoke @ zone.js:372
  run @ zone.js:134
  runOutsideAngular @ core.js:28604
  tick @ core.js:29723
  (anonymous) @ core.js:29571
  invoke @ zone.js:372
  onInvoke @ core.js:28705
  invoke @ zone.js:371
  run @ zone.js:134
  run @ core.js:28559
  next @ core.js:29570
  __tryOrUnsub @ Subscriber.js:183
  next @ Subscriber.js:122
  _next @ Subscriber.js:72
  next @ Subscriber.js:49
  next @ Subject.js:39
  emit @ core.js:25968
  checkStable @ core.js:28627
  onLeave @ core.js:28755
  onInvokeTask @ core.js:28699
  invokeTask @ zone.js:405
  runTask @ zone.js:178
  invokeTask @ zone.js:487
  invokeTask @ zone.js:1600
  globalZoneAwareCallback @ zone.js:1626
</code>```

When I did console.log(typeof this.outputFormats), it returns object. I tried to convert it to array using Array.from(this.outputFormats), Object.values(this.outputFormats) but the result is still the same, it is output is still an object.

Versions:
Angular Cli 12.1.4
TypeScript 4.3.5

Solutions that didn't work for me:

https://github.com/angular/angular/issues/6392

Angular error : Cannot find a differ supporting object '[object Object]'

Angular: Cannot find a differ supporting object '[object Object]'

答:
I've got modified a version of the documentation example to use what you've shared and it's working at https://stackblitz.com/edit/angular-3pnr1l with the TS/Angular versions you specified. It's ng-bootstrap 11.0 for what it's worth, but you hadn't specified that.

One difference in the implementation is the use of <Button ngbDropdownItem.

```<code># dropdown-basic.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { NgbdDropdownBasic } from './dropdown-basic';

@NgModule({
  imports: [BrowserModule, NgbModule],
  declarations: [NgbdDropdownBasic],
  exports: [NgbdDropdownBasic],
  bootstrap: [NgbdDropdownBasic]
})
export class NgbdDropdownBasicModule {}

# dropdown-basic.ts
import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-dropdown-basic',
  templateUrl: './dropdown-basic.html'
})
export class NgbdDropdownBasic {
  public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];
}

# dropdown-basic.html
<div ngbDropdown class="d-inline-block">
  <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>
    Toggle dropdown
  </button>
  <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
    <button
      ngbDropdownItem
      class="dropdown-item"
      *ngFor="let format of outputFormats"
    >
      {{format}}
    </button>
  </div>
</div>
</code>```

If it's not working for you with this exact setup, then this error may be a red herring and you could have your hands full with isolating exactly what's causing it to break. We don't have enough insight into your surrounding code to really diagnose this. Hopefully you spot something that's obvious and different from this example.

Body:
My code is the following in my component, I defined this:

public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];

In my template:

     <button class="dropdown-item" *ngFor="let format of outputFormats"
         (click)="onOutputFormatChanged(format)">{{format}}
     </button>

But I get the following error on init.

  ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.ngDoCheck (common.js:3323:1)
      at callHook (core.js:2536:1)
      at callHooks (core.js:2495:1)
      at executeInitAndCheckHooks (core.js:2446:1)
      at selectIndexInternal (core.js:8447:1)
      at Module.ɵɵadvance (core.js:8430:1)
      at PrintComponent_Template (print.component.html:41:48)
      at executeTemplate (core.js:9598:1)
      at refreshView (core.js:9464:1)
      at refreshComponent (core.js:10635:1)
  defaultErrorLogger @ core.js:6479
  handleError @ core.js:6527
  (anonymous) @ core.js:29723
  invoke @ zone.js:372
  run @ zone.js:134
  runOutsideAngular @ core.js:28604
  tick @ core.js:29723
  (anonymous) @ core.js:29571
  invoke @ zone.js:372
  onInvoke @ core.js:28705
  invoke @ zone.js:371
  run @ zone.js:134
  run @ core.js:28559
  next @ core.js:29570
  __tryOrUnsub @ Subscriber.js:183
  next @ Subscriber.js:122
  _next @ Subscriber.js:72
  next @ Subscriber.js:49
  next @ Subject.js:39
  emit @ core.js:25968
  checkStable @ core.js:28627
  onLeave @ core.js:28755
  onInvokeTask @ core.js:28699
  invokeTask @ zone.js:405
  runTask @ zone.js:178
  invokeTask @ zone.js:487
  invokeTask @ zone.js:1600
  globalZoneAwareCallback @ zone.js:1626

When I did console.log(typeof this.outputFormats), it returns object. I tried to convert it to array using Array.from(this.outputFormats), Object.values(this.outputFormats) but the result is still the same, it is output is still an object.

Versions:
Angular Cli 12.1.4
TypeScript 4.3.5

Solutions that didn't work for me:

https://github.com/angular/angular/issues/6392

Angular error : Cannot find a differ supporting object '[object Object]'

Angular: Cannot find a differ supporting object '[object Object]'

Body:
I've got modified a version of the documentation example to use what you've shared and it's working at https://stackblitz.com/edit/angular-3pnr1l with the TS/Angular versions you specified. It's ng-bootstrap 11.0 for what it's worth, but you hadn't specified that.

One difference in the implementation is the use of <Button ngbDropdownItem.

# dropdown-basic.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';

import { NgbdDropdownBasic } from './dropdown-basic';

@NgModule({
  imports: [BrowserModule, NgbModule],
  declarations: [NgbdDropdownBasic],
  exports: [NgbdDropdownBasic],
  bootstrap: [NgbdDropdownBasic]
})
export class NgbdDropdownBasicModule {}

# dropdown-basic.ts
import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-dropdown-basic',
  templateUrl: './dropdown-basic.html'
})
export class NgbdDropdownBasic {
  public outputFormats =  ["pdf", "png32", "png8", "jpg", "gif", "eps", "svg"];
}

# dropdown-basic.html
<div ngbDropdown class="d-inline-block">
  <button class="btn btn-outline-primary" id="dropdownBasic1" ngbDropdownToggle>
    Toggle dropdown
  </button>
  <div ngbDropdownMenu aria-labelledby="polylineStyleDropdown">
    <button
      ngbDropdownItem
      class="dropdown-item"
      *ngFor="let format of outputFormats"
    >
      {{format}}
    </button>
  </div>
</div>

If it's not working for you with this exact setup, then this error may be a red herring and you could have your hands full with isolating exactly what's causing it to break. We don't have enough insight into your surrounding code to really diagnose this. Hopefully you spot something that's obvious and different from this example.


问:
Vue3 - How to override styles after importing node_modules css file?
I have a standard Vue3 app using the library https://github.com/ismail9k/vue3-carousel.

In my App.vue file, I have the following, which is required to use the library:

```<code><style>
@import "~vue3-carousel/dist/carousel.css";
</style>
</code>```

Since I don't want to use the library's default colors, I'm trying to override some styles.

The library defines some colors on :root, such as:

```<code>--vc-clr-primary: #333333;
--vc-pgn-background-color: var(--vc-clr-primary);
</code>```

Then, the style that I want to ultimately override is:

```<code>.carousel__pagination-button {
  ...
  background-color: var(--vc-pgn-background-color);
}
</code>```

So, I assume that I want to override either of the variables, or the class itself. In my Component.vue file, I have the following:

```<code><style scoped>
.carousel__pagination-button {
  background-color: #999999 !important;
}
</style>
</code>```

But that doesn't do anything.

I don't care where I override these colors, because I'll use the same colors throughout the website, but I can't figure out how to get them to override no matter where or how I attempt to override them.

What am I doing wrong?

答:
This worked:

App.vue

```<code>...

<style>
#app {
  --vc-pgn-background-color: #mycolor;
}

@import "~vue3-carousel/dist/carousel.css";
</style>
</code>```

Body:
I have a standard Vue3 app using the library https://github.com/ismail9k/vue3-carousel.

In my App.vue file, I have the following, which is required to use the library:

Since I don't want to use the library's default colors, I'm trying to override some styles.

The library defines some colors on :root, such as:

--vc-clr-primary: #333333;
--vc-pgn-background-color: var(--vc-clr-primary);

Then, the style that I want to ultimately override is:

.carousel__pagination-button {
  ...
  background-color: var(--vc-pgn-background-color);
}

So, I assume that I want to override either of the variables, or the class itself. In my Component.vue file, I have the following:

But that doesn't do anything.

I don't care where I override these colors, because I'll use the same colors throughout the website, but I can't figure out how to get them to override no matter where or how I attempt to override them.

What am I doing wrong?

Body:
This worked:

App.vue

...

<style>
#app {
  --vc-pgn-background-color: #mycolor;
}

@import "~vue3-carousel/dist/carousel.css";
</style>


答:
list comprehension

X = np.r_[[Y[:, :, i].ravel() for i in Y.shape[2]]]

Title: Reshaping an array of matrices into one matrix without a for-loop


问:
Creating a vector of set
In my code I have a vector defined:

```<code>vector<vector<vector<vector<shared_ptr<foo> > > > > fooBoxes;
</code>```

I am initializing the vector using:

```<code>int BOX_NUM = 12 //this is actually defined elsewhere

fooBoxes.resize(BOX_NUM);
for (int i = 0; i<BOX_NUM; i++){
  fooBoxes[i].resize(BOX_NUM);
  for (int j = 0; j < BOX_NUM; j++){
    fooBoxes[i][j].resize(BOX_NUM);
    for (int k = 0; k < BOX_NUM; k++){
      fooBoxes[i][j][k].resize(0);
    }
  }
}
</code>```

I suspect that the use of vector is causing me a segmentation fault and I want to replace fooBoxes to be:

```<code>vector<vector<vector<set<shared_ptr<foo> > > > > fooBoxes
</code>```

what do I do in the for loops? simply remove the resize(0) part?

Edit:

This is the output of valgrind in the crash:

```<code>==2258== Invalid read of size 8
==2258==    at 0x439237: trans(int) (stl_iterator.h:704)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  Address 0x7932420 is 8 bytes after a block of size 24 free'd
==2258==    at 0x4A05743: operator delete(void*) (vg_replace_malloc.c:346)
==2258==    by 0x405636: vec::~vec() (valarray_array.h:71)
==2258==    by 0x437D66: trans(int) (transFile.cpp:64)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==
==2258== Invalid read of size 8
==2258==    at 0x439240: trans(int) (stl_vector.h:604)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  Address 0x111 is not stack'd, malloc'd or (recently) free'd
==2258==
==2258==
==2258== Process terminating with default action of signal 11 (SIGSEGV)
==2258==  Access not within mapped region at address 0x111
==2258==    at 0x439240: trans(int) (stl_vector.h:604)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  If you believe this happened as a result of a stack
==2258==  overflow in your program's main thread (unlikely but
==2258==  possible), you can try to increase the size of the
==2258==  main thread stack using the --main-stacksize= flag.
==2258==  The main thread stack size used in this run was 10485760.
</code>```

I believe that the problem is that I'm not careful enough when I try to delete/put a bead into a vector and this is why I want to move to set.

答: That depends on what you want to achieve. Your code will most definitely compile if you remove fooBoxes[i][j][k].resize(0); since the std::set does not support this function.

Title: Creating a vector of set

Body:
In my code I have a vector defined:

vector<vector<vector<vector<shared_ptr<foo> > > > > fooBoxes;

I am initializing the vector using:

int BOX_NUM = 12 //this is actually defined elsewhere

fooBoxes.resize(BOX_NUM);
for (int i = 0; i<BOX_NUM; i++){
  fooBoxes[i].resize(BOX_NUM);
  for (int j = 0; j < BOX_NUM; j++){
    fooBoxes[i][j].resize(BOX_NUM);
    for (int k = 0; k < BOX_NUM; k++){
      fooBoxes[i][j][k].resize(0);
    }
  }
}

I suspect that the use of vector is causing me a segmentation fault and I want to replace fooBoxes to be:

vector<vector<vector<set<shared_ptr<foo> > > > > fooBoxes

what do I do in the for loops? simply remove the resize(0) part?

Edit:

This is the output of valgrind in the crash:

==2258== Invalid read of size 8
==2258==    at 0x439237: trans(int) (stl_iterator.h:704)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  Address 0x7932420 is 8 bytes after a block of size 24 free'd
==2258==    at 0x4A05743: operator delete(void*) (vg_replace_malloc.c:346)
==2258==    by 0x405636: vec::~vec() (valarray_array.h:71)
==2258==    by 0x437D66: trans(int) (transFile.cpp:64)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==
==2258== Invalid read of size 8
==2258==    at 0x439240: trans(int) (stl_vector.h:604)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  Address 0x111 is not stack'd, malloc'd or (recently) free'd
==2258==
==2258==
==2258== Process terminating with default action of signal 11 (SIGSEGV)
==2258==  Access not within mapped region at address 0x111
==2258==    at 0x439240: trans(int) (stl_vector.h:604)
==2258==    by 0x413B0E: membrane::MCstep(int) (membrane.cpp:490)
==2258==    by 0x402767: main (main.cpp:14)
==2258==  If you believe this happened as a result of a stack
==2258==  overflow in your program's main thread (unlikely but
==2258==  possible), you can try to increase the size of the
==2258==  main thread stack using the --main-stacksize= flag.
==2258==  The main thread stack size used in this run was 10485760.

I believe that the problem is that I'm not careful enough when I try to delete/put a bead into a vector and this is why I want to move to set.


问:
python parsing with bs4 an xml to get a list of elements
I have an xml file containing data in this form:

```<code><head xml:id="_2ebf9c0003">\n\nTECHNICAL FIELD</head>\n
<p n="0001" xml:id="_2ebf9c0004">whatever</p>
<p n="0002" xml:id="_2ebf9c0004">whatever</p>
<... other tags and data...>
<head xml:id="_2ebf9c0003">\n\nTITLE</head>\n
</code>```

I know how to get particular elements like:

```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup(PDM_description, 'lxml')
title_element = soup.title$
importing all p elements
paras = soup.findAll('p')
</code>```

The question is how can I add an OR inside the query to get a list of "p" or "head" elements? More general how to get all the elements with tags belonging to a list.

PSEUDO CODE:

```<code>paras = soup.findAll('p' OR 'head')
</code>```

答:
You can use the , CSS selector, define your tags separated by a comma (,). To use a CSS selector, use the .select() method:

```<code>print(
    soup.select("p, head")
)
</code>```

Body:
I have an xml file containing data in this form:

\n\nTECHNICAL FIELD\n

whatever

whatever

<... other tags and data...>
\n\nTITLE\n

I know how to get particular elements like:

from bs4 import BeautifulSoup
soup = BeautifulSoup(PDM_description, 'lxml')
title_element = soup.title$
importing all p elements
paras = soup.findAll('p')

The question is how can I add an OR inside the query to get a list of "p" or "head" elements? More general how to get all the elements with tags belonging to a list.

PSEUDO CODE:

paras = soup.findAll('p' OR 'head')

Body:
You can use the , CSS selector, define your tags separated by a comma (,). To use a CSS selector, use the .select() method:

print(
    soup.select("p, head")
)


问:
Map within a map in react, getting unexpected token expected ","
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

```<code>export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },
</code>```

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

```<code>return(
<div className="col-sm">
   {jobList.map((job, i) =>
      <p>{job.name)</p>
      job.specs.map((spec, i) =>
         <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
      )
   )}
</div>
)
</code>```

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.

答:
Ultimately, I moved the code out of the return

```<code>    let list = jobList.map((job) => {
        return (
          <>
            <p>{job.name}</p>
            {job.specs.map((spec, i) =>
              <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
            )}
          </>
        )
      })
</code>```

And then inside the return I simply put

```<code><div className="col-sm jobList">
   {list}
</div>

</code>```

And it worked like a charm. Thanks for your input everyone!

Body:
I'm trying to iterate through an array of objects and for each object also iterate through the nested array of specs. My data structure looks something like this:

export const jobList = [
    {
        name: "Death Knight",
        specs:  [{name: "Blood"},
                 {name: "FrostDK"},
                 {name:"Unholy"}]
    },

    {
        name: "Shaman",
        specs: [{name:"Elemental"},
                {name:"Enhancement"},
                {name:"RestoShaman"}]
    },

My desired output is

Death Knight

Blood

FrostDK

Unholy

Shaman

Elemental

Enhancement

RestoShaman

Here's the problem code:

return(

   {jobList.map((job, i) =>

{job.name)

      job.specs.map((spec, i) =>

      )
   )}

)

This is throwing a 'Parsing error: Unexpected token, expected ","' on job.specs.map. If I remove
{job.name)
 it lists all of the specs as expected. If I throw a comma after
{job.name)
 then I got "'job' is not defined" on job.specs.map. I'm not understanding why it can't call job.name for each job and then run job.specs.map() afterwards.

Body:
Ultimately, I moved the code out of the return

    let list = jobList.map((job) => {
        return (
          <>
            <p>{job.name}</p>
            {job.specs.map((spec, i) =>
              <img className="spec" src={window.location.origin + '/icons/' + spec.name + '.png'} alt={spec.name} onClick={this.handleClick.bind(this, i)} />
            )}
          </>
        )
      })

And then inside the return I simply put

<div className="col-sm jobList">
   {list}
</div>

And it worked like a charm. Thanks for your input everyone!


答:
You could also use collector transformations and mappings</p>
```<code>listOfQueues.stream().map(a ->
            a.stream().map(String::valueOf).collect(
                    Collectors.joining(","))
    ).collect(Collectors.reducing((a, b) -> a + "\n" + b)).get().toString()
</code>```

Title: Print arraylist of queues separated by commas

Body:
I want to print the values of an arraylist that's filled with queues, but i want to do it separated by a comma.

This is what i'm doing to print the list:

for(int i=1;i<listaOfQueues.size();i++){
      System.out.println(listaOfQueues.get(i).toString()+"\n");
    }

This is my current output:

242424242424242525252525252526262626262626

272727272727272828282828282829292929292929

303030303030303131313131313132323232323232

333333333333333434343434343435353535353535

363636363636363737373737373738383838383838

393939393939394040404040404041414141414141

My desired output:

24,24,24,24,24,24,24,25,25,25,25,25,25,25,26,26,26,26,26,26,26

27,27,27,27,27,27,27,28,28,28,28,28,28,28,29,29,29,29,29,29,29

30,30,30,30,30,30,30,31,31,31,31,31,31,31,32,32,32,32,32,32,32

33,33,33,33,33,33,33,34,34,34,34,34,34,34,35,35,35,35,35,35,35

36,36,36,36,36,36,36,37,37,37,37,37,37,37,38,38,38,38,38,38,38

39,39,39,39,39,39,39,40,40,40,40,40,40,40,41,41,41,41,41,41,41

Any suggestions? Thanks

Body:
You could also use collector transformations and mappings

listOfQueues.stream().map(a ->
            a.stream().map(String::valueOf).collect(
                    Collectors.joining(","))
    ).collect(Collectors.reducing((a, b) -> a + "\n" + b)).get().toString()