text:
Q: Retrive Window Handle in Class Library WinUI3 I am trying to use the PrintManager in a WinUI3 class library project. But with WinUI, currently, we can only use PrintManager if we have the windows handle(HWND) unlike UWP where we could simply use ForCurrentView() without any parameters.
Here is something similar (the difference is they call the PrintManager in UI project itself and not a different class library) https://github.com/marb2000/PrintSample. In this, we retrieve the HWND using the below API:
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
Notice that in the above line a Window object needs to be injected. This is not available to me currently in my class library which will be consumed by a UI project.
Could we retrieve the Windows Handle in the class library without injecting it from the UI code that will be using the library?

A: In a WinUI3 app (or more generally in a Windows desktop app), you can have multiple Windows, contrary to UWP where you could only have only one Window.
That's why there's no more the concept of a "current" window/view.
So, you must pass the Window (or its handle directly) to your functions, something like this for example How to retrieve the window handle of the current WinUI 3 MainWindow from a page in a frame in a NavigationView control on the MainWindow
Another solution, if you're sure there's only one Window for example, is to get its handle by browsing the list of Windows for the current process (you could also filter by current thread, etc.). Here's some C# code with interop calls that does this:
// get all windows in the process
var tops = Win32Window.GetProcessWindows();

// get the first WinUI3 window, its class name is fixed as far as we know
var firstWinUI3 = tops.FirstOrDefault(w => w.ClassName == "WinUIDesktopWin32WindowClass");

// utility class that wraps a win32 window
public class Win32Window
{
    public Win32Window(IntPtr handle)
    {
        Handle = handle;
        ThreadId = GetWindowThreadProcessId(handle, out var processId);
        ProcessId = processId;
    }

    public IntPtr Handle { get; }
    public int ThreadId { get; }
    public int ProcessId { get; }
    public string ClassName => GetClassName(Handle);
    public string Text => GetWindowText(Handle);
    public bool IsEnabled => IsWindowEnabled(Handle);

    public override string ToString()
    {
        var s = ClassName;
        var text = Text;
        if (text != null)
        {
            s += " '" + text + "'";
        }
        return s;
    }

    public static IReadOnlyList<Win32Window> GetTopLevelWindows()
    {
        var list = new List<Win32Window>();
        EnumWindows((h, l) =>
        {
            list.Add(new Win32Window(h));
            return true;
        }, IntPtr.Zero);
        return list.AsReadOnly();
    }

    public static IReadOnlyList<Win32Window> GetProcessWindows()
    {
        var process = Process.GetCurrentProcess();
        var list = new List<Win32Window>();
        EnumWindows((h, l) =>
        {
            var window = new Win32Window(h);
            if (window.ProcessId == process.Id)
            {
                list.Add(window);
            }
            return true;
        }, IntPtr.Zero);
        return list.AsReadOnly();
    }

    private static string GetWindowText(IntPtr hwnd)
    {
        var sb = new StringBuilder(1024);
        GetWindowText(hwnd, sb, sb.Capacity - 1);
        return sb.ToString();
    }

    private static string GetClassName(IntPtr hwnd)
    {
        var sb = new StringBuilder(256);
        GetClassName(hwnd, sb, sb.Capacity - 1);
        return sb.ToString();
    }

    private delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr lParam);

    [DllImport("user32", SetLastError = true)]
    private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

    [DllImport("user32")]
    private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);

    [DllImport("user32")]
    public static extern bool IsWindowEnabled(IntPtr hwnd);

    [DllImport("user32", CharSet = CharSet.Unicode)]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("user32", CharSet = CharSet.Unicode)]
    public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
}


text:
Q: jQuery UI Accordian. I need to make newly appended item active I would like the newly appended section to be active in a jQuery Accordion.
I have a link that appends new sections to the Accordion but currently it is not activating the newly added element as I wish.
$("#add-content-section").on("click", function(){

    var count = $("#accordion .content_section").size();
    var newsection = ++count;
     var html = '
Section '+newsection+'

Test
';

    $('#accordion').append(html).accordion('destroy').accordion({active: newsection});
  });

I have created a JSFiddle to demonstrate http://jsfiddle.net/stefairc/JP2wN/
Thanks!

A: Instead of destroying the accordion, you can refresh it.
Then you could simply trigger the click event.
$('#accordion').append(html).accordion('refresh').find('h4').last().click();

You could also do as Ohgodwhy suggested, and use the index.
var count = $('#accordion').find('h4').length;

// Then later inside your event handler
$('#accordion').append(html).accordion('refresh').accordion({active:count++});

A: Destroy accordion first, then inject html and initialize.
Using active:-1 will activate last section
 $('#accordion').accordion('destroy').append(html).accordion({active:-1});

DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: Truncate HTML elements in Angular Image you had a div with maybe 20 <button> elements:

Sometimes, this can get extremely high. I am wondering what would be the right approach with Angular to "truncate" these to the first "4" buttons and a "More/less"
 tag toggle, which will show or hide the extra buttons on demand.
I understand what I need to do, I know how to do it with jQuery or "primitive HTML", but there must be an angular way I am not seeing (I was thinking on integrating a pipe, which can truncate based on boolean, but not so sure)
Current Code:

  <ng-container *ngFor="let color of car['style']?.colors">

         <md-card-subtitle>
             {{ color.category }} Colors {{display.exterior}}
          </md-card-subtitle>
          <md-card-content>
             <ng-container *ngFor="let option of color?.options">
                <button *ngIf="option.colorChips !== undefined" type="button" (mouseover)="display.exterior = option.name"  (mouseleave)="display.exterior = colors.exterior.name" (click)="setSelectedColor(x)" [ngStyle]="{'background-color': '#' + option.colorChips.primary.hex}"> </button>
              </ng-container>
           </md-card-content>

       </ng-container>

A: You can use Pagination to solve his.
You can limit the number of buttons to be displayed on each page using pagination.
You can use ngx-pagination for this => NGX_PAGINATION
1) Install ngx-pagination npm install ngx-pagination --save
2) Add to app.module.ts @NgModule({
    imports: [BrowserModule, NgxPaginationModule]
3) In your HTML
        <ng-container *ngFor="let option of color?.options | paginate: { itemsPerPage: this.linesperpage, currentPage: p }">

    Lines Per Page
    <select class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput"  [(ngModel)]="linesperpage">
      <option>4</option>
      <option>10</option>
      <option>20</option>
    </select>
<pagination-controls (pageChange)="p = $event" class="my-pagination" ></pagination-controls>

4) In your Component:-
    export class RideSuccessComponent  {

  p = 1;
  linesperpage = 4;
}

By just adding  in select class you can easily modify number of displayed buttons on each page. Hope this helps.

A: There are several ways to solve this. I'll describe below only one of the solutions that I've used recently. Please see this link the section of poplar categories.

*

*You can use ngFor directive to iterate over the collection and then use ngIf directive to conditionally show and hide the desired sections of the buttons.

*In your component class declare a boolean variable and attach it to the button to set it true and false

Please see below code
  <ng-container *ngFor="let featuredCategory of featuredCategories; let i=index">
        <div class="col-sm-3 mb-5 mt-4  mr-auto ml-auto" *ngIf="i<=7">
           show this div if array index is less than 7th item

=8">
           show this div if array index is more than 7th item

      </ng-container>
      <button class="btn btn-primary btn-lg" (click)="showAllCategories = !showAllCategories">
           View Less Categories

           View All Categories

        </button>


text:
Q: How to parameterise a plane? Ie. $2x+3y=z$ I see in the text book, we can equate $x=\cos{}u$, $y=\sin{u}$, $z=v$, but seems to be for cylinders, how do we find a parametric representation of $2x+3y=z$?

A: Let $P:=\{(x,y,z)\in\mathbb{R}^3:2x+3y=z\}$.
$P=\{(x,y,z)\in\mathbb{R}^3:\exists t\in\mathbb{R}, \exists u\in\mathbb{R},  (x=t)\wedge(y=u)\wedge(z=2t+3u)\}
=\{(x,y,z)\in\mathbb{R}^3:\exists t\in\mathbb{R}, \exists u\in\mathbb{R},  (x,y,z)=t(1,0,2)+u(0,1,3)\}=\mathbb{R}(1,0,2)+\mathbb{R}(0,1,3)$


text:
Q: Only one jquery ajax post doesnt work in Firefox I have a problem with ajax post in Firefox.
My code:
var addStats = function(id, type) {
   $.ajax({
      url: '/api.php',
      type: "POST",
      data: {
          id: id,
          type: type
      }
  }).done(function(res){
      console.log('[STATS] Success.');
  }).fail(function() {
      console.log('[STATS] Error.');
  });
};

This code works correctly in Chrome, Opera, IE and Edge but no in Firefox.
I will add that the website also supports sending of forms and it works correctly...
Other code that works in firefox:
$.ajax({
   url: form.attr("action"),
   type: "POST",
   data: form.serialize()
}).done(function(res){
    //
}).fail(function() {
   //
});


text:
Q: Compression / Caching and Request Object not working together ASP.NET I have a slight issue with an ASP.NET application,
I have configured a ViewBag variable to send to my View (using razor) the next page link with querystrings but when enabling this attribute :
public class CompressAttribute : System.Web.Mvc.ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      #region Cache
      HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddDays(1));
      HttpContext.Current.Response.Cache.SetValidUntilExpires(true);
      HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
      HttpContext.Current.Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
      #endregion
      #region Compression
      var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
      if (string.IsNullOrEmpty(encodingsAccepted)) return;

      encodingsAccepted = encodingsAccepted.ToLowerInvariant();
      var response = filterContext.HttpContext.Response;

      if (encodingsAccepted.Contains("deflate"))
      {
        response.AppendHeader("Content-Encoding", "deflate");
        response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
      }
      else if (encodingsAccepted.Contains("gzip"))
      {
        response.AppendHeader("Content-Encoding", "gzip");
        response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
      }
      #endregion
    }
  }

The site doesn't take care of the following statement entirely :
ViewBag.NextPageLink = "/" + culture + "/next/" + pageName + Request.Url.Query;

it only produces the link : /culture/next/pageName but the querystring is not included (it's mark as null).
Is anything in my CompressAttribute that can cause that ? Because clearly when disabling it the redirection works.
EDIT :
It seems that the cache is in cause. Maybe the server doesn't re-render this link when reloading the page with different query.

A: The server returns the same cached page even when the query string has changed.
To tell server to vary the cache per query string, use the HttpCacheVaryByParams.
Example:
HttpContext.Current.Response.Cache.VaryByParams["*"] = true; //* means all params

By the way, you may want to use the OutputCacheAttribute and IIS Compression instead of rolling your own.


text:
Q: Dynamically access TextField in SwiftUI I am creating a TextField dynamically inside VStack. Here TextFields are created as follows:
struct Input: View {

    var title: String
    @State var value:String
    var disableInputMode:Bool = true

    var body: some View {
        VStack {
            Text(title)
                .frame(maxWidth: .infinity, alignment: .leading)
                .foregroundColor(Color("SecondaryTextColor"))
            TextField("", text: $value)
                .disabled(disableInputMode)
                .frame(maxWidth: .infinity, alignment: .leading)
            Divider()
        }
        .padding()
    }
}

and these TextFields depend on some other data fields (which are decided at run time):
ScrollView {
    VStack {
        ForEach(detailsViewModel.details) { datum in
            Input(title: datum.title, value: datum.detail!)
        }
    }.frame(maxWidth: .infinity)
    .padding()
}.background(Color("Light"))
.cornerRadius(25)
.padding()

Now, when a user enters data and tries to apply, I couldn't find how to get those inputs from other views. From the example in this case — from the above view.

A: Solution 1 (iOS 14 *)
Use onChange modifier to detect TextField value changes and update it to your model.
struct Input: View {

    var title: String
    @State var value:String
    var disableInputMode:Bool = false

    var onTextChange: ((String) -> Void)?

    var body: some View {
        VStack {
            Text(title)
                .frame(maxWidth: .infinity, alignment: .leading)
                .foregroundColor(Color("SecondaryTextColor"))
            TextField("", text: $value)
                .onChange(of: value) {
                    // Called each time value changes.
                    if onTextChange != nil {
                        onTextChange!($0)
                    }
                }
                .disabled(disableInputMode)
                .frame(maxWidth: .infinity, alignment: .leading)
            Divider()
        }
        .padding()
    }
}

Solution 2 (iOS 13 *)
Extend Binding to handle custom onChange
extension Binding {
    func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
        Binding(
            get: { self.wrappedValue },
            set: { newValue in
                self.wrappedValue = newValue
                handler(newValue)
            }
        )
    }
}

Then your Input View become
struct Input: View {

    var title: String
    @State var value:String
    var disableInputMode:Bool = false

    var onTextChange: ((String) -> Void)?

    var body: some View {
        VStack {
            Text(title)
                .frame(maxWidth: .infinity, alignment: .leading)
                .foregroundColor(Color("SecondaryTextColor"))
            TextField("", text: $value.onChange(textChanged))
                .disabled(disableInputMode)
                .frame(maxWidth: .infinity, alignment: .leading)
            Divider()
        }
        .padding()
    }

    func textChanged(to value: String) {
        // Called each time value changes.
        if onTextChange != nil {
            onTextChange!(value)
        }
    }
}

How to use:
Both solutions you can use your Input View like follows.
ScrollView {
    VStack {
        ForEach(detailsViewModel.details) { datum in
            Input(title: datum.title, value: datum.detail) { newValue in
                // Each time you will get the update
                // Do what ever you want to do with the new value
                // something like
                // detailsViewModel.update(value: newValue, forItem: datum.id)
                print("Text value for \(datum.id) :", newValue)
            }
        }
    }.frame(maxWidth: .infinity)
    .padding()
}.background(Color("Light"))
.cornerRadius(25)
.padding()


text:
Q: Assigning a collection to a custom created collection page in Shopify? I am using a free Venture theme on Shopify and i am trying to make a custom collection page.
I found a solution in stackoverflow but it was able to help someplace.
How to add collection.liquid to an existing page?
The summery of the solution is:
Copy everything that's in collection.liquid and paste it into a new snippet (let's say you call it collection-copy.liquid).
Then, in the page you want to add the collections page to, just add {% include 'collection-copy' %}
This solution worked well but there is one more issue for me. In the custom created page it says "Sorry, there are no products in this collection" In the customization of the same page there is a "collection" section. But in the "collection" section there is no option to choose a collection. There is only "Enable tag filtering" and "Enable sorting" check boxes.
Webpage: https://mottomfreedom.com/pages/less-is-more
Do you have any idea of assigning a collection with this custom created snippet?

{% paginate collections[settings.frontpage_collection].products by 20 %}

        {{ collection.title }}
        {% if current_tags %}
          – {% assign title_tags = current_tags | join: ', ' %}
          {{ title_tags }}
        {% endif %}

      {% if collection.description != blank %}

          {{ collection.description }}

      {% endif %}

      {% section 'collection-filters' %}

    {% for product in collection.products %}

        {% include 'product-card', product: product %}

    {% else %}
      {% comment %}
        Add default products to help with onboarding for collections/all only.

        The onboarding styles and products are only loaded if the
        store has no products.
      {% endcomment %}
      {% if shop.products_count == 0 %}

            {% assign collection_index = 1 %}
            {% for i in (1..10) %}
              {% case i %}
                {% when 7 %}
                  {% assign collection_index = 1 %}
                {% when 8 %}
                  {% assign collection_index = 2 %}
                {% when 9 %}
                  {% assign collection_index = 3 %}
                {% when 10 %}
                  {% assign collection_index = 4 %}
              {% endcase %}

                        {% capture current %}{% cycle 1, 2, 3, 4, 5, 6 %}{% endcapture %}
                        {{ 'product-' | append: current | placeholder_svg_tag: 'placeholder-svg' }}

{{ 'homepage.onboarding.product_title' | t }}

                      $19.99

                    {% assign view_string_length = 'products.product.view' | t | size %}
                     8 %} btn--narrow{% endif %}">{{ 'products.product.view' | t }}

              {% assign collection_index = collection_index | plus: 1 %}
            {% endfor %}

      {% else %}
        {% comment %}
          If collection exists but is empty, display message
        {% endcomment %}

{{ 'collections.general.no_matches' | t }}

      {% endif %}
    {% endfor %}

  {% if paginate.pages > 1 %}

      {{ paginate | default_pagination | replace: '« Previous', '←' | replace: 'Next »', '→' }}

  {% endif %}

{% endpaginate %}

A: You are right about giving some time before accepting an answer :)) The solution worked but forced me to create 1 page and 4 liquid files per collection. And at the end, i figured out that some sections like "collection.list" doesn't directs to the page which i have created. I think you were talking about this at the beginning of the answer :)
After that, i found a much better solution. Just creating a new section.liquid file and placing it in "collection.liquid" with an "if" statement solved my problem.

{% if collection.handle == 'less-is-more' %}
       {% section 'custom-featured-products-LESSisMORE' %}

{% endif %}

But in any way, i'm grateful for your interest. Thank you very much Dave.

A: It looks like there's nothing defining the collection variable anywhere.
I would suggest changing the beginning of your code snippet from:
{% paginate collections[settings.frontpage_collection].products by 20 %}

To:
{% assign collection = collections[settings.frontpage_collection] %}
{% paginate collection.products by 20 %}

There is an implicit collections variable whenever you're on a page that includes /collections/[something] in the URL, but when you're on a URL that's /page/[something], you have an implicit page variable in Liquid instead.

*

*Note: if the collection set in your theme's value for settings.frontpage_collection isn't the one you want, you can possibly:
a. Change the value using the 'Customize' link beside your theme (most easily found on the /admin/themes page), useful if you're not going to use that setting for anything else;
b. Hard-code a collection handle, eg: collections['i-am-sure-this-will-never-change'], but hard-coded strings are ugly and should generally be avoided;
c. Create your own theme setting by adding an entry to config/settings_schema.json - see https://help.shopify.com/en/themes/development/theme-editor/settings-schema if you're still getting up to speed with custom theme settings; or
d. If all your content is in a section, you can use section settings (similar to theme settings) to make a variable that's tied specifically to just that block of code.
If you need to make these special pages for multiple collections, and each of these pages is largely reusing the same code, you can make your life easier by moving the common code to a snippet and passing variables to it from your page template.  To do so:

*

*Create a file in the 'snippets' folder of your theme.  (For this example, let's say the file is called collection-in-page.liquid.  We will be passing a collection into this snippet, so you can remove the assign statement.

*In your page-specific template, figure out what the collection handle is going to be
a. This might be hard-coded, or it might be something you could look up by using metafields or tags on the page.  Examples:
{% assign collection_handle = 'hardcoded-handle' %}, {% assign collection_handle = page.metafields.related_items.collection %}

*In your page template, include the snippet you created. I find it helps to explicitly pass any variables I want to use, like so:
{% include 'collection-in-page', collection: collections[collection_handle] %}
Hope this helps!


text:
Q: Spring: Configure PropertyPlaceHolder when Property File outside Jar File I have a SPRING 2.5.6 based project and my properties file is outside executable Jar file like
./
 |---MyApplication.Jar
 |---MyApplication.properties

I don't know how to configure PropertyPlaceholderConfigurer so that it can pick the file outise of JAR file or any other way by which spring can know the location of properties file. In other words How to put Jar root path in class-path because spring can automatically pick the properties file from class-path.
I have read the following Questions but it did not exactly tell how to configure PropertyPlaceholderConfigurer.
Read properties file outside JAR file
Add properties file to build path of runnable jar
java -jar -cp . ./main.jar
I know this way of adding root path into class-path but my client do not want to run jar by command line or batch file. So is there a way to configure Spring somehow?
I think of possible solution is to make JAVA base configuration alongside xml base configuration.

A: java -jar -cp . ./main.jar

Change run command.

A: Solution- To get the directory where jar is located, spel can be used.
The following should get you going.
  <context:property-placeholder location="file:///#{T(java.lang.Object. getClass().getProtectionDomain().getCodeSource().getLocation())}/ application.properties"/>

A: You can use Maven or Gradle to manage your project, he can help you automatically add dependencies, you do not need to manually import Jar package.


text:
Q: Metrizibality of an uncountable product of the real line Below is a question from Topology, James Munkres. Following that is my attempt at a solution, which I am not sure is correct and would appreciate if somebody could point out what (if anything) is wrong with it.
$\textbf{Question:}$
Show that the product of an uncountably many copies of the real line is not metrizable.
$\textbf{Attempted Solution:}$
Let $X$ denote the space $\prod_{\alpha\in J} \mathbb{R}_{\alpha}$. In order to show that $X$ is not metrizable, it suffices to show that $X$ is not first-countable.
Let $X$ be first-countable. Then given a point $x=(x_{j})_{j\in J}$ in $X$, there exists a countable collection $\{U_{n}\}_{n\in N}$ of open neighbourhoods of $x$ such that every open set containing $x$ contains atleast one of the $U_{j}$. Let $V_{j}$ denote the basis element about $x$ contained in $U_{j}$. Then $V_{j}$ is of the form $\pi^{-1}_{\alpha_{1_{j}}}(W_{\alpha_{1_{j}}})\cap \pi^{-1}_{\alpha_{2_{j}}}(W_{\alpha_{2_{j}}})\cap \dots\pi^{-1}_{\alpha_{n_{j}}}(W_{\alpha_{n_{j}}})$. Let $I$ be the subset of $J$ consisting of the indices $\alpha_{i_{j}}$ for all $j\in \mathbb{N}$ and $1<i<n$. Then $I$ is a countable union of finite sets, so is countable and therefore $J-I$ is nonempty.
For some $\gamma\in J-I$ and some open neighbourhood $V_{\gamma}\subsetneq X_{\gamma}$ containing $\pi_{\gamma}(x)$, let $\pi^{-1}_{\gamma}(V_{\gamma})$ be an open set containing $x$. Then $\pi^{-1}_{\gamma}(V_{\gamma})$ must contain an open set of the form $U_{k}$, which in turn contains the open set $V_{k}$. This means that $V_{k}\subset \pi^{-1}_{\gamma}(V_{\gamma}) $, so that after applying $\pi_{\gamma}$ on both sides we get $X_{\gamma}\subset V_{\gamma}$, contradicting the fact that $V_{\gamma}$ is a proper subet of $X_{\gamma}$.


text:
Q: Holomorphic function in a fixed domain. Can I conclude or prove the following statement?
For every holomoprhic function $f(z)$ and a fixed domain $D$, if
$$\int_{\partial D}G(z,\overline{z})f(z)dz=0$$
then $G(z,\overline{z})$ is either zero or holomorphic in $D$.

A: It is incorrect. For example, let $D=\{z\in\mathbb{C}:|z|<1\}$ and let $G(z,\bar{z})=z\bar{z}=|z|^2$.


text:
Q: Remove empty namespace declaration in elements I got a XML which I tranform into another, but after the translation I got some elements that have an empty namespace declaration (xmlns="") which I want to remove.
Secondly I also want to have the xmlns:xsi declared in the InterChangeHead element.
INPUT XML
<?xml version="1.0" encoding="UTF-8"?>
<PostenInterchange type="tag">
    <heInterchangeType>PostenInterchange</heInterchangeType>
    <heVersion>1.4-rev3</heVersion>
    <heTestindicator>1</heTestindicator>
    <InterChangeHead type="tag">
        <heVersion>1</heVersion>
        <heSenderid>SENDID</heSenderid>
        <heRecipientid>RECIPID</heRecipientid>
        <heXmlnsxsi>"http://www.w3.org/2001/XMLSchema-instance"</heXmlnsxsi>
        <heXmlns>"posten.xsd"</heXmlns>
        <Shipment type="tag">
            <heShipmenttype>IMP</heShipmenttype>
            <Shipper type="tag">
                <name>Shipper</name>
            </Shipper>
            <Consignee type="tag">
                <name>Consignee</name>
            </Consignee>
            <GoodsData type="tag">
                <heSequencenumber>2</heSequencenumber>
                <GrossWeight>0.000</GrossWeight>
                <NetWeight>0.660</NetWeight>
            </GoodsData>
        </Shipment>
    </InterChangeHead>
</PostenInterchange>

CURRENT XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" exclude-result-prefixes="xs fn">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Identity template -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- Copy local names -->
    <xsl:template match="*">
        <xsl:element name="{name()}">
            <xsl:apply-templates select="@*|node()" />
        </xsl:element>
    </xsl:template>

    <!-- Rename elements beginning with "he" to elements without the "he" -->
    <xsl:template match="node()">
        <xsl:choose>
            <xsl:when test="substring(local-name(), 1, 2) = 'he'">
                <xsl:element name="{substring(local-name(), 3)}">
                    <xsl:apply-templates select="@*|node()" />
                </xsl:element>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates select="@*|node()" />
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <!-- Correct InterChangeHead element -->
    <xsl:template match="InterChangeHead">
        <xsl:element name="InterChangeHead" namespace="posten.xsd">
            <!-- Copy childs -->
            <xsl:apply-templates select="child::node()" />
        </xsl:element>
    </xsl:template>

    <!-- Remove type attribute -->
    <xsl:template match="@type"/>

    <!-- Remove unnecessary elements -->
    <xsl:template match="heXmlnsxsi" />
    <xsl:template match="heXmlns" />
</xsl:stylesheet>

CURRENT OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<PostenInterchange>
    <InterchangeType>PostenInterchange</InterchangeType>
    <Version>1.4-rev3</Version>
    <Testindicator>1</Testindicator>
    <InterChangeHead xmlns="posten.xsd">
        <Version xmlns="">1</Version>
        <Senderid xmlns="">SENDID</Senderid>
        <Recipientid xmlns="">RECIPID</Recipientid>
        <Shipment xmlns="">
            <Shipmenttype>IMP</Shipmenttype>
            <Shipper>
                <name>Shipper</name>
            </Shipper>
            <Consignee>
                <name>Consignee</name>
            </Consignee>
            <GoodsData>
                <Sequencenumber>2</Sequencenumber>
                <GrossWeight>0.000</GrossWeight>
                <NetWeight>0.660</NetWeight>
            </GoodsData>
        </Shipment>
    </InterChangeHead>
</PostenInterchange>

DESIRED OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<PostenInterchange>
    <InterchangeType>PostenInterchange</InterchangeType>
    <Version>1.4-rev3</Version>
    <Testindicator>1</Testindicator>
    <InterChangeHead xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="posten.xsd" >
        <Version>1</Version>
        <Senderid>SENDID</Senderid>
        <Recipientid>RECIPID</Recipientid>
        <Shipment>
            <Shipmenttype>IMP</Shipmenttype>
            <Shipper>
                <name>Shipper</name>
            </Shipper>
            <Consignee>
                <name>Consignee</name>
            </Consignee>
            <GoodsData>
                <Sequencenumber>2</Sequencenumber>
                <GrossWeight>0.000</GrossWeight>
                <NetWeight>0.660</NetWeight>
            </GoodsData>
        </Shipment>
    </InterChangeHead>
</PostenInterchange>

Can anyone help me out with the last bit? I added the next template because I thought this will remove the empty namespace declaration:
<!-- Copy local names -->
<xsl:template match="*">
    <xsl:element name="{name()}">
        <xsl:apply-templates select="@*|node()" />
    </xsl:element>
</xsl:template>

A: Remember that an xmlns="..." declaration sets the default namespace for the element to which it is attached and all its descendants unless countermanded by another xmlns="..." further down the tree.  Therefore in your desired output all the descendant elements under <InterChangeHead xmlns="posten.xsd" > are also in the posten.xsd namespace, and your templates need to reflect this.  Since you're using XSLT 2.0 you can use conditionals as part of the XPath expressions to do this easily:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Copy elements, fixing up names and namespaces as required -->
    <xsl:template match="*">
        <xsl:element name="{if(substring(local-name(), 1, 2) = 'he')
                            then substring(local-name(), 3) else local-name()}"
                     namespace="{if(ancestor-or-self::InterChangeHead)
                                 then 'posten.xsd' else ''}">
            <xsl:apply-templates select="@*|node()" />
        </xsl:element>
    </xsl:template>

    <!-- specific template for InterChangeHead to add the (unused) xsi
         namespace declaration -->
    <xsl:template match="InterChangeHead">
      <InterChangeHead xmlns="posten.xsd"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <xsl:apply-templates select="@*|node()" />
      </InterChangeHead>
    </xsl:template>

    <xsl:template match="@* | text()">
      <xsl:copy-of select="." />
    </xsl:template>

    <!-- Remove type attribute -->
    <xsl:template match="@type"/>

    <!-- Remove unnecessary elements -->
    <xsl:template match="heXmlnsxsi" />
    <xsl:template match="heXmlns" />
</xsl:stylesheet>

I have added a specific template to declare the xsi namespace on InterChangeHead, though I'm not sure why it's necessary to include that declaration as it isn't used anywhere in the output XML document.  If it turns out not to be necessary you can simply remove the <xsl:template match="InterChangeHead"> altogether, as the template matching * will also handle InterChangeHead, setting the namespace correctly.

A: You need to change the namespace for each element node, so change the template
<!-- Correct InterChangeHead element -->
<xsl:template match="InterChangeHead">
    <xsl:element name="InterChangeHead" namespace="posten.xsd">
        <!-- Copy childs -->
        <xsl:apply-templates select="child::node()" />
    </xsl:element>
</xsl:template>

to
<!-- Correct InterChangeHead element and descendants -->
<xsl:template match="InterChangeHead | InterChangeHead//*">
    <xsl:element name="{local-name()}" namespace="posten.xsd">
        <!-- Copy childs -->
        <xsl:apply-templates select="@* | node()" />
    </xsl:element>
</xsl:template>

Here is a complete stylesheet that simplifies the code:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" exclude-result-prefixes="xs fn">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <!-- Identity template -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- Correct InterChangeHead element -->
    <xsl:template match="InterChangeHead | InterChangeHead//*">
        <xsl:element name="{local-name()}" namespace="posten.xsd">
            <!-- Copy childs -->
            <xsl:apply-templates select="@* | node()" />
        </xsl:element>
    </xsl:template>

    <!-- Rename elements beginning with "he" to elements without the "he" -->
    <xsl:template match="InterChangeHead//*[substring(local-name(), 1, 2) = 'he']" priority="5">
                <xsl:element name="{substring(local-name(), 3)}" namespace="posten.xsd">
                    <xsl:apply-templates select="@*|node()" />
                </xsl:element>
    </xsl:template>

    <!-- Remove type attribute -->
    <xsl:template match="@type"/>

    <!-- Remove unnecessary elements -->
    <xsl:template match="heXmlnsxsi" priority="6"/>
    <xsl:template match="heXmlns" priority="6"/>
</xsl:stylesheet>


text:
Q: count word appear alphabetically In text processing tasks, one of the first things to do is figure out how often each word appears in a given document. In this task, you will be completing a function that returns the unique word frequencies of a tokenized word document.
write code to complete the count_frequencies function. The input argument (arr), is a list of strings, representing a tokenized word document. An example input would look like this:
['the', 'dog', 'got', 'the', 'bone']
Your count_frequencies function should return a list of tuples, where the first element in the tuple is a unique word from arr and the second element in the tuple is the frequency with which it appears in arr. The returned list should be sorted in alphabetical order by the first element of each tuple. For the above example, the correct output would be the following list of tuples:
**[('bone', 1), ('dog', 1), ('got', 1), ('the', 2)]**

A couple more examples (with solutions) are shown below:
**Input: ['we', 'came', 'we', 'saw', 'we', 'conquered']**
**Solution: [('came', 1), ('conquered', 1), ('saw', 1), ('we', 3)]**
**Input: ['a', 'square', 'is', 'a', 'rectangle']**
**Solution: [('a', 2), ('is', 1), ('rectangle', 1), ('square', 1)]**

You can write your own test cases in the input text box.
In this case, your test case should be space-separated words, representing an input list for the count_frequencies function.

A: You can use this simple function using collections.Counter:
from collections import Counter

def count_words(list_of_words):
    return sorted(Counter(list_of_words).items())

>>> count_words(['we', 'came', 'we', 'saw', 'we', 'conquered'])

# [('came', 1), ('conquered', 1), ('saw', 1), ('we', 3)]


text:
Q: vim doesn't react to register access command `"` - how to fix it? Whenever I type " in normal mode in vim it never appears - the editor (I tried both on Ubuntu 16.04 and macOS 10.13 with terminal vim as well as Spacemacs with evil) does not react - double quote does not appear in the command line, nor editor pastes anything when I use, e.g. "+p. I verified with :reg that I have all default registers and they are filled with data.
What can be the source of the problem and how to fix it?
I very often come with a case where "0p or "*p would fit perfectly and have to deal with them manually.


text:
Q: Can you add CSS to a Dynamic editable area based on an input label value I am using a CMS system that allows you to edit multiple content areas inside the main space (like all of them). What I am trying to do is for each editable content area I want to show a certain background color. The Main-Content = white and the right rail would be red when editing them.
Since everything is generated on the fly once the edit button is clicked, and everything between the two are are the same besides a input value, I am trying to say if the input value = main content show white if the value is right rail show red on the editor's body tag #tinymce.mceContentBody. I can only use CSS and I can not add to the HTML (so no adding IDs and classes).
Below is a cut out of some of the code generated. If you scroll through it, you will see the line <input id="label" type="hidden" value="Main-Content" name="label"></input>. That is the only thing that is different among the two editable areas. One is Main-Content and the other is Right-Right(not shown below). Can this be done? Can I drill down - The only thing I can think of is using that label value, but I am not sure how to code that and if it possible to say it is the parent of the editable area. I tried doing something like this - input[value="Main-Content"] #tinymce.mceContentBody {background-color:#FFF;} This failed and I am sure I am coding it incorrectly, but I think there might be something like this that will work.
NOTE this is the code and can not be changed at all -
<form id="wysiwyg_form" method="post" action="/servlet/OX/iesave">
<input id="site" type="hidden" value="test-email" name="site"></input>
<input id="path" type="hidden" value="/training/eo/Erick-Test_delete.aspx" name="path"></input>
<input id="newPath" type="hidden" value="/training/eo/Erick-Test_delete.aspx" name="newPath"></input>
<input id="label" type="hidden" value="Main-Content" name="label"></input>
<input id="dest" type="hidden" value="preview" name="dest"></input>
<textarea id="text" rows="1" cols="1" name="text" style="display: none;" aria-hidden="true"></textarea>

                   #document
                      <!DOCTYPE >

This is where the content gets displayed - I want this BG to be white and be red when the label above is right rail

A: The way to accomplish this is to use the 'wysiwyg-class' attribute in the either the editor tag inside of your editable regions. That class will be added to the  node of the TinyMCE editor and then one css can modify the margins, width, height position of the body based on the class
body.main_content { }
body.left_column { }


text:
Q: dplyr and ggplot piping is not working as expected I find no solution for these two following issues:
First I try this:
library(tidyverse)
gg <- mtcars %>%
      mutate(group=ifelse(gear==3,1,2)) %>%
      ggplot(aes(x=carb, y=drat)) + geom_point(shape=group)

Error in layer(data = data, mapping = mapping, stat = stat, geom =
GeomPoint,:object 'group' not found

which is obviously not working. But using something like this .$group is also not successfull. Of note, I have to specifiy the shape outside from aes()
The second problem is this. I'm not able to call a saved ggplot (gg) within a pipe.
gg <- mtcars %>%
      mutate(group=ifelse(gear==3,1,2)) %>%
      ggplot(aes(x=carb, y=drat)) + geom_point()

    mtcars %>%
        filter(vs == 0) %>%
        gg + geom_point(aes(x=carb, y=drat), size = 4)

Error in gg(.) : could not find function "gg"

Thanks for your help!
Edit
After a long time I found a solution here. One has to set the complete ggplot term in {}.
mtcars %>%
   mutate(group=ifelse(gear==3,1,2)) %>% {
   ggplot(.,aes(carb,drat)) +
       geom_point(shape=.$group)}

A: If you wrap your shape definition in aes() you can get the desired behavior.  To use shape outside of aes() you can pass it a single value (ie shape=1).  Also note that group is converted to a discrete var, geom_point throws an error when you pass a continuous var to shape.
library(tidyverse)

gg <- mtcars %>%
  mutate(group=ifelse(gear==3,1,2)) %>%
  ggplot(aes(x=carb, y=drat)) +
  geom_point(aes(shape=as.factor(group)))

gg

Second, the %>% operator, when called as lhs %>% rhs, assumes that the rhs is a function.  So as the error shows, you are calling gg as a function.  Calling a plot as a function on a dataframe (ie gg(mtcars)) isnt a valid operation.
See @docendo discimus comment on the question for how to use {} to accomplish adding a layer to an existing ggplot object from a magrittr pipeline.


text:
Q: Running js on the php buffer content i would like to do some JQuery stuffs on the content of the php buffer before sending the content of the buffer. I have this code:
<?php ob_start() ?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Titre</title>
        <link rel="stylesheet/ucss" href="style.css" />

    </head>
    <body>
           //some html and php code
    </body>
</html>
<?php $bufferContent = ob_get_clean(); ?>

Also I'd like to do some DOM stuff with JQuery on the content of the $bufferContent var.
I already know the V8JS PECL extension but i don't know how to use it with JQuery and DOM function.
Thanks for help and excuse my english.

A: Remember the basics - PHP runs on server and JS (jQuery too) runs in the user's browser. You can not run jQuery on the server side (only if you start browser there :)), but it is useless)

A: You can use PHPQuery to run most JQuery commands.
However to run commands that use certain elements like document / window / etc you will need not only a JavaScript engine (v8js) but a DOM to work with the engine. For that there is Env-JS and Node-JS.
You will have to load that into v8 before loading jquery-min.js.


text:
Q: Manupulating "html a tag redirects" to nginx server's domain ( + proper icon loading ) My Nginx server is configured with a domain nginxsite.in
I proxied its subpath '/home'  to another website 'mywebsite.com/home'
server{
                listen 80;
                listen [::]:80;

                server_name nginxsite.in;

                location /home {
                proxy_pass https://myWebsite.com/home/;
                }

}

in myWebsite html there are references like <a href="https://myWebsite.com/home/blog"..

*

*How can I proxy them to nginxsite.in/home/blog whenever someone clicks on the "a tag" link?

*It is also not loading icons from mywebsite.com.Any solutions?
(*the sitenames are madeup)


text:
Q: How do we plot a list of HoloViews plots? I have a list of heatmaps
[:HeatMap   [column,row]   (analyte_value),
 :HeatMap   [column,row]   (analyte_value),
 :HeatMap   [column,row]   (analyte_value),
 :HeatMap   [column,row]   (analyte_value)]

Is there a command to render them all in the notebook, rather than:
(heatmaps[0] + heatmaps[1] + heatmaps[2] + heatmaps[3]).cols(1)
?

A: The + and * operators are simply convenient ways of creating Layout and Overlay container objects respectively. To construct a Layout or Overlay from a list you can simply use the constructor directly, e.g. in your case that would simply be:
hv.Layout(heatmaps).cols(1)


text:
Q: Como abrir uma GUI construída no Eclipse pelo Netbeans? Estou com um código usando JFrame, porém quando vou abri-lo pelo Netbeans só consigo mudar o layout pelo código. Como faço para usar o código e editar o layout pelo construtor de GUI do Swing.

A: No Netbeans para ele ser reconhecido como um formulário e funcionar corretamente há vários requisitos. Vou começar pelo mais simples (mas menos importante). Primeiramente, o construtor deverá ter a seguinte forma:
public MinhaTela() {
    initComponents();
}

Você até pode alterar o construtor como quiser, mas é importante manter a chamada ao initComponents(). Como é o formato do initComponents()? Tipicamente é assim:
/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
    // ... Um monte de código ...
}// </editor-fold>

// Mais um monte de código...

// Variables declaration - do not modify
// ... Algumas variáveis aqui ...
// End of variables declaration

Estas duas áreas acima (o código do initComponents() e as variáveis declaradas no final da classe) serão coloridas de cinza pelo Netbeans. Ele normalmente não te deixará alterá-las diretamente pelo código. Se você abrir em um editor externo (exemplo, Notepad++) você verá mais códigos que o Netbeans nunca mostra:
/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
    // ... Um monte de código ...
}// </editor-fold>//GEN-END:initComponents

// Mais um monte de código...

// Variables declaration - do not modify//GEN-BEGIN:variables
// ... Algumas variáveis aqui ...
// End of variables declaration//GEN-END:variables

Vê esses //GEN-BEGIN:initComponents, //GEN-END:initComponents, //GEN-BEGIN:variables e //GEN-END:variables? Eles são delimitadores que o Netbeans usa para proteger o código contra modificações. Se você removê-los com uma ferramenta externa o Netbeans permitirá você a mexer diretamente neste código.
Tal como o comentário do initComponents() diz, o corpo deste método é gerado e regerado automaticamente (bem como as variáveis no final) sempre que o construtor de GUI decidir alterá-lo. As configurações de formulário do editor estão dentro de um arquivo com a extensão .form na mesma pasta da sua classe. Assim, se o seu arquivo que contém a sua subclasse de JFrame se chama MinhaTela.java, deverá haver um arquivo MinhaTela.form na mesma pasta.
É neste arquivo .form que os detalhes do editor de tela estão armazenados (em um formato XML). Então para que o Netbeans reconheça a sua tela no editor dele, este arquivo deverá estar presente.
Mas e se você não tiver este arquivo .form? Se você não tiver este arquivo, o Netbeans não irá reconhecer o seu JFrame como editável pelo construtor de GUI. Neste caso, se você não quiser simplesmente esquecer a edição pelo construtor de GUI e ficar apenas no código, você poderá criar um arquivo .form vazio para começar a recriar o layout todo.
Se você for recriar o layout todo, convém fazer um backup uma vez que o Netbeans irá alterar automaticamente a sua classe a partir das informações contidas no arquivo .form e também certifique-se que o initComponents() e as variáveis do final da classe estão presentes seguindo o modelo mostrado acima (possivelmente incluindo os comentários GEN-BEGIN e GEN-END). Eis um arquivo .form vazio para começar:
<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.9" type="org.netbeans.modules.form.forminfo.JFrameFormInfo">
  <Properties>
    <Property name="defaultCloseOperation" type="int" value="3"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
    <SyntheticProperty name="generateCenter" type="boolean" value="false"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <EmptySpace min="0" pref="400" max="32767" attributes="0"/>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <EmptySpace min="0" pref="300" max="32767" attributes="0"/>
      </Group>
    </DimensionLayout>
  </Layout>
</Form>

Além disso, você pode aprender qual é a estrutura do arquivo .form a medida que você manipula o construtor de GUI do Netbeans ao analisar como o XML é alterado e como estas alterações se refletem no código Java, mas não vou entrar em muitos detalhes nisso pois já está um tanto fora do propósito da pergunta.


text:
Q: Como atribuir o Name de um componente, sendo que ele não existe no contexto atual Estou com um form para cadastro de clientes e dentro desse form existe um RadioButton que pergunta se esse cliente necessita de envio de faturas, se a reposta por igual a SIM surgem dois componentes, um TextBox e um DateTimePicker.
if (rdsim.Checked == true)
{
    metroPanel1.Controls.AddRange(new Control[]
    {
       new MetroFramework.Controls.MetroTextBox
       {
           Name = "txtconta", //aqui adiciono o nome do componente
           Location = new Point(TextBoxX, 15),
           Size = new Size(185, 30)
       },
       new MetroFramework.Controls.MetroDateTime
       {
           Name = "dtpvencimento", //aqui adiciono o nome do componente
           Format = DateTimePickerFormat.Custom,
           Location = new Point(DateTimeX, 13),
           Size = new Size(124,33)
       },
   });
}

Deste modo, quando o usuário clicar no botão Cadastrar devo passar esses dados para o banco, estou fazendo dessa forma:
Contas contas = new Contas();
contas.Nroconta = txtconta.Text;
contas.Vencimento = dtpvencimento.Text;

Mas me retorna o erro de que esses names não existem no contexto atual, como posso resolver isso? Há outra forma de atribuir um componente, sem ser pelo seu Name?

A: Ao fazer Name = "dtpvencimento", você apenas está informando um nome para o controle e não criando uma variável para ele. Portanto, não faz sentido você tentar acessar uma variável...
Existem diversas formas de resolver isso, uma delas é criar uma variável e atualizá-la no momento da criação do componente.
public class Form1
{
    private MetroTextBox txtconta;
    private MetroDateTime dtpvencimento;

    ...

    if (rdsim.Checked == true)
    {
        txtConta = new MetroFramework.Controls.MetroTextBox
        {
            Name = "txtconta", //aqui adiciono o nome do componente
            Location = new Point(TextBoxX, 15),
            Size = new Size(185, 30)
        };

        dtpvencimento = new { }; // ...

        metroPanel1.Controls.AddRange(new Control[]
        {
           txtConta,
           dtpvencimento
       });
    }
}

Dessa forma, será possível acessar os elementos como está fazendo atualmente.
Você pode também deixar os componentes criados em tempo de design e apenas mudar a visibilidade dos mesmos. Se todos os componentes deste form estiverem sendo criados em tempo de design esta pode ser uma solução melhor que a anterior.
Se você quiser manter o código de criação dos componentes exatamente como está agora, poderá encontrar os controles pelo seu nome, usando o método Find().
Contas contas = new Contas();
var txtconta = Controls.Find("txtconta");
var dtpvencimento = Controls.Find("dtpvencimento");

contas.Nroconta = txtconta.Text;
contas.Vencimento = dtpvencimento.Text;

De forma análoga à solução acima, é possível usar o indexador de ControlCollection.
Contas contas = new Contas();
var txtconta = Controls["txtconta"];
var dtpvencimento = Controls["dtpvencimento"];

contas.Nroconta = txtconta.Text;
contas.Vencimento = dtpvencimento.Text;

A: Eu criaria um metodo para poder submeter os parametros de controle para criação do componente.
Private Sub EnviarFormaPgto(ByRef ucUserControl As UserControl)

            Me.grpDados.Controls.Add(ucUserControl)// grpDados é um GroupBox

            ucUserControl.Location = New System.Drawing.Point(6, 7)
            ucUserControl.Name = "UcForma"
            ucUserControl.Size = New System.Drawing.Size(465, 85)
            ucUserControl.TabIndex = 2

End Sub


text:
Q: Adding a commit from a fork to a topic branch If userA and I both fork a project from userB. Then userA creates a commit in their master fork and has not decided to make a pull request to userB master. How do I add their commit (userA) to my dev branch (not my master) in my fork?

A: You can actually do this with one command. For example:
git pull https://github.com/userA/repo.git master

This will merge userA's master branch into your current branch (use git checkout dev on your own repository first).
If you find yourself doing this frequently, you can add a remote to your local repository that allows you to refer to userA's repository with a single name. For example:
git remote add userA https://github.com/userA/repo.git
git pull userA master


text: Q: Puedo usar el archivo .env en React si use javascrip nativo? mi pregunta radica porque tengo un proyecto con react con javascrip nativo nada de nodejs ,Puedo usar el archivo .env en React si use javascrip nativo?


text:
Q: How can I solve the "Cannot save file into a non-existent directory: '{parent}'" error? I want to save the 'df' to 'dataset' file.
There is my code
The code file name is 'practice.py'
import pandas as pd

df = pd.DataFrame({
    "x1": [100000, 200000, 300000],
    "x2": [400000, 500000, 600000],
    "x3": [700000, 800000, 900000]},

     index=[2019, 2021, 2020]

)
df.index.name = 'year' # set the index name

df.to_csv('dataset/covid_dataset.csv', encoding='utf-8') # save to file

I think I set the file path well, but I don't know where the mistake is.
And this is my file structure :
enter image description here
Here is the error message :
(covid_project) C:\self_project\covid_project>C:/self_project/covid_project/Scripts/python.exe c:/self_project/covid_project/covid19_project/practice.py
Traceback (most recent call last):
  File "c:\self_project\covid_project\covid19_project\practice.py", line 13, in <module>
    df.to_csv('dataset/covid_dataset.csv', encoding='utf-8')
  File "C:\self_project\covid_project\lib\site-packages\pandas\core\generic.py", line 3563, in to_csv
    return DataFrameRenderer(formatter).to_csv(
  File "C:\self_project\covid_project\lib\site-packages\pandas\io\formats\format.py", line 1180, in to_csv
    csv_formatter.save()
  File "C:\self_project\covid_project\lib\site-packages\pandas\io\formats\csvs.py", line 241, in save
    with get_handle(
  File "C:\self_project\covid_project\lib\site-packages\pandas\io\common.py", line 697, in get_handle
    check_parent_directory(str(handle))
  File "C:\self_project\covid_project\lib\site-packages\pandas\io\common.py", line 571, in check_parent_directory
    raise OSError(fr"Cannot save file into a non-existent directory: '{parent}'")
OSError: Cannot save file into a non-existent directory: 'dataset'

Here's the desired result:

*

*I want to save 'df' as 'covid_dataset.csv' file name in 'dataset' file.

A: It works on my machine
windows 11
python 3.8
try './dataset/covid_dataset.csv'


text:
Q: Metric Spaces, determining whether a point is in the interior, boundary, or interior of the complement. I'm really stuck on this Real Analysis problem, if anyone would mind helping me.
Let $(X,d)$ be a metric space, and let $A$ be a non-empty subset of $X$.
How do you show whether any point $x \in X$ is in the interior, interior of the complement, or boundary of $A$, if the only information you have is $d_A(x) = \inf d(x,a)$ and $d_{A^c}(x)$.
I have been trying to make some arguments using strictly distances but this hasn't been working out. How would you do this?
Thanks.

A: Hint: If $d_A(x)>0$, then $x$ is in the exterior of $A$ (interior of $A^c$). Why?
And, what if $d_A(x)=d_{A^c}(x)=0$?

A: Hint: For any $S\subset X$
$$
x\in\mathrm{cl}(S)\Longleftrightarrow d_S(x)=0
$$
$$
X=\mathrm{int}(S)\cup\mathrm{int}(S^c)\cup\partial S
$$

A: $\newcommand{\cl}{\operatorname{cl}}\newcommand{\int}{\operatorname{int}}\newcommand{\bdry}{\operatorname{bdry}}$I gather from your comment to Berci that you have the basic idea but are having a hard time expressing it. It might help to start by proving the observation that for any non-empty $S\subseteq X$ and any $x\in X$, $d_S(x)=0$ if and only if $x\in\cl S$. Then you immediately get that
$$d_A(x)=0=d_{X\setminus A}(x)\quad\text{iff}\quad x\in\cl A\cap\cl(X\setminus A)=\bdry A\;,$$
and you should find it even easier to write down and verify the conditions on $d_A(x)$ and $d_{X\setminus A}(x)$ corresponding to $x\in\int A$ and $x\in\int(X\setminus A)$.


text:
Q: D3 JS - Force Graph - Doesn't restart layout after removing Node UPDATE :
The graph now behaves correctly after removal of node(s).
However, when I conditionally remove non-sequential nodes (e.g. 4,5,10) the graph does not display the correct nodes.
Please look at the updated click handler below (lots of debugging).
I'm trying to remove all nodes with the "d.source" value == "news24", which are all the large blue circles.
Although the array is correct after "removal", the incorrect nodes are being displayed.
I suspect its something to do with node.exit(), but I'm not sure.
Full updated code : http://www.darkness.co.za/code/graph_test_2.zip
$('#btnRemove').click(function(e) {
// These are the large blue circles
var sourceToHide = "news24";

// DEBUG - Before Removal
for (i=0; i < nodes.length; i++) {
  console.log("node_object[" + i + "].source = " + nodes[i].source);
  console.log("-----------------------------------");
}

// Hold indices of items to remove
var itemsToRemove = [];

// Find items with the source to remove
for (i=0; i < nodes.length; i++) {
    var nodeSource = nodes[i].source;

    console.log("Node source = " + nodeSource + " sourceToHide = " + sourceToHide);

    if (nodeSource == sourceToHide) {
        itemsToRemove.push(i);
    }
}

// Reverse removal array - makes splice work as expected
itemsToRemove.reverse();

// Remove items
for (i=0; i < itemsToRemove.length; i++) {
    nodes.splice(itemsToRemove[i], 1);
}

// DEBUG - After Removal
for (i=0; i < nodes.length; i++) {
    console.log("node_object[" + i + "].source = " + nodes[i].source);
    console.log("-----------------------------------");
}

// Rebind the nodes to the array
node = svg.selectAll("circle")
.data(nodes)

// Remove the exit'ed node
node.exit().remove();

// Tell the layout that this is the new set of nodes
// so that it doesn't include the old one in the computation
force
.nodes(nodes)

// That's it. No need to restart the force layout

});
I've searched a lot, and tried many examples in isolation, but could not solve this issue for my particular setup and data.
Code :
Apologies, I had issues setting it up on JSFiddle (external files etc.) so you can get the full code here :
http://darkness.co.za/code/graph_test.zip
What I want to achieve:
(for this test) I want to remove a single node, and then redraw/restart the graph
What I've tried:
I've attempted to remove the last element from the Array of nodes, and then redraw the graph (circles and lines) and then call force.start()
The problem :
The node does disappear as desired, but the entire graph stops responding.
How do I correctly remove a node and then successfully restart the graph with it normal Drag behaviour ?
Note : I do at the end of the "drawGraph()" function call "force.start()"
Thanks

A: You don't need to "restart" the graph in this case. All you should have to do is remove the node from the DOM and tell the force layout that there's a new set of nodes (same set as before MINUS the removed one). So, in the button's click handler:
// Button Listeners
$('#btnRemove').click(function(e) {
  // Remove the node from the array
  nodes.splice((nodes.length - 1), 1);

  // Rebind the nodes to the array
  node = svg.selectAll(".node")
    .data(nodes)

  // Remove the exit'ed node
  node.exit().remove();

  // Tell the layout that this is the new set of nodes
  // so that it doesn't include the old one in the computation
  force
    .nodes(nodes)

  // That's it. No need to restart the force layout
});

This doesn't address the removal of the node's link line, but you can follow the same approach to do that.


text:
Q: Get the average color inside a contour with Open CV So I decided to get started learning Open CV and Python together!
My first project is to detect moving objects on a relatively still background and then detect their average color to sort them. There are at least 10 objects to detect and I am processing a colored video.
So far I managed to remove the background, identify the contours (optionally get the center of each contour) but now I am struggling getting the average or mean color inside of each contour. There are some topics about this kind of question but most of them are written in C. Apparently I could use cv.mean() but I can't get a working mask to feed in this function. I guess it's not so difficult but I am stuck there... Cheers!
import numpy as np
import cv2

video_path = 'test.h264'

cap = cv2.VideoCapture(video_path)
fgbg = cv2.createBackgroundSubtractorMOG2()

while (cap.isOpened):

    ret, frame = cap.read()
    if ret==True:
        fgmask = fgbg.apply(frame)
        (contours, hierarchy) = cv2.findContours(fgmask, cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)

        for c in contours:
            if cv2.contourArea(c) > 2000:
                cv2.drawContours(frame, c, -1, (255,0,0), 3)
        cv2.imshow('foreground and background',fgmask)
        cv2.imshow('rgb',frame)

    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

A: Solution on an image
1) find contour (in this case rectangle, contour that is not rectangle is much harder to make)
2) find coordiantes of contour
3) cut the image from contour
4) sum individual channels and divide them by number of pixels in it ( or with mean function)
import numpy as np
import cv2
img = cv2.imread('my_image.jpg',1)
cp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(cp,150,255,0)
cv2.imshow('img',thresh)
cv2.waitKey(0)
im2,contours,hierarchy = cv2.findContours(thresh.astype(np.uint8), 1, 2)
cnts = contours
for cnt in cnts:
    if cv2.contourArea(cnt) >800: # filter small contours
        x,y,w,h = cv2.boundingRect(cnt) # offsets - with this you get 'mask'
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
        cv2.imshow('cutted contour',img[y:y+h,x:x+w])
        print('Average color (BGR): ',np.array(cv2.mean(img[y:y+h,x:x+w])).astype(np.uint8))
        cv2.waitKey(0)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

To remove noise, you can just take center of the contour, and take smaller rectangle to examin.
For non rectangular contour, look at cv2.fillPoly function -> Cropping non rectangular contours. But its a bit slow algorithm (but nothing limiting)
If you are interested in non rectangular contour, you will have to be careful about doing mean, because you will need mask and the mask/background is always rectangular so you will be doing mean on something you dont want

A: You can create a mask by first creating a new image with the same dimensions as your input image and pixel values set to zero.
You then draw the contour(s) onto this image with pixel value 255. The resulting image can be used as a mask.
mask = np.zeros(frame.shape, np.uint8)
cv2.drawContours(mask, c, -1, 255, -1)

mask can then be used as a parameter to cv.mean like
mean = cv.mean(frame, mask=mask)

Just one word of caution, the mean of RGB colors does not always make sense. Maybe try converting to HSV color space and solely use the H channel for detecting the color of your objects.


text:
Q: How can I create a SharePoint group using Flow? I want to use Flow to create SharePoint groups on one of my sites. From what I can tell, I should be using the "Send an HTTP request to SharePoint" action but I know next to nothing about using REST API.
The closest answer I've found is this:
How can I create a standard Sharepoint permission group using "send HTTP request to sharepoint.
which isn't really enough information for me to work this out on my own.

A: Yes, you are right. You need to use Send an HTTP request to SharePoint action in Microsoft Flow in order to create a SharePoint Group.
Try Using it as given in below image:

Output: Group with name GroupFromFlow is created.


text:
Q: How do I write simple unit test functions for attributes when creating procedural macros? I'm trying to test parsing attributes for structs as I'm beginning to write a custom derive. I would like to split testing custom derives into multiple simpler test functions rather than testing it as a whole derive system at once.
This is my proposal:
#[derive(From)]
#[from(forward)]  //this is what I wanna parse into `FromAttribute`
struct A;

#[derive(Debug, PartialEq)]
pub enum FromAttribute {
    None,
    /// Add general bounds for `From` implementation.
    Forward,
    /// Skip generate `From` impl for this variant
    Ignore,
    /// Manually choose for witch `From` should be implemented
    Types(Vec<syn::Type>),
}

impl FromAttribute {
    pub fn from_attributes(attrs: &[syn::Attribute]) -> syn::Result<FromAttribute> {
        // function I want to test
    }
}

I come up with this draft:
#[test]
fn from_attribute_test() {
    let code: HOW_TO_MAKE_IT_PARSE_STREAM = #[from(forward))] ; /// This is part I don't know how to implement
    let attributes: Vec<syn::Attribute> = syn::Attribute::parse_inner(code).unwrap();

    assert_eq!(
        FromAttribute::Forward,
        FromAttribute::from_attributes(&attributes)
    );
}

You can suggest a completely different way.


text:
Q: Call the actual association in an ActiveRecord redefined association method I have this model:
class User < ActiveRecord::Base
  belongs_to :company

  def company
    # Do something here

    # Call the actual association (that would be usually returned by calling User#company)
  end
end

I'm aware that I could use another internal name for the association but want to avoid that.
I'm pretty sure there is some kind of internal method that Rails calls when you call the plain association User#company method and I want to call it myself in my redefined User#company method here.
Thanks!

A: You can call super in your method. Or association(:company) or associations(:company) (I forgot which one). Or you can
def company_with_my_stuff
  company_without_my_stuff
end
alias_method_chain :company, :my_stuff

Also you could rename the belongs_to :original_company, :class_name => "Company", :foreign_key => "company_id" which I think is a better solution.


text:
Q: How to set a single cell only in getRange of Google Script? I am trying to make a message box appear when the condition in a specific cell is met. However, it applies to all the cells in all the sheets. What is the code for this?
function onEdit(e){
var sheet = SpreadsheetApp.getActiveSheet();
const VITALS = ss.getSheetByName("VITAL SIGNS")

var temp = sheet.getRange("C10").getValues();

if (temp >= 38 ){
Browser.msgBox('WARNING: Temperature is above normal levels')}
else
if (temp <= 36) {
Browser.msgBox('WARNING: Temperature is below normal levels')}
else
if (temp >=36) {
return
 }
}

Thank you!
I tried several other codes but no progress.


text:
Q: PHP Reference to a static variable I'm not sure if this is possible at all in PHP but this is what I try to do. I have a static variable in my class that I want to have as a reference outside the class.
class Foo {

  protected static $bar=123;

  function GetReference() {

    return self::&$bar; // I want to return a reference to the static member variable.
  }

  function Magic() {

    self::$bar = "Magic";
  }
}

$Inst = new Foo;
$Ref = $Inst->GetReference();
print $Ref; // Prints 123
$Inst->DoMagic();
print $Ref; // Prints 'Magic'

Can someone confirm if this is possible at all or another solution to achieve the same result:

*

*The variable must be static because class Foo is a base class and all derivates needs access to the same data.

*HTML needs access to the class reference data, but not to be able to set it without a setter method because the class needs to know when the variable is set.

I guess it can always be solved with globals declared outside the class and some coding disciplines as an emergency solution.
// Thanks
[EDIT]
Yes, I use PHP 5.3.2

A: The PHP documentation provides a solution: Returning References
<?php
class foo {
    protected $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42.
$obj->value = 2;
echo $myValue;


text:
Q: Can I download Minecraft on a another computer but with a different username and skin? My cousin and I would like to play minecraft pc  in a multiplayer world, just asking if I could just change the username and skin on a another computer for my cousin, or would that affect my character in the minecraft on my laptop too? ( sorry, I'm still new to this)

A: This will only work if you have two different accounts, your skin is linked to your account, not the computer. So if I change my skin on this computer, and log into Minecraft on my laptop, the skin will still be changed. One account, one skin.
If you have one account, and your cousin has one account. Then you can change the skin on your account and it would not affect your cousin's account.


text:
Q: Sticky element inside overflow element I would like to make the timeline-header sticky to the top of the page in the following example:
http://jsfiddle.net/m152usbd/1/
But because the timeline has overflow enabled, sticky stops working on timeline-header.
.timeline{
  overflow: auto;
}

.timeline-header{
  position: sticky;
  top: 0;
}

The closest I came to what I want is:
http://jsfiddle.net/ztuf4gjc/1/
But I feel this is not a good solution, because I need to adjust every other element on the page to make this work and I can foresee some side-effects happening. Also, I want only the timeline section to be scrollable in the x-axis, not the entire page.
Does anyone know how to tackle this issue?
Update
Based on @a--m answers, this might not be possible with CSS unfortunately.
Here is the js approach: http://jsfiddle.net/cvk43g1o/
If anyone knows how to do this with CSS, please let me know!

A: I think it's not possible to achieve what you ask using CSS only:

A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.

https://www.w3.org/TR/css-position-3/#sticky-pos
Since the parent timeline has a horizontal scroll, then the sticky refers to this one and loses the ability to track window as you desire. The limitation to sticky in this case is that can't track two different containers.

A: It seems to me that you could just copy the contents of .timeline-header into .timeline and it seems to work as far as I understand the question.
The reason position: sticky wouldn't work when applied to .timeline-header is because the scroll is dependent on it's containing block and since it takes up most of it's containing block you don't actually see it move before it returns to position relative. When position: sticky is applied to .timeline the containing block is much larger allowing you to see it scroll throughout the page.


text:
Q: How to handle calculated models in django? From a model called Suggestion, I need to calculate another model that is called Task.
Task objects doesn't need to store anything in the database since it is totally calculated using Suggestion fields.
An exemple would be a task of approving a suggestion using fields :

*

*approver

*state

*approving_deadline
Is their a standard way in django to handle this kind of models that doesn't need to store any information but are fully  calculated using other models ?

A: You should use a SerializerMethodField:

*

*In your Serializer, create a field for your Task like task = serializers.SerializerMethodField()

*Still, in your serializer, create a method called get_taks(self, obj). obj is your current Suggestion, from which you need to calculate your task and return it as serialized data (the Task primary key using task.pk, or a serialized Task using TaskSerializer(task).data, or whatever you prefer).

ex.:
class SuggestionSerializer(serializers.ModelSerializer):
    task = serializers.SerializerMethodField()

    class Meta:
        model = Suggestion
        fields = [
            'id', 'approver', 'state', 'approving_deadline',
            ..., 'task'
        ]

    def get_tasks(self, obj):
        # obj is a Suggestion instance
        task = my_get_task_from_suggestion_helper(obj)
        return task.id # or TaskSeriaizer(task).data

You can read more detail about SerializerMethodField on Django REST Framework docs


text:
Q: How to get a SOAP post in PHP? OK n00b here with SOAP,
Would like some clarification on how to use SOAP.
Question:
I have a Java JSP that posts a WSDL (Looks like XML format) to my PHP script, but how do I get this in the PHP script? The URL for the WSDL will be different every time.
I'm sure it's very simple but just don't see how or am I not understanding this correctly?

A: You can try something like this:

try {
  if (!($xml = file_get_contents('php://input'))) {
    throw new Exception('Could not read POST data.');
  }
} catch (Exception $e) {
  print('Did not successfully process HTTP request: '.$e->getMessage());
  exit;
}

This will read the body of the POST request to the $xml variable and print an error if there is one.

A: Do you mean that the JSP sends the WSDL in a POST request to the PHP script?
If so, have a look at the $_POST array. If you specify exactly how the JSP sends it, I can probably help you more.
Anyway, once you have the WSDL url in a variable in your PHP script, you can have at it with the SoapClient class.

A: Assuming the best scenario:
$soapClient = new SoapClient($wsdlUrl, $soapOptions);
$soapClient->callYourMethod();

But you're likely to hit a lot of brick walls when using SOAP. Here's the documentation for SoapClient.
Edit:
So, the WSDL is POST-ed. Then, you could access it either by using $HTTP_RAW_POST_DATA if the XML string was sent as the HTTP body, or by using the $_FILES superglobal if the XML string was send as a part of a multipart request.
Something like this:
$wsdl = $HTTP_RAW_POST_DATA;
$wsdlUrl = 'data:text/xml;base64,' . base64_encode($wsdl);
$soapClient = new SoapClient($wsdlUrl);

Anyway, $HTTP_RAW_POST_DATA is only available if the php.ini setting always_populate_raw_post_data is turned on. Also, if the request was multipart, this setting is ignored, $HTTP_RAW_POST_DATA is not populated but you get access to the posted parts using $_FILES. And you may, indeed, use php://input instead of $HTTP_RAW_POST_DATA.
Also, data URIs may only be used when allow_url_fopen is turned on in php.ini.


text:
Q: How to do case insensitive search using QueryBuilder in CQ? I am doing CQ search using Querybuilder on a set of 8 properties. One of them is a text box. So case insensitive search needs to be done on it. All others are drop downs.
Issue: Case sensitive search is happening on the text box.
Below mentioned in piece of code. When I include case insensitive code, the search is not happening properly.
Any pointers on this will be really helpful.
map.put("1_customcase.property", searchkey);
map.put("1_customcase.property.value", searchkey);
map.put("1_customcase.case", "no_case");
map.put("orderby", "customcase");**

map.put("2_property", propertyname);
map.put("2_property.value", value);
map.put("3_property", propertyname);
map.put("3_property.value", value);
...
...
...

Query query = builder.createQuery(PredicateGroup.create(map), session);


text:
Q: Win32 Visual Styles backwards compatibility? When I embed the Visual Styles manifest in my program like this:
// Embed visual style XML manifest
#pragma comment(linker,                           \
    "\"/manifestdependency:type='Win32'"          \
    "   name='Microsoft.Windows.Common-Controls'" \
    "   version='6.0.0.0'"                        \
    "   processorArchitecture='*'"                \
    "   publicKeyToken='6595b64144ccf1df'"        \
    "   language='*'\""                           \
)

// Link common controls library
#pragma comment(lib, "ComCtl32.lib")

Does that mean my program will only run on Windows XP? Or if visual styles are not on the computer will they just use the operating systems default style? I ask because I enabled visual styles in my program that I am developing with Visual Studio 2008 and I want to know what is the earliest version of Windows it can be run on. Should I check WINVER to see if they are running a version that supports visual styles? If so, what version number should I check for in the preprocessor. Another thing I would like to know is, without visual styles, what is the lowest version I can run my program on?

A:
Does that mean my program will only run on Windows XP? Or if visual
  styles are not on the computer will they just use the operating
  systems default style?

The latter is true and the documentation defines the exact behaviour (emphasis is mine):

If you want your application to use visual styles, you must add an
  application manifest or compiler directive that indicates that
  ComCtl32.dll version 6 should be used if it is available.

Another section in the same page describes some things you should watch out for in terms of backwards compatibility: Making Your Application Compatible with Earlier Versions of Windows. On visual styles, it states:

Much of the visual style architecture is designed to make it simple to
  continue to ship your product on earlier versions of Windows that do
  not support changing the appearance of controls.

A: This is not a problem.  The manifest simply tells Windows that you want version 6 of the common controls DLL.  The one that's stored in the side-by-side cache (c:\windows\winsxs), not the legacy one stored in c:\windows\system32.  The side-by-side cache is a DLL Hell counter-measure, it can store different versions of DLLs with the same name.
The manifest has no effect on earlier versions of Windows, those versions didn't know anything about manifests so don't know to look for them.


text:
Q: How to write transition coverage between two enums? enum {Idle, S1, S2} State;

covergroup cg_State @(posedge Clock);
  states      : coverpoint State;
  state_trans : coverpoint State {
    bins legal[] = ( Idle => S1, S2 ),
                   ( S1, S2 => Idle);
    bins idle[] = ( Idle [* 2:4] );
    bins illegal = default sequence;
  }
endgroup

For a single enum I am aware that the transition coverage looks as above
In my case I have two enums which are represented as below,
typedef enum {RST=0,START=1,PAUSE=2,RESUME=3} instr_t;
typedef enum {IDLE=0,RUNNING=1,PAUSED=2,EXPIRED=3} state_t;

I am trying to write coverpoint for IDLE => RST, START => RUNNING etc but could not figure out a way to do this,
could anyone tell if there is any possible way to do this eg(IDLE=> RST, IDLE => START etc)

A: Since both of them are two independent enums, it does not make sense to look for transition coverage across them.
It makes more sense to do a cross coverage.
When you mean (IDLE=> RST, IDLE => START ), you probably want a cross coverage that checks when state_t is in IDLE state,  instr_t is in RST or instr_t transitions from RST->START
And this can be done with cross coverage constructs


text:
Q: CFSocketCreate request is not going via UDP I have used below code to create socket.
CFSocketRef socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, NULL, NULL);

I have given SOCK_DGRAM, IPPROTO_UDP as parameters to go request via UDP, But still request is going via TCP only checked using Wireshark.
Any help would be really appreciated.


text:
Q: simple html DOM cant see all hrefs Im trying to retrieve the youtube link of a certain site. But when using the simple html DOM parser it cant find the links im looking for.
$new_html = file_get_html("https://www.bia2.com/video/Amir-Shamloo/Delam-Tange/");
    foreach ($new_html->find('href') as $youtube) {
    echo $youtube;
}

it should find the link: https://www.youtube.com/watch?v=vJ2aNG0aJPU.
does someone know what the problem is here?

A: That particular link is inserted via JavaScript via onYouTubeIframeAPIReady("vJ2aNG0aJPU") during the onload event.
SimpleHtmlDom (or any other PHP based HTML parser for that matter) will not execute any JavaScript. They just parse the markup returned by the webserver.
You'd need a scraper capable of executing Javascript before you can scrape it. Or you can match the argument to that function and assemble the link yourself.
On a side note: $new_html->find('href') will try to find any elements named "href", which is obviously wrong. To get all href attributes for any element, you'd have to use *[href] instead.
On another side not: SimpleHtmlDom is a crap library. Consider your options:

*

*How do you parse and process HTML/XML in PHP?


text:
Q: Creating a Web Form from an XML Description of It i am assigned to web part of some project.My duty is to create web form from xml.
These xml comes from window part and tells which controls are include in my web form and their properties.My xml Format is like below.
<Object type="System.Windows.Forms.Form">
  <Property name="Name">Form1</Property>
  <Property name="Text">Option</Property>
  <Object type="System.Windows.Forms.RadioButton">
    <Property name="Name">RadioButton1</Property>
    <Property name="Size">86, 24</Property>
    <Property name="Text">RadioButton1</Property>
    <Property name="Location">175, 126</Property>
  </Object>
  <Object type="System.Windows.Forms.CheckBox">
    <Property name="Name">CheckBox1</Property>
    <Property name="Size">84, 24</Property>
    <Property name="Text">Accept</Property>
    <Property name="Location">84, 126</Property>
  </Object>
  <Object type="System.Windows.Forms.TextBox">
    <Property name="Name">TextBox1</Property>
    <Property name="Size">177, 20</Property>  1
    <Property name="Text">Singapore</Property>
    <Property name="Location">84, 88</Property>
  </Object>
  <Object type="System.Windows.Forms.Label">
    <Property name="Name">Label1</Property>
    <Property name="Size">100, 23</Property>
    <Property name="Text">Name</Property>
    <Property name="Location">7, 53</Property>
  </Object>
  <DataSet1>
    <Table1>
      <TableName>TableOne</TableName>
      <ItemName>item001</ItemName>
      <Qty>100</Qty>
      <Price>1000</Price>
    </Table1>
    <Table2>
      <TableName>TableTwo</TableName>
      <ItemName>item002</ItemName>
      <Qty>200</Qty>
      <Price>2000</Price>
    </Table2>
  </DataSet1>
</Object>

what is the best way to solve my problem? i found some people used
XmlSerialization, so, can i use this way or is there any other way?

A: *

*I hope you don't expect to be adding Windows Forms controls onto your web form.

*This doesn't make much sense. You will not only need to create a web form - you also need to be able to create code to handle events from the controls on the form. I don't see anything in your XML that describes that.


text:
Q: Changing Design For All Module Pages In Magento I'm doing a custom module in Magento and everything is going swimmingly... except I want to change the base layout template that all pages in the module use.  I've done some googling with little success.  Anyone have any answers?  I want to do something along the lines of:
...
<optionbox>
  <reference name="root">
    <action method="setTemplate"><template>page/empty.phtml</template></action>
  </reference>
</optionbox>

As you may guess, it's a lightbox... I'm a glutton for punishment I guess :)

A: I notice that you've got the root of your layout update as <optionbox> which in theory should cover all controllers and actions under that module.  However, I've only ever seen this done with <optionbox_index> where index is from IndexController in your module.  So perhaps try this replaced with your controller name:
<layout>
 ...
 <optionbox_index>
   <reference name="root">
     <action method="setTemplate"><template>page/empty.phtml</template></action>
   </reference>
 </optionbox_index>

Also, you should try Alan Storm's LayoutViewer module, instructions on it's use here.  That might help you debug it.
Cheers,
JD

A: In my modules I do it within the controller action like so:
public function listAction() {
  $this->loadLayout();
  $this->getLayout()->getBlock('root')->setTemplate('page/2columns-right.phtml');
  $this->renderLayout();
}

A: have you tried inserting that snippet into your optionbox.xml layout file? It looks like it should work as you have it?


text:
Q: Symfony2 - add attribute/class to single select option Having form select field like:
$builder->add('foo', new ChoiceType, $this->defaults + [
                'choices'           => [/* some choices as key->value*/],
            ]);

I would like to add class to some of the options, so it renders like:
<select>
    <option value="1">foo</option>
    <option value="2">bar</option>
    <option value="3" class="showModal">baz</option>
</select>

How to achieve it? Important thing is that I would like to do this inside form type, not in template.
Similar problem has been described: here, but it was about input field.

A: Stumbled on this post..
You can use the choice_attr option, like this :
        $builder
            ->add('cours', ChoiceType::class, [
                'choices' => $this->getCours(),
                'required' => true,
                'multiple' => false,
                'expanded' => false,
                'attr' => [
                    'class' => 'select2'
                ],
                'constraints' => [
                    new NotBlank(),
                ],
                'choice_attr' => function($choice, $key, $value) {
                    return ['class' => 'my_class'];
                },
            ])
        ;


text:
Q: How to connect two points in Google map..?     function createLine()
{

        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(7.5653, 80.4303);
        var mapOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

        var address = document.getElementById('startvalue').value;
        var address2 = document.getElementById('endvalue').value;

        var temp, temp2;

        geocoder.geocode({ 'address': address }, function (results, status) {
            temp = results[0].geometry.location;
        });
        geocoder.geocode({ 'address': address2 }, function (results, status) {
            temp2 = results[0].geometry.location;
        });

        var route = [
          new google.maps.LatLng(temp),
          new google.maps.LatLng(temp2)
        ];

    var polyline = new google.maps.Polyline({
        path: route,
        strokeColor: "#ff0000",
        strokeOpacity: 0.6,
        strokeWeight: 5
    });

    polyline.setMap(map);

}

I want to draw a direct line to connect two points and i wont to calculate that line distance.any way i try to connect points using this code but it didn't work.Please help me..

A: Geocoding is asynchronous.  Try something like this (call the second geocoder operation from the call back of the first, use the results of both inside the call back of the second).
function createLine()
{

    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(7.5653, 80.4303);
    var mapOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

    var address = document.getElementById('startvalue').value;
    var address2 = document.getElementById('endvalue').value;

    var temp, temp2;

    geocoder.geocode({ 'address': address }, function (results, status) {
        temp = results[0].geometry.location;
        geocoder.geocode({ 'address': address2 }, function (results, status) {
            temp2 = results[0].geometry.location;

        var route = [
          temp,
          temp2
        ];

        var polyline = new google.maps.Polyline({
            path: route,
            strokeColor: "#ff0000",
            strokeOpacity: 0.6,
            strokeWeight: 5
        });

        polyline.setMap(map);
        });
    });
}

working example

code snippet:

var geocoder;
var map;

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(7.5653, 80.4303);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map"), mapOptions);

  createLine();
}

function createLine() {

  var address = document.getElementById('startvalue').value;
  var address2 = document.getElementById('endvalue').value;

  var temp, temp2;

  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status != "OK") alert("geocode of address:" + address + " failed, status=" + status);
    temp = results[0].geometry.location;
    document.getElementById('results').innerHTML += temp.toUrlValue() + "
";
    geocoder.geocode({
      'address': address2
    }, function(results, status) {
      if (status != "OK") alert("geocode of address:" + address + " failed, status=" + status);
      temp2 = results[0].geometry.location;
      document.getElementById('results').innerHTML += temp2.toUrlValue() + "
";

      var route = [
        temp,
        temp2
      ];

      var polyline = new google.maps.Polyline({
        path: route,
        strokeColor: "#ff0000",
        strokeOpacity: 0.6,
        strokeWeight: 5
      });

      var lengthInMeters = google.maps.geometry.spherical.computeLength(polyline.getPath());
      // alert("polyline is "+lengthInMeters+" long");
      document.getElementById('results').innerHTML += "Polyline is " + lengthInMeters + " meters long
";

      polyline.setMap(map);
      var bounds = new google.maps.LatLngBounds();
      bounds.extend(temp);
      bounds.extend(temp2);
      map.fitBounds(bounds);
    });
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  margin: 0;
  padding: 0;
  height: 100%;
}
<input id="startvalue" type="text" width="90" value="Megaswewa, Sri Lanka"></input>
<input id="endvalue" type="text" width="90" value="Kandy, Sri Lanka"></input>
<input type="button" value="Geocode" onclick="createLine()"></input>


text:
Q: Normal closure in Baumslag-Solitar group Let $G:=BS(m,n)= \langle a,t \mid ta^mt^{-1}=a^n\rangle$ be a Baumslag-Solitar group (here $m,n\in \Bbb Z\setminus\{\pm 1\})$.
I was trying to determine the normal closure of the element $a\in G$; here, by normal closure I mean $\langle a\rangle^G:=\langle\{gag^{-1}\mid g\in G\}\rangle$.
At first I thought that $\langle a\rangle^G\cong F_\infty$  as the set $\{t^{r}at^{-r}\mid r\in \Bbb Z\}$ is contained in $\langle a\rangle^G$.
But this set is not a free generating set since $a^n=(tat^{-1})^m$.
So I want to know, what is the subgroup $\langle a\rangle^G$ precisely?
Thank you so much in advance!

A: "determine the normal closure" is not very clear. It seems you want to identify the isomorphism type of the normal closure.
Namely, this kernel $\mathrm{BS}_0(m,n)$ is an infinitely iterated amalgam
$$\cdots\ast_\mathbf{Z}\mathbf{Z}\ast_\mathbf{Z}\mathbf{Z}\ast_\mathbf{Z}\mathbf{Z}\ast_\mathbf{Z}\cdots$$
where each left embedding is $k\mapsto nk$ and each right embedding is $k\mapsto mk$. This is a general fact about HNN extensions (description of the isomorphism type of the kernel of the canonical homomorphism from a given HNN-extension onto $\mathbf{Z}$), which can be found in Serre's book. In particular, this kernel $\mathrm{BS}_0(m,n)$ is not free as soon as $\max(|m|,|n|)\ge 2$. Indeed,

*

*if $\min(|m|,|n|)=1$ (say $m=\pm 1$ and $|n|\ge 2$), this kernel $\mathrm{BS}_0(\pm 1,n)$ is isomorphic to the infinitely generated abelian group $\mathbf{Z}[1/n]$;

*if $\min(|m|,|n|)\ge 2$, this kernel $\mathrm{BS}_0(m,n)$ contains a copy of $\mathbf{Z}^2$ (inside the amalgam $\mathbf{Z}\ast_\mathbf{Z}\mathbf{Z}=\langle a,b\mid a^m=b^n\rangle$, namely $\langle a^m,ab\rangle\simeq\mathbf{Z}^2$), hence is not free.

*(If $|m|=|n|=1$ this kernel $\mathrm{BS}_0(m,n)$ is infinite cyclic.)

On the other hand, the kernel $\mathrm{BS}_{00}(m,n)$ of the canonical homomorphism onto $\mathbf{Z}[m/n,n/m]\rtimes_{m/n}\mathbf{Z}$ is free, since it acts freely on the Bass-Serre tree.
Note: $\mathrm{BS}_0(m,n)$ is locally residually finite. Also $\mathrm{BS}_0(m,n)$ is not residually finite if $|m|,|n|$ are coprime and $\ge 2$: this is due to R. Campbell (1990 Proc AMS). I don't know if it's also non-residually-finite whenever $2\le |m|<|n|$, for instance, $(m,n)=(2,4)$.

Edit: the free subgroup $\mathrm{BS}_{00}(m,n)$ is infinitely generated as soon as $2\le |m|<|n|$. Since $2\le \min(|m|,|n|)$, it is not trivial, hence contains a loxodromic element for the action on the Bass-Serre tree. Hence it has a unique minimal nonempty subtree (the convex hull of the union of axes of loxodromic elements) for the action on the Bass-Serre tree $T$ of the HNN extension defining $\mathrm{BS}(m,n)$; hence this subtree is invariant under the whole group, and hence by vertex-transitivity, this is the whole tree.
The tree $T$ naturally carries a Busemann-function (defined up to addition with an integral constant), so that every vertex $v$ has $n+m$ adjacent vertices: $m$ vertices $w$ with $b(w)=b(v)-1$ and $n$ vertices $w$ with $b(w)=b(v)+1$. Let $G$ is the group of automorphisms of $T$ preserving $b+\mathbf{Z}$, so the locally compact group $G$ acts cocompactly on $T$ and $\mathrm{BS}(m,n)$ acts through $G$.
Now assume by contradiction that $\mathrm{BS}_{00}(m,n)$ is finitely generated: then since it acts freely and minimally on the tree $T$, the action is cocompact. Hence $\mathrm{BS}_{00}(m,n)$ is a cocompact lattice in $G$. But $G$ is not unimodular, by an easy argument (using $|m|\neq |n|$). This is a contradiction.