How to dynamically add attributes to an interface

Question: I need to add an attribute for every attribute in an interface. So I am trying to dynamically modify it to add them, but not with much success for now.
Let's say I have the following interface:
class IMember(Interface):
    first_name = schema.TextLine(title=u'first name')
    last_name = schema.TextLine(title=u'last name')

And I would like to modify it like that:
class IMember(Interface):
    first_name = schema.TextLine(title=u'first name')
    last_name = schema.TextLine(title=u'last name')
    visbility_first_name = schema.Bool(title=u'Display: first name')
    visbility_last_name = schema.Bool(title=u'Display: last name')

I tried modifying the class afterwards, but as it was already initialized, the schema was set and I was not sure how to change it. I also thought about writing a directive (e.g.: interface.Implements()) but it seems quite complicated to do just to add attributes.
My final goal is to add a z3c.form fieldset with a set of Bool widgets.
So, is there a way to do it in Python, or do I have to modify the interface and add all the attributes manually ?
Thanks !
Comment: Are you sure your additional attributes need to be first class fields on the schema? Maybe [Tagged Values](https://developer.plone.org/components/interfaces.html#tagged-values) on the interface could work for you.
Comment: Sorry, on mobile, having trouble posting the right links: http://docs.zope.org/zope.interface/README.html#tagged-values
Comment: My final goal is to have a fieldset in z3c.form with a set of Bool widgets. I don't think tagged values will be helpful in this case.
Answer: You can create a dynamic subclass of the interface using the InterfaceClass metatype.
Create a dictionary of the additional schema fields:
fields = {}
for name, attr in IMember.namesAndDescriptions():
    if isinstance(attr, schema.Field):
        fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

Now you can create a dynamic interface subclassing your existing interface:
from zope.interface.interface import InterfaceClass

IMemberExtended = InterfaceClass('IMemberExtended', (IMember,), fields)

This can all be wrapped up in a class decorator if you so desire:
from zope.interface.interface import InterfaceClass
from zope import schema

def add_visibility_fields(iface):
    fields = {}
    for name, attr in iface.namesAndDescriptions():
        if isinstance(attr, schema.Field):
            fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

    return InterfaceClass(iface.__name__, (iface,), fields)

which you'd use on your existing interface:
@add_visibility_fields
class IMember(Interface):
    first_name = schema.TextLine(title=u'first name')
    last_name = schema.TextLine(title=u'last name')

This creates a subclass; you can also replace the whole interface with the generated interface:
def add_visibility_fields(iface):
    fields = {}
    for name, attr in iface.namesAndDescriptions():
        fields[name] = attr
        if isinstance(attr, schema.Field):
            fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)

    return InterfaceClass(iface.__name__, iface.__bases__, fields)

Demo of that last version:
>>> @add_visibility_fields
... class IMember(Interface):
...     first_name = schema.TextLine(title=u'first name')
...     last_name = schema.TextLine(title=u'last name')
...
>>> IMember.names()
['visible_last_name', 'first_name', 'last_name', 'visible_first_name']

Answer: It seems like you want to use python's metaclasses. Use of a custom metaclass will allow you to modify the creation of a class, so you can dynamically add or modify attributes upon/before class creation. For an excellent SO answer on metaclasses see this post.
However you should try and restructure your program to avoid having to use metaclasses. Typically they should only be used if you really know you need them. In your case, is it possible to modify schema.TextLine to allow the behavior you want (perhaps by adding a hook)?
Comment: @MartijnPieters Your answer looks great. I like your class decorator and usage of Zope's `InterfaceClass`. I think I'll steal this pattern for the future haha.
Comment: `zope.interface` already makes heavy use of metaclasses though, it'll be... tricky to integrate with that.
Comment: Yeah, using metaclasses is tricky to begin with, I can't even imagine how much of a headache trying to do metaclass inheritance must be... All the more reason to find a solution that doesn't involve them!
Comment: Yeah it seems quite complicated to implement, having an easier solution would be great :).
Comment: @FastTurtle: You can just use the metaclass to produce a new interface object; see my answer.
Comment: @FastTurtle: also note that a Zope and Plone lean *heavily* on interfaces and schemas; avoiding these would be akin to trying to swim up a waterfall.


sudo: setuid must be root

Question: I changed the permissions of my /usr directory to 777 by mistake and now my system give this error whenever I try to use sudo:
sudo: setuid must be root

How do I fix this issue?
Comment: should be on serverfault, but i'll tell you now your best bet is to re install OS - all the setuid and setgid bits will be gone, short of finding out what all of those are and running `chmod +sS` you'll want to reinstall
Comment: i had the same problem 2 weeks ago. reinstalling is the only solution.
Answer: Based on your error, you didn't simply changed the permissions of /usr to 777, you did it recursively which is a more serious and problematic change.
Unless you have backups of your system directories, your best option is just to reinstall.
Comment: With the caveat that you *could* manually reset every file of every sub-directory to the right setting by manually comparing it to a good Ubuntu install.
Answer: Go to recovery console (reboot, and chose recovery console ) and type
chown root:root /usr/bin/sudo
then
chmod 4755 /usr/bin/sudo
then
reboot
Comment: It'll work for `sudo` only, but other binaries are affected as well and are likely to cause issues too.

sudo: setuid must be root


IE8 Issue with R2D3

Question: I have been using R2D3 for drawing a force directed layout. When i run it on IE8 i see Arg: Illegal input string in Vector2D as seen below:

This happens for transform attribute i apply for the layout.
node.attr("transform", function(d) {
  return "translate(" + d.x + "," + d.y + ")";
});

I doubt the translate function returns some value the browser engine is not able to read. Possible a large number. Is there any way I can position the nodes without using transform attr. Following is my code:
d3.json("egoGraph.json", function(json) {
    nodeSet = json.nodes;
    linkSet = json.links;
        var width = 600;
        var height = 500;
        var centerNodeSize = 30;
        var nodeSize = 10;

         var rscale = d3.scale.linear().domain([0, d3.max(nodeSet, function (d) {
                return d.data
            })]).range([5, 20]);

         var color = ['#B43104','#F5ECCE', '#F3E2A9', '#F7D358', '#FFBF00', '#FF8000'];
        // Create a canvas...
        var svgCanvas = d3.select('#chart').append("svg:svg").attr(
                "width", width).attr("height", height).append("svg:g")
                .attr("class", "focalNodeCanvas").attr("transform",
                        "translate(" + width / 3.333333 + "," + height / 2.352 + ")")

        var node_hash = [];
        //var type_hash = [];

        // Create a hash that allows access to each node by its id
        nodeSet.forEach(function(d, i) {
            node_hash[d.journalname] = d;
            //type_hash[d.type] = d.type;
        });

        // Append the source object node and the target object node to each link records...
        linkSet.forEach(function(d, i) {
            d.source = node_hash[d.sourceId];
            d.target = node_hash[d.targetId];
            if (d.sourceId == focalNodeID) {
                d.direction = "OUT";
            } else {
                d.direction = "IN";
            }
        });

        // Create a force layout and bind Nodes and Links
        var force = d3.layout.force().nodes(nodeSet).links(linkSet).charge(
                -1000)
        //.gravity(.2)
        //.linkStrength(20)
        .size([ width / 8, height / 10 ]).linkDistance(function(d) {
            if (width < height) {
                return width * 1 / 3;
            } else {
                return height * 1 / 3
            }
        }) // Controls edge length
        .on("tick", tick).start();

        // Draw lines for Links between Nodes
        var link = svgCanvas.selectAll(".gLink").data(force.links())
                .enter().append("g").attr("class", "gLink").append("line")
                .attr("class", "link").attr("stroke-width", function(d) {
                    return (Math.random() * (10 - 1) + 1);
                }).style("stroke", "#808080").attr("x1", function(d) {
                    return d.source.x;
                }).attr("y1", function(d) {
                    return d.source.y;
                }).attr("x2", function(d) {
                    return d.target.x;
                }).attr("y2", function(d) {
                    return d.target.y;
                });

        // Create Nodes
        var node = svgCanvas.selectAll(".node").data(force.nodes()).enter()
                .append("g").attr("class", "node").attr("fixed", function(d) {
                    return true
                }).call(force.drag);

        // Append circles to Nodes
        node.append("circle").attr("x", function(d) {
            return 100;
        }).attr("y", function(d) {
            return 30;
        }).attr("r", function(d) {
            if (d.journalname == focalNodeID) {

                return centerNodeSize;

            } else {
                return rscale(d.data);
            }
        }) // Node radius
        .style("fill", function(d) { return color[Math.floor(Math.random() * (5 - 0 + 1)) + 0]; }) // Make the nodes hollow looking
        .on("mouseover", function() { d3.select(this).attr("stroke", "#808080").attr("stroke-width", 5);})
        .on("mouseout",  function(){ d3.select(this).attr("stroke",  function(d) { return color[Math.floor(Math.random() * (5 - 0 + 1)) + 0]; }).attr("stroke-width", 0);})
        .call(force.drag);

        // Append text to Nodes
        node.append("text").attr("x", function(d) {
            if (d.journalname == focalNodeID) {
                return 0;
            } else {
                return 20;
            }
        }).attr("y", function(d) {
            if (d.journalname == focalNodeID) {
                return 0;
            } else {
                return -10;
            }
        }).attr("text-anchor", function(d) {
                    return "middle";
        }).attr("font-family", "Arial, Helvetica, sans-serif").style(
                "font", "normal 12px Arial").text(function(d) {
            return d.journalname;
        });

        function tick() {
            link.attr("x1", function(d) {
                return d.source.x;
            }).attr("y1", function(d) {
                return d.source.y;
            }).attr("x2", function(d) {
                return d.target.x;
            }).attr("y2", function(d) {
                return d.target.y;
            });

            node.attr("transform", function(d) {
                return "translate(" + d.x + "," + d.y + ")";
            });

        }

});

Answer: transform doesn't work in IE8, and in IE9 you need the browser prefix ms-
So you will need to abstract your transform call, or use an expression in CSS
http://msdn.microsoft.com/en-us/library/ms532918(v=vs.85).aspx

IE8 Issue with R2D3


How to control the spacing/indentation of an HTML container tag?

Question: I'm using a bootstrap navbar and I have put the contents of the navbar inside a container.  With the container, the indentation (for lack of a better term) of the navbar is a little too wide for my liking. Is there a way to shorten the indentation and bring the content of the navbar closer to the edges of the browser (by way of HTML or CSS)?
Seeing the code may not be useful but here it is:

        Navbar
        <button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button">

        </button>

                    Home

                    Link

                        Dropdown

                        Action
                        Another action

                        Something else here

            <form class="form-inline my-2 my-lg-0">
                <input aria-label="Search" class="form-control mr-sm-2" placeholder="Search" type="search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

Answer: Using css media query you can adjust the bootstrap default container width. I just adjusted the max container width by adding small class. You can adjust your max-width based on your requirement.

@media (min-width: 1200px)
.small.container {
    max-width: 980px; //overwritten the default boostrap width
}
@media (min-width: 992px)
.small.container {
    max-width: 960px;
}
@media (min-width: 768px)
.small.container {
    max-width: 720px;
}
@media (min-width: 576px)
.small.container {
    max-width: 540px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

        Navbar
        <button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button">

        </button>

                    Home

                    Link

                        Dropdown

                        Action
                        Another action

                        Something else here

            <form class="form-inline my-2 my-lg-0">
                <input aria-label="Search" class="form-control mr-sm-2" placeholder="Search" type="search">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

Answer: Looks like you need .container-fluid and not .container. From the docs:

Use .container-fluid for a full width container, spanning the entire width of the viewport.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

    Navbar
    <button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button">

        </button>

          Home

          Link

                        Dropdown

            Action
            Another action

            Something else here

      <form class="form-inline my-2 my-lg-0">
        <input aria-label="Search" class="form-control mr-sm-2" placeholder="Search" type="search">
        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
      </form>

PS: You probably don't need a .container div. Just tried without it here:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

  Navbar
  <button aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarSupportedContent" data-toggle="collapse" type="button">

        </button>

        Home

        Link

                        Dropdown

          Action
          Another action

          Something else here

    <form class="form-inline my-2 my-lg-0">
      <input aria-label="Search" class="form-control mr-sm-2" placeholder="Search" type="search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>

Comment: Yes, I looks like container-fluid does leave a small indentation which is what I was looking for, versus when I take it out completely it removes the spacing entirely and practically spans the entire width. Small and subtle difference between the two but it does what I was looking for
Comment: If this answers your question, you can mark the answer as accepted for anybody who would like to solve a similar problem in the future.


Activate the corresponding ribbon tool tab

Question: Programmatically select a shape on PowerPoint slides doesn't activate the corresponding ribbon tool tab.
The attached image shows that when selecting an "Audio Shape" manually, the ribbon tab of "Audio Tools" is then automatically visible. But when selecting the shape through a VBA code e.g. oShp.Select, the ribbon tab of "Audio Tools" will not visible.

Is there any special trick to make the corresponding ribbon tool tab visible when selecting a shape programmatically?
I need to access some commands through the SendKeys method as I can't/ don't know how to set some properties of the audio shape (e.g. audio fade-out duration, volume, starts).

EDIT
Further testing.
The following code will make the ribbon tab visible
Sub test()
    Dim pres As Presentation
    Dim sld As Slide
    Dim shp As Shape

    Set pres = ActivePresentation
    Set sld = pres.Slides(1)
    Set shp = sld.Shapes(1)

    shp.Select
End Sub

However, if I add more lines after the select statement, the ribbon tab will not visible, e.g.
Sub test()
    Dim pres As Presentation
    Dim sld As Slide
    Dim shp As Shape

    Set pres = ActivePresentation
    Set sld = pres.Slides(1)
    Set shp = sld.Shapes(1)

    shp.Select
    DoEvents
    SendKeys "%jn%v%{DOWN}", True 'Volume=low
    'SendKeys "%jn%u%{UP}", True ' Start:  play across slides
    SendKeys "%jn%o5~", True 'Fade out: 5s
End Sub

Answer: You shouldn't need to use SendKeys.
The code below will change some of the audio options.
Sub Test()

    Dim sld As Slide
    Dim shp As Shape

    Set sld = ActivePresentation.Slides(1)
    Set shp = sld.Shapes("Recorded Sound")

    With shp.MediaFormat
        .FadeInDuration = 1000
        .FadeOutDuration = 1000
        .StartPoint = 0
        .EndPoint = 4000
        .Volume = 0.8
    End With

End Sub

I'll admit I haven't found how to Play Across Slides or Rewind after Playing.
Comment: How to set the property "Hide During Show" to True (ticked)?


Is Ubuntu One be able to store RAW and AVI files?

Question: Is Ubuntu One be able to store RAW file and AVI video format. I cant find an answer on this question on here. I have tried and none of my files were able to be copied
Answer: You can upload any kind of file to ubuntu one it shouldn't make a difference as long as you have enough free space.


What thickness drywall do I need for 24" OC wall studs in a detached garage?

Question: I am currently finishing an older 3-car detached garage.  Both the wall studs and the ceiling trusses have 24" OC spacing.
I know that for the ceiling, I'll need to use 5/8" thick drywall, due to the 24" spacing, and sagging that would occur over time as moisture hits the drywall (which will happen in a detached garage).  However, for the walls, our local code allows for 1/2" wallboard for 24" OC studs.  But wouldn't I have the same issues as with the ceiling?  Thoughts?  (I am not opposed to the price- it is only about $30 difference to use all 5/8".  However it is easier to hang 1/2")
Answer: You actually have a couple of options in this case.  The easiest option would be to simply use 12 ft sheets of 5/8 fire rated sheetrock and rent a lift to do the ceiling with.  A lift is very easy to use and almost makes it a one person job.  Personnally, I'd also use 5/8 on the walls as well. As BMitch already mentioned, mount the wall sheets horizonally and stagger the vertical joints.  You can use 2X4 nailers, (fire breaks) at the 4ft OC point, but not really necessary.  You will not see any bowing or cupping with 5/8" at 24" OC on walls.
The second, and BEST option would be to install 3/4" strapping 12" OC across the field of the ceiling, and around the parameter.  This will give you a lot more surface area to screw the drywall to and make aligning joints a lot easier, especially if the 24" joists are not perfectly spaced or square. Putting up strapping is quick and easy if you have a nail gun. Use 4D ring nails. Ring nails will hold tight and not loosen over time.
Hint: Use a chalk line on rock to mark backer locations before you hang it, or you can also mark the location of your joists or strapping on the wall before you lift the rock into place. Secure the rock with a few screws to hold it in place, then  use the marks to snap a quick chalk line marking the location of your strapping. This will assure you hit a solid spot with every screw. Ceiling screws should be no more than 16 inches apart.
Comment: +1, lots of great points. @MarkD, if you don't go with the strapping idea, any joists/studs that aren't well aligned for the end of your drywall can be worked around by sistering a stud on the side you need it. On the ceiling, I'd extend any sistered joist all the way between the two load bearing walls to add structure.
Answer: 5/8" drywall will work on the ceilng, and in a garage, I would want to use fire rated even if it isn't required in your instance/locality. You can also get 1/2" sag resistant drywall that is specially designed to handle 24" OC ceiling joists, but I can't find it at the major HI stores online, so this may be a special order.
For the walls, you shouldn't have the same sagging issues as the weight is pulling the drywall to the floor rather than away from the wall. In that situation, the drywall is under a lot of compression force, which it handles well. It's the expansion that drywall doesn't do well with, which is why it's easy to break when one side of the paper is cut.
If you are paranoid about this, then install a fireblock (a standard 2x4 installed horizontally between two studs so that fire cannot freely burn up the wall cavity) in your walls at exactly 4' from the ceiling and use that to give extra support to each piece of drywall and make a stable connection between the two sheets. With 24" wall spacing, my concern is structural, so assuming the current design passes code, I would install the drywall horizontally to connect the maximum number of studs together.


Mask phone numbers with (XXX-XXX-XXXX) in a Text C#

Question: I am trying to mask the phone number from a text file that gets captured in richtextbox.Text
from a log file .I am unable to get a proper logic based on the indexes ,since the text indexes changes based on the length of the log file.The log file starts with every import dates .e,g today's date
The contents from richTextBox2.Text :
<code>Started: 11/11/2022 01:20:04 AM.

Import started for period [11/09/2022] to [11/10/2022].

Creating connection to tocco SQL server on SQL03-DM... ok.
Creating connection to Oracle database on TPROD... ok.

Checking for new completes... 10 found (may already exist in Comtel).

--> Checking home number 5811232 (123-001-8956) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception TV... Cell ID 8072 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Prai home (G2)... ok.
--> Checking home number 5791211 (456-806-0737) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception CABLE ... Cell ID 4410 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Queco home (G2)... ok.
--> Checking home number 5810404 (789-876-8864) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception TV ... Cell ID 4410 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Quenco home (G2)... ok.
--> Checking home number 5804303 (101-985-5632) in Comtel. Inserting... Home Sub Status 03 ... Recruitment Reception DIGITAL ... Cell ID 9081 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Vaome (G2)... ok.
--> Checking home number 5812793 (111-586-5998) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception DIGITAL ... Cell ID 8062 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Came (G2)... ok.
--> Checking home number 5811594 (112-670-7592) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception DIGITAL ... Cell ID 8062 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Caome (G2)... ok.
--> Checking home number 5811925 (113-599-8694) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Reception DIGITAL ... Cell ID 8112 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Edmome (G2)... ok.
--> Checking home number 5792492 (114-908-8636) in Comtel. Inserting... Home Sub Status 03 ... Recruitment Reception DIGITAL ... Cell ID 9086 ... Q1CANS Length 0 and Q1DANS Lenth 0 ... Vancoume (G2)... ok.
--> Checking home number 5822459 (115-112-2693) in Comtel. Inserting... Home Sub Status 01 ... Recruitment Recep

10 home(s) added to Comtel.
   0 home(s) skipped.

Import completed successfully.
</code>
My code
<code>  if (filedata.Contains("Started: " + value))
                {
                    int indexOfMessage = filedata.IndexOf("Started: " + value);

                    //int indexOfMessage = filedata.IndexOf("Started: " + value);

                    int indexofData = filedata.IndexOf("Ended: " + value);
                    string message = filedata.Substring(indexOfMessage, indexofData - indexOfMessage);
                    richTextBox2.Text = message;

                        if (richTextBox2.Text.Contains("--> Checking home number"))
                        {

                           // string message2 = richTextBox2.Text.Substring(indexOfMessage2, indexofData2 - indexOfMessage2);

                        }
                    }
</code>
Comment: It's not clear what you're trying to do. Are you trying to mask the phone number before it goes into the log file? Or is the text box displaying what's in the log file, and when you display it you want to mask the phone number?
Comment: I want to mask the phone numbers in the richtextbox
Answer: <code>   if (richTextBox1.Text.Contains("Checking home number"))
                        {
                            List<string> phoneList = new List<string>();
                            Regex rg = new Regex(@"\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})");
                            MatchCollection m = rg.Matches(richTextBox1.Text);
                            string Finalstring = rg.Replace(richTextBox1.Text, "");
                            richTextBox1.Text = Finalstring;
                        }
</code>


How to have specific events fire if you can only bind ajaxStart to document?

Question:
As of jQuery 1.8, the .ajaxStart() method should only be attached to document.

I have two different forms on my page, both which I want to submit using ajax, and display a 'sending' while it's happening. I want #contact_response to display a message when the #contact_form is submitted like so:
$(document).ajaxStart(function() {
    $("#contact_response").html("Sending...");
});

And similarly, #booking_response to display a message when #booking_form is submitted. However, doing this causes the other element to display Sending.... If you're only meant to attach ajaxStart() to the document, how are you meant to send multiple responses, but only update certain sections?
Is this the wrong function to use?
Answer: You could use:
$(document).ajaxSend(function (event, xhr, options) {
    if (options.url === "targetedScriptPath") $("#contact_response").html("Sending...");
}).ajaxComplete(function (event, xhr, options) {
    if (options.url === "targetedScriptPath") $("#contact_response").empty();
});

Answer: as far as i know the ajaxStart() and ajaxStop() functions are good if you want to trigger something globally on your page when some ajax-action is going on.
i ran over a similar problem, and that's how i solved it:
just trigger the action with the event that submits your form (maybe some click-event) or add an event-listener for the form submission like for example:
$('#contact_form').on("submit", function() {
    $("#contact_response").html("Sending...");
});
$('#booking_form').on("submit", function() {
    $("#booking_response").html("Sending...");
});

to trigger the action after the ajax function has been completed, use the callback-function of whatever ajax function you are using:
$.post("booking_update.php", {
        //post vars
        post_var1: post_text
    },
    function(result) {
        //callback function
        $("#booking_response").html("Success!");
    }
);


Wrap datatable pagination control inside a div using CSS

Question: I have a datatable with pagination. I want to style the div containing the pagination ul. I have tried the following code but it does not seem to work. I am not able to put the ul inside the div.row (not able to provide the desired CSS style):
HTML:

       <<

       <

      1

      2

      3

       >

       >>

CSS:
.myClass
{
border:1px solid grey;
height:50px;
margin-top:10px;
background-color: #ddd;
}

.myUlClass
{
  float:right;
  z-index:10;
  margin-bottom:10px;
}

Here is the non-working Demo
Output which I want looks like
I want pure CSS solution without modifying the HTML as well.
Answer: Just as simple as setting the following css?
.myUlClass {
  border:1px solid grey;
  height:50px;
  margin-top: 7px;
  margin-bottom:10px;
  background-color: #ddd;
}

Comment: Sorry I meant `.myUlClass` but I guess you do not want to style those but the div surrounding the pagination?
Comment: Both could do, I wanted only CSS solution. Thanks it worked :)
Answer: Demo  problem is you did not reset margin on ul  check demo now pagination is in center
Answer: /* CSS used here will be applied after bootstrap.css */
.myClass .paging_full_numbers ul
{
    border:1px solid grey;
    height:50px;
    margin-top:10px;
    background-color: red;
    padding-top:6px;
}

.myUlClass
{
  float:right;
  z-index:10;
  margin-bottom:10px;
}

.myUlClass>.active>a{
   background-color: green;
  }


argparse concatenate cli options

Question: Just starting to learn python and playing around with passing command line options to a python script. I'm trying to concatenate two or more arguments and pass it on to a string variable,
e.g.,
myscript.py http://www.domain.com 1234

put it in to a string variable called url, which then should have the value of "http://www.domain.com:1234"
I'm not quite sure on how to archive that. It's quite straight forward to do it with raw_input and some string manipulation, but I wonder if this can be done with argparse as well.
Comment: What have you tried? It seems like argparse isn't all that useful in this case.
Answer: import argparse

parser = argparse.ArgumentParser()
parser.add_argument('server') # first positional argument
parser.add_argument('port') # second positional argument
args = parser.parse_args()

url = '%s:%s' % (args.server, args.port)
print url

Answer: argparse is one way to solve it, but may be overkill if you're just learning (YMMV).
If you import the sys module, the command line arguments passed to you are available in a list of strings at sys.argv
import sys
if len(sys.argv) < 3:
    print "Not enough args!"
    sys.exit(0)
# sys.argv[0] is the name of your script, the rest are parameters
url = "%s:%s" % (sys.argv[1], sys.argv[2])
print url

Comment: argparse seems to be quite powerful though, but looking at the examples on http://docs.python.org/dev/library/argparse.html was a bit overwhelming, especially if you just start out with the language.
Comment: Funny how the argparse example is in fact nearly as short ;)
Comment: @delnan -- yeah, that does kind of undercut my "why bother with argparse?" argument...
Answer: Why not do,
argstring = ':'.join(args[1:])

Answer: If you want a variable with the string http://www.domain.com:1234 from command line input then do the following:
if len(sys.argv) >= 3:
    result = '%s:%s' % tuple(sys.argv[1:3])

Answer: Thanks Amber,
that was exactly what I was looking for
#!/usr/bin/python

from urllib import urlopen
import argparse

usage='will be using it later'

parser=argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=usage, add_help=False)
parser.add_argument('link')
parser.add_argument('port')
args = parser.parse_args()

url = '%s:%s' % (args.link, args.port)
link = urlopen(url)
content=link.read()

print(content)

just a bit confused with this line "url = '%s:%s' % (args.link, args.port)"
does that line take the arguments in brackets and add it to the string variable 'url'?
Jack
Answer:
just a bit confused with this line
  "url = '%s:%s' % (args.link,
  args.port)" does that line take the
  arguments in brackets and add it to
  the string variable 'url'?

That format is actually not recommended any more. ( see http://docs.python.org/tutorial/inputoutput.html). The simplest way to do the same with a currently recommended method would be:-
url = '{0}:{1}'.format( args.link , args.port )

where {n} is the nth variable within format( variables ). This method will always convert the arguments to a string for you.
The older method using %s does the same; the 's' meaning turn an argument into a string, but there has to be exactly as many '%s' flags within the string as there are arguments after the % sign after the string. Don't worry about this, but if you're learning, use .format().

argparse concatenate cli options


How to determine location of IsolatedStorageFile root directory

Question: I'm using IsolatedStorage for persisting objects, but from time to time I need to manually clean out files from this directory.
As I persist the files, I want to write the physical location of the directory to the console. There doesn't appear to be an accessible property that returns this information though.
How should I do it?
Here is my incomplete code:
using (var store = IsolatedStorageFile.GetMachineStoreForAssembly())
{
   Console.WriteLine("Persisting Hotel to {0}", store.<<INSERT APPROPRIATE PROPERTY>>);
}

Answer: Well, I haven't tried this, but I did find a link (wasn't easy to find) that supposedly shows how to do this: http://msmvps.com/blogs/angelhernandez/archive/2008/10/04/retrieving-file-path-from-isolatedstorage.aspx
Basically the key line of code appears to be:
fileName = isoStore.GetType.GetField("m_RootDir",Reflection.BindingFlags.NonPublic or Reflection.BindingFlags.Instance).GetValue(isoStore).ToString

I'm not sure if any special permissions have to be set to get this to work.
Ok, also found a related stackoverflow: Can I get a path for a IsolatedStorage file and read it from external applications?
Answer: Try this:
using System.IO.IsolatedStorage;
using System.Reflection;

var store = IsolatedStorageFile.GetMachineStoreForAssembly();
var pathName = store.GetType().GetField("m_RootDir", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(store).ToString();


File edited remotely on GitHub site lost after force-pushing from local

Question: In my remote repository, I only had a readme on which I was working on.  I committed the readme after the last update.Afterwards I accidentally pushed a folder from my local repository to that remote one, resulting in losing the readme file I was working on.
Is there any way I can get the readme back?
n.b. went through my command history, noticed that I did a git push origin master --force. I am a beginner, I think there went something wrong while using force. Without force, the error was :
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

EDIT: the error looks pretty much same like having a merge conflict, but the bone of contention here is that my problem is losing a commit from remote after pushing from local without pulling it. The accepted answer solved my problem.
Comment: Did you "commit the readme after the last update" in the remote repository, or locally? Please give us more details. Did you force-push?
Comment: Force-push removed the commit from the remote repository. It is still likely on disk there but if this was github, as judging by your comments on the now deleted answer, I'm unsure if you can access the reflog on github directly. I found this - https://medium.com/git-tips/githubs-reflog-a9ff21ff765f - which seems to indicate you can grab the hash of the commit containing that readme file, and that might allow you to bring it back.
Comment: As for other tips, if, as you say, you're a beginner with git, **do not use force-push**. That and a few other commands can lead to lost commits (not immediately lost permanently, but still). It's an operation similar to "hmm, I can't seem to bend my arm backwards at the angle I want... I know, I'll use a sledgehammer!"
Comment: You can try accessing the event log from that link I provided above, which should be `https://api.github.com/repos///events`, then see if you can find the commit with your readme and grab the SHA of it. Then, once you have that, see if you can access `https://github.com///commit/`, and see if that gives you the content.
Comment: edited the question, yes used force push
Comment: Possible duplicate of [git: updates were rejected because the remote contains work that you do not have locally](https://stackoverflow.com/questions/24357108/git-updates-were-rejected-because-the-remote-contains-work-that-you-do-not-have)
Comment: https://stackoverflow.com/search?q=%5Bgit%5D+hint%3A+Updates+were+rejected+because+the+remote+contains+work+that+you+do
Comment: @LasseVågsætherKarlsen yes that did solve my problem ! Saved the raw content for recovering my readme.
Answer: There's a few steps involved so let's go through them.

First and foremost, it's important that you understand that "lost commits" are not permanently lost immediately but may still reside on disk for a limited time. It is very important that you don't push or modify the repository in question further before attempting to fix your current problem

Additionally, depending on what you've done to the repository already, it may already be too late. But let's assume it isn't and see if we can retrieve your lost file.
First, navigate to your GitHub repository in question, let's say this is this (I'm using my own repository as an example, please edit the pertinent bits as indicated below):
https://github.com/lassevk/LVK
                   ^--edit---^

Then let's edit the URL somewhat to grab the event log of your repository:
https://api.github.com/repos/lassevk/LVK/events
                             ^--edit---^

This should give you a json file. In this json file you need to search for the file in question, or its contents, using Ctrl-F in your browser. Let's say you find it and it looks like this:
"commits": [
  {
    "sha": "a52da7697640b77f0b2e16de8d6e8ad8c29924e2",
    "author": {
      "email": "firstname.lastname@example.com",
      "name": "Lasse Vågsæther Karlsen"
    },
    "message": "Rewrite HttpClient related code.",
    "distinct": false,
    "url": "https://api.github.com/repos/lassevk/LVK/commits/a52da7697640b77f0b2e16de8d6e8ad8c29924e2"

See that SHA there? Copy it and paste it into the following type of link:
https://github.com/lassevk/LVK/commit/a52da7697640b77f0b2e16de8d6e8ad8c29924e2
                   ^-------------------------edit----------------------------^

If this gives you a "404 not found" then you're out of luck as far as I know.
However, if it opens up the commit page then you can open the files modified one by one and download their raw content directly to your local disk as files, these you can then integrate into your repository as you see fit.
If you want to create a branch for the commit and deal with it later, you can by using this URL instead:
https://github.com/lassevk/LVK/tree/a52da7697640b77f0b2e16de8d6e8ad8c29924e2
                   ^--edit---^      ^------------------edit----------------^

This should open up the repository browser for that commit, and you can then use the dropdown for branches to create a new branch that points to the commit. Once a branch points to a commit, it is no longer lost.
For instance, you can then locally do the following:
git fetch
git checkout master                # or whichever branch this is on
git merge NAME-OF-TEMP-BRANCH

This should merge that file into your branch.


TPL Dataflow and Async Method Calls

Question: I'm trying to get a better understanding of the whole concept of parallel processing and have set up test cases. After playing with the tests, I see that using Async method calls within Dataflow ActionBlock (or TransformBlock) does not positively affect performance, it just complicates the code. Am I right in assuming that if I'm using Dataflow Blocks, code within them does not have to be asynchronous, Dataflow will make it asynchronous by itself. Or am I missing the point?
Answer: TPL Dataflow doesn't enable concurrency or parallelization (although you can get things like ActionBlock to parallelize its processing) it's something concurrent or parallel code uses to communicate data.  Among other things, it's a mechanism for message passing--which is kind of an alternative to shared data.  Shared data, when used by multiple threads requires expensive synchronization.  Message-passing, when done right, doesn't need synchronization because the data that needs to be worked on is encapsulated in a message that is "sent" to the code that will work on it.
TPL Dataflow is something you can use if you have a specific design.  If you are not specifically implementing something like Actor-based programming, or message-passing, or non-blocking producer/consumer scenarios, then TPL Dataflow will likely complicate things.
If you think that you might want to design a system like this, there's some good resources on understanding TPL Dataflow (TDF) like a video by Stephen Toub (a member of the parallel team at Microsoft), as well as the Dataflow MSDN page.
UPDATE:
You can set the maximum degree of parallelism for a block, but setting it higher than the number of CPUs or Cores is often counter-productive.  The assumption is that each action that executes is more-or-less CPU bound (using the CPU at 100% while it's running).  If the actions spend a lot of time waiting (waiting on a wait handle, waiting on messages in a message pump--which isn't normal for an action but is for a UI threa--etc.) then a degree of parallelism beyond the number of CPUs might make sense (although that would be hard to tweak).  When you do have more actions running than CPUs that are CPU bound you really start to task the OS.  The OS wants to give up CPU time to each thread (or each action in this case) because it's "running".  When there aren't enough CPUs to go around, the OS starts to preemptive multitask, round-robin giving CPU time to each active thread.  Each time the OS takes the CPU away from one thread and gives it to anther is called context switching.  This is really expensive (in the range of 2000-8000 cpu cycles).  So, the OS is really spending all its time context switching and not running your actions.
If your actions are really asynchronous then the degree of parallelism of the block is irrelevant because something else is doing the parallelising.  But, same issue arises, your asynchronous actions are being executed unchecked and you risk overwhelming the OS in the degree of context switching you introduce.  I would seriously consider not doing asynchronous actions because of this lack of control.
Comment: @PeterRitchie And setting `MaxDegreeOfParallelism` to unbounded doesn't mean that each item will be processed on its own thread, that would indeed be terribly inefficient. What it means is that it will use as many threads as the ThreadPool will let it, which will be around 1 per core most of the time.
Comment: Yes, I'm designing a producer/consumer application with message passing. And I see that Dataflow is the best fit for this (compared to Tasks, ThreadPool etc.). But wanted to know would i still need Async methods within ActionBlocks.
Comment: You can set a level of parallelism with ActionBlock.  I believe it defaults to no parallelism (one block at a time, in order).  See http://msdn.microsoft.com/en-us/library/hh228609.aspx for some details
Comment: I'm afraid I didn't ask my question clear enough. I do set DoP as unbounded (which from my understanding does not limit number of concurrent threads), but would also making code that executes inside the ActionBlock Async speed up processing, or would it be a waste
Comment: @Dimitri My response was much larger than a comment could be, so I've updated the answer.
Comment: Thanks, now it does make a lot more sense.
Comment: I disagree that context switching is such a big problem in this case. Yes, setting the degree of parallelism to more than the number of cores won't make the program any faster, if the computation is CPU-bound. But TPL Dataflow uses ThreadPool by default, which means that each action doesn't get its own thread, most of the time. Instead, the actions are in a queue and the ThreadPool tries to use optimal number of threads to execute them.
Comment: @svick You might be thinking TPL and a ThreadPool scheduler.  ThreadPool defaults to 25 threads per cpu/core--more than enough to cause context-switching issues.  (`ThreadPool.QueueUserWorkItem,` not TPL...)  But, if you tell the TPL that you want a maximum degree of parallelism you're telling it that everything should have its own thread (well, your asking for everything to run concurrently--currently the only way to do that is to give something its own thread).
Comment: @svick in fact, this is documented here: http://msdn.microsoft.com/en-us/library/ff963552.aspx
Comment: @PeterRitchie From the article you linked to: "In most cases, the built-in load balancing algorithms in the .NET Framework are the most effective way to manage these tradeoffs." And TDF does use TPL, which in turn does use ThreadPool, which is why I am thinking about them. ThreadPool doesn't default to 25 threads per core, it starts with 1 thread per core, but this number can increase if the ThreadPool thinks this is appropriate (e.g. when one of the threads blocks).
Comment: @svick what they are saying is that the built-in load-balancing is most effective and that if you do change MDOP you're no longer using the built-in load balancing.  Otherwise the "Arbitrarily increasing the degree of parallelism puts you at risk of processor oversubscription" comment makes no sense.  It's pretty easy to show by simply using `Parallel.ForEach` with the `ParallelOptions` overload.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16392/discussion-between-svick-and-peter-ritchie)
Comment: @svick  Now, the ThreadPool is throttled by the intial number of threads it creates.  It only creates a new thread when needed once every second.  so, if it starts out with 5 thread and all your work can be down within a second, it will never use another thread because it has time to reuse some.  But, if you start action that take longer than a second or two, you'll see the thread pool create more threads, if MDOP is -1, that will be 25*CPU count (but will also take 25*CPU count seconds to get there...
Answer: TPL Dataflow is not suitable for all kinds of parallel processing and it also won't make your code magically faster.
The main idea behind TDF is that you have blocks, which do their work independently. What this means is that the work for each block can be performed on a separate thread, so parallelizing your code using TDF can be very simple in some cases.
This can be especially useful if the code inside a block uses some resource that can't be shared. This way, you can get great utilization of that shared resource, because processing of this block is independent of other blocks.
In general, TDF is most suitable if your code is like a pipeline: an item comes in, gets processed by phase 1, then by phase 2, …, and finally it comes to the output. Although dataflow networks can be much more complicated than that. But you shouldn't try to force this, if what you want to do doesn't fit well with TDF, you're right that you will just complicate your code for no benefit.
Comment: Thanks svick for the input. My scenario is a perfect example of data pipeline where a piece of raw data goes through different stages of processing and is finally persisted to the database.

TPL Dataflow and Async Method Calls


Kernel symbol table mapped into virtual address space - why?

Question: What is /proc/ksyms and /proc/kallsyms, and why is it mapped into a processes address space? What purpose does it serve? Is it used in context switching of the kernel during a system call?
Answer: The Solaris manpage for ksyms(7d) explains this. The data is informative-only, the kernel exposes its currently-used symbol table to kernel debuggers and/or the kernel module loader this way, through /dev/ksyms.
Linux does the same through /proc/kallsyms; /proc/ksyms - if present - is a "traditional" file presenting a subset of the same data (i.e. it's deprecated).
The difference, as usual for Linux/Solaris, is that the Linux version presents text while the Solaris one is binary. You can run nm /dev/ksyms on the Solaris one to get the same type of output you get from cat /proc/kallsyms on Linux.


Publish Windows form application - path too long

Question: I'm trying to publish my application, but the bin\Debug\App.publish\ ect path is too long. I've found out that you can change this default path in web project by doint this c:\shortPath\ in the publish profile file, but i can't figure out how to do it for windows form application, i don't get any file i can edit.  I'm using VS 2012
Thanks in advance!
Answer: Changed Output path in project properties-> build.


How to merge Subquery which returns multiple data for single row of table?

Question: My table contains startDate and endDate columns, so if I take its difference, it has multiple days in between, which I am able to do with one of my custom tables.
select btwnDates from CustomDateTable where btwnDates between '2019-01-5' and '2019-01-7';
2019-01-5
2019-01-6
2019-01-7

Now, I want to merge this output with other columns of the table.
My input table has value:
titles       description       startDate        endDate
homelone     homeloan_policy   2018-06-07      2018-06-09
carlone      carloan_policy    2019-07-18      2019-07-18

Output should be like:
titles       description     startDate        endDate          Day
homelone   homeloan_policy   2018-06-07      2018-06-09     2018-06-07
homelone   homeloan_policy   2018-06-07      2018-06-09     2018-06-08
homelone   homeloan_policy   2018-06-07      2018-06-09     2018-06-09
carlone    carloan_policy    2019-07-18      2019-07-18     2019-07-18

I found a json_extract_array_element_text function does the same but it works for json values also tried for arrays in redshift but no luck.
I am a newbie in redshift and its queries.
Answer: You seem to want a join:
select t.*, cd.btwnDates
from input t join
     customdatetable cd
     on cd.btwnDates >= t.startdate and
        cd.btwnDates >= t.enddate ;


How do I automount a unionfs-fuse filesystem?

Question: I can run the shell command:
unionfs-fuse /changedata=RW:/immutedata=RO -o cow /data

This mounts the filesystem exactly how I want to.  Now I need to incorporate it into the automounter so that it's remounted upon demand.
What I tried in /etc/auto.misc:
/data -fstype=fuse,cow /changedata=RW:/immutedata=RO

What automount --debug -f /etc/auto.master says when I do ls /data:
handle_packet: type = 5
handle_packet_missing_direct: token 19, name /data, request pid 6063
attempting to mount entry /data
lookup_mount: lookup(file): looking up /data
lookup_mount: lookup(file): /data -> -fstype=fuse,cow /changedata=RW:/immutedata=RO
parse_mount: parse(sun): expanded entry: -fstype=fuse,cow /changedata=RW:/immutedata=RO
parse_mount: parse(sun): gathered options: fstype=fuse,cow
parse_mount: parse(sun): dequote("/changedata=RW:/immutedata=RO") -> /changedata=RW:/immutedata=RO
parse_mapent: parse(sun): gathered options: fstype=fuse,cow
parse(sun): invalid location
dev_ioctl_send_fail: token = 19
failed to mount /data

Google reveals little.  Man pages are rather empty on the incorporation of this filesystem.
Maybe I should just put it in /etc/fstab and ask users to remount?
Comment: @Sridhar-Sarnobat I have provided an answer that works :)
Comment: 4 years on and I can't find an example on the web.
Answer: I know it is too late to answer but adding the following to /etc/fstab in Ubuntu works,
/dir/A=RW:/dir/B=RO /dir/my-union fuse.unionfs-fuse allow_other,cow,use_ino  0   0

Comment: I specifically am trying automount since some of this stuff is remote the mount can go stale and/or missing for a variety of reasons
Comment: Where should that line be written to? [edit] your answer to amend it!
Answer: automounting unionfs with autofs
TLDR: create the following entry in /etc/auto.misc and include it in your etc/auto.master (as outlined below).
data    -fstype=fuse,cow,allow_other :unionfs\#/changedata=RW\:/immutedata=RO

Bonus: Creating a unionfs automount on top of nfs automounts (to illustrate how to properly configure autofs)
When using NFSv4, enable IMAPD in /etc/default/nfs-common
NEED_IDMAPD=yes

If you want autofs to always create directories for your mounts, enable browse_mode in /etc/autofs.conf
browse_mode = yes

Now to the core part: in your /etc/auto.master add the following lines
# automount all nfs volumes under /nfs and misc filesystems under /mnt
/nfs   /etc/auto.nfs
/mnt   /etc/auto.misc

autofs will mount all filesystems specified in /etc/auto.nfs under /nfs/<mount> and all filesystems specified in /etc/auto.misc under /mnt/<mount>.
In my /etc/auto.nfs I have the following (example) entries:
# FileServer: nfs data configuration
data01 -fstype=nfs4,ro,soft,intr,rsize=8192,wsize=8192,nosuid,tcp,allow_other 192.168.3.100:/mnt/data01
data02 -fstype=nfs4,ro,soft,intr,rsize=8192,wsize=8192,nosuid,tcp,allow_other 192.168.3.100:/mnt/data02
data03 -fstype=nfs4,ro,soft,intr,rsize=8192,wsize=8192,nosuid,tcp,allow_other 192.168.3.100:/mnt/data03
data04 -fstype=nfs4,ro,soft,intr,rsize=8192,wsize=8192,nosuid,tcp,allow_other 192.168.3.100:/mnt/data04
data05 -fstype=nfs4,ro,soft,intr,rsize=8192,wsize=8192,nosuid,tcp,allow_other 192.168.3.100:/mnt/data05

And in my /etc/auto.misc I added the following entry for unionfs
# unionfs mount of all /nfs/data* mounts into /mnt/data
data    -fstype=fuse,allow_other,use_ino,ro,noatime :unionfs\#/nfs/data01=RO\:/nfs/data02=RO\:/nfs/data03=RO\:/nfs/data04=RO\:/nfs/data05=RO

Make sure all files have a permission of 644 ( adjust with chown 644 /etc/auto.{nfs,misc} if necessary)
Then you can enable autofs and restart the service.
# reload autofs to enable all shares
systemctl enable autofs
systemctl restart autofs

You should now be able to do a ls /mnt/data


How to use HighChart.getOption() with react-native-highchart

Question: I am using highchart on react-native with this library. I have created simple activity gauge component from high chart official site. Here is the code of component.
import ChartView from 'react-native-highcharts';
import React, { Component } from 'react';

export default class Speedometer extends Component {

    render() {
      var Highcharts='Highcharts';
      var conf={

     chart: {
            type: 'solidgauge',
            height: '110%',

        },
        ....
        series: [{
            name: 'Move',
            data: [{
                color: Highcharts.getOptions().colors[0],
                radius: '112%',
                innerRadius: '88%',
                y: 80
            }]
        }, {
            name: 'Exercise',
            data: [{
                color: Highcharts.getOptions().colors[1],
                radius: '87%',
                innerRadius: '63%',
                y: 65
            }]
        }, {
            name: 'Stand',
            data: [{
                color: Highcharts.getOptions().colors[2],
                radius: '62%',
                innerRadius: '38%',
                y: 50
            }]
        }]
    };

      const options = {
          global: {
              useUTC: false
          },
          lang: {
              decimalPoint: ',',
              thousandsSep: '.'
          }
      };

      return (
        <ChartView style={{height:300}} more guage config={conf} options={options}></ChartView>
      );
    }
}

When i render this component on my screen i get the error
TypeError: TypeError: TypeError: TypeError: undefined is not a function (evaluating 'Highcharts.getOptions()')

How can i use getOptions or colors or theme or other variable with highchart inside react-native component.
Comment: you still need to `import Highcharts from 'highcharts'` - the other is a wrapper.
Comment: after the import i am getting this error `TypeError: undefined is not a function (evaluating '_highcharts.default.getOptions()')`
Comment: `REMEMBER to declare the variable Highcharts='Highcharts'` - this has overwritten it. dunno what it's supposed to do when it assigns it to a string...
Comment: you mean i need to add the `import Highcharts from 'highcharts'` and `Highcharts='Highcharts'` both ?
Comment: no, not tried the react native one but in react web port, you need to only do the import, not the `var Highcharts = 'Highcharts'`.
Comment: it is recommended by the library that i need to declare highcharts in this way.. any way still not working
Comment: Hi Ahsan Sohail, I think that your problem is closely related to `react-native-highcharts` library, so you should ask this question directly on their github.
Answer: You need to understand a few things here:

react-native-highcharts library create a dynamic html content and then inject into webview. Whatever is passed in the config props of ChartView is converted in to string content after flattenObject function inside the library.
If you look at the starting code of html content inside the library you would see that some javascript dependencies has been included and one of them is highcharts. This highcharts library will make the variable Highcharts in the local scope of javascript inside webview.
You are getting this error because React thinks that Highchart must be define somewhere in the component and define Highchart as a string, so if you access string.function it will throw error.
(Solution) you have two option here either to tweak the code inside the library and make it to accept flat string as props and pass this string directly to the ChartView, or you can create dummy Highchart object inside your root component to make the React stop complaining about the Highchart object. Once this object is passed through CharView highchart would be available in javascript scope inside webview and BOOM you Charts are loading.

Now you know the problem you can come up with more solutions. Hope this helps!


How to show that $\lim\limits_{t \rightarrow \infty} S(t) = \Lambda/\mu$?

Question: Can someone here help me establish that $\lim\limits_{t \rightarrow \infty} S(t) = \Lambda/\mu$,
given that:
$\frac{dS}{dt}=\Lambda-\mu S-\beta \frac{S}{N}(H+C+C_1+C_2)-\tau \frac{S}{N}(T+C)$
$N(t)=S(t)+H(t)+C(t)+C_1(t)+C_2(t)$
$\Lambda,\beta,\tau,\mu > 0$
$\text{As} \ \ t \rightarrow \infty, \ T,H,C,C_1,C_2 \rightarrow 0?$

My attempt:
$\frac{dS}{dt}=\Lambda-\mu S-\beta \frac{S}{N}(H+C+C_1+C_2)-\tau \frac{S}{N}(T+C) \leq \Lambda-\mu S.$ Clearly if $S > \Lambda/\mu,$ then $dS/dt<0.$ Since $dS/dt$ is bounded by $\Lambda-\mu S,$ a standard comparison theorem can be used to show that $S(t) \leq S(0)e^{-\mu t} + \frac{\Lambda}{\mu}(1-e^{-\mu t}).$ In particular, $S(0) \leq \frac{\Lambda}{\mu} \Rightarrow S(t) \leq \frac{\Lambda}{\mu}.$
Also, since $T,H,C,C_1,C_2 \rightarrow 0 \ \ \text{as} \ \ t \rightarrow \infty,$
$$(\forall \delta>0)(\exists T>0)\left(t \geq T \implies \left|-\beta\frac{S}{N}(H+C+C_1+C_2)-\tau\frac{S}{N}(T+C)\right|<\frac{\delta}{2}\right).$$ If we take $S \geq \frac{\Lambda-\delta}{\mu},$ then $\Lambda-\mu S \leq \delta.$
Hence $\frac{dS}{dt}=\Lambda-\mu S-\beta \frac{S}{N}(H+C+C_1+C_2)-\tau \frac{S}{N}(T+C) \leq \frac{3\delta}{2}.$
If we take $S \leq \frac{\Lambda+\delta}{\mu},$ then $\Lambda-\mu S \geq -\delta.$
Hence $\frac{dS}{dt}=\Lambda-\mu S-\beta \frac{S}{N}(H+C+C_1+C_2)-\tau \frac{S}{N}(T+C) \geq -\frac{3\delta}{2}.$

Question: How do I conclude?
Answer: One can synthetize the relevant assumptions as the fact that $S'(t)=\Lambda-\mu(t)S(t)$ where $\mu(t)\to\mu$ when $t\to\infty$ and $\mu\gt0$.
For every $\nu\gt\mu$, there exists some $t_\nu$ such that $\mu(t)\leqslant\nu$ for every $t\geqslant t_\nu$. Then $S'(t)\geqslant\Lambda-\nu S(t)$ for every $t\geqslant t_\nu$. The RHS is positive for every $S(t)\lt S_\nu$, where $$S_\nu=\Lambda/\nu,$$ hence, if $S(t)\lt S_\nu$ for some $t\geqslant t_\nu$, then the function $t\mapsto S(t)$ is increasing until $S(t)\geqslant S_\nu$ hence $\liminf\limits_{t\to\infty}S(t)\geqslant S_\nu$.
Likewise, for every positive $\nu\lt\mu$,  $\limsup\limits_{t\to\infty}S(t)\leqslant S_\nu$.
Thus, $S_{\mu+\varepsilon}\leqslant\liminf\limits_{t\to\infty}S(t)\leqslant\limsup\limits_{t\to\infty}S(t)\leqslant S_{\mu-\varepsilon}$ for every positive $\varepsilon\lt\mu$. When $\varepsilon\to0^+$, $S_{\mu+\varepsilon}\to S_\mu$ and $S_{\mu-\varepsilon}\to S_\mu$, hence $\liminf\limits_{t\to\infty}S(t)=\limsup\limits_{t\to\infty}S(t)=S_\mu$, that is, $\lim\limits_{t\to\infty}S(t)=S_\mu$.
Comment: Sure, since the lower bound on the liminf holds for every $\nu\gt\mu$ and the upper bound on the limsup holds for every $\nu\lt\mu$.
Comment: Finish what? First, my answer is complete. Second, the proof in your comment is absurd.
Comment: ((Comment by the OP deleted.))
Comment: Before "thus", one establishes a lower bound on the liminf and an upper bound on the limsup. After "thus", one puts them together. Thus, "thus". (And imbecility is off-topic here.)


Issues with multiple AJAX calls requesting JSONP

Question: I have a code which I request data from a geoserver and display geoJSON on a map. To this request I'm using three AJAX calls like the following:
//JSON request
            var WFSLayer1 = null;
            var ajax = $.ajax({
                url: "http://localhost:8080/geoserver/PastDenver/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=PastDenver:dataset3&maxFeatures=300&outputFormat=text/javascript&format_options=callback:getJson",
                dataType: 'jsonp',
                jsonpCallback: 'getJson',
                success: function (response) {
                    WFSLayer1 = L.geoJson(response, {
                        style: function (feature) {
                            return {
                                weight: 5,
                                color: '#6e7ce8',
                                weight: 2,
                                opacity: 1,
                                dashArray: '3',
                                fillOpacity: 0.7,
                            };
                        },
                        onEachFeature: function (feature, layer) {
                            popupOptions = {
                                maxWidth: 200
                            };
                            if (feature.properties.name !== null) {
                                layer.bindLabel(feature.properties.name, popupOptions, {
                                    noHide: true
                                });
                            };
                            layer.bindPopup("Name: " + feature.properties.name + "
Description: " + feature.properties.descr + "
Floors: " + feature.properties.floors + "
Material: " + feature.properties.material);
                            layer.on({
                                click: zoomToFeature
                            })
                        }
                    }).addTo(dataset1);
                }
            });

            var WFSLayer2 = null;
            var ajax = $.ajax({
                url: "http://localhost:8080/geoserver/PastDenver/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=PastDenver:dataset1&maxFeatures=300&outputFormat=text/javascript&format_options=callback:getJson",
                dataType: 'jsonp',
                jsonpCallback: 'getJson',
                success: function (response) {
                    WFSLayer1 = L.geoJson(response, {
                        style: function (feature) {
                            return {
                                weight: 5,
                                color: '#e31424',
                                weight: 2,
                                opacity: 1,
                                dashArray: '3',
                                fillOpacity: 0.7,
                            };
                        },
                        onEachFeature: function (feature, layer) {
                            popupOptions = {
                                maxWidth: 200
                            };
                            if (feature.properties.name !== null) {
                                layer.bindLabel(feature.properties.name, popupOptions, {
                                    noHide: true
                                });
                            };
                            layer.bindPopup("Name: " + feature.properties.name + "
Description: " + feature.properties.descr + "
Floors: " + feature.properties.floors + "
Material: " + feature.properties.material);
                            layer.on({
                                click: zoomToFeature
                            })
                        }
                    }).addTo(dataset2);
                }
            });

            var WFSLayer3 = null;
            var ajax = $.ajax({
                url: "http://localhost:8080/geoserver/PastDenver/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=PastDenver:dataset2&maxFeatures=300&outputFormat=text/javascript&format_options=callback:getJson",
                dataType: 'jsonp',
                jsonpCallback: 'getJson',
                success: function (response) {
                    WFSLayer3 = L.geoJson(response, {
                        style: function (feature) {
                            return {
                                weight: 5,
                                color: '#14e324',
                                weight: 2,
                                opacity: 1,
                                dashArray: '3',
                                fillOpacity: 0.7,
                            };
                        },
                        onEachFeature: function (feature, layer) {
                            popupOptions = {
                                maxWidth: 200
                            };
                            if (feature.properties.name !== null) {
                                layer.bindLabel(feature.properties.name, popupOptions, {
                                    noHide: true
                                });
                            };
                            layer.bindPopup("Name: " + feature.properties.name + "
Description: " + feature.properties.descr + "
Floors: " + feature.properties.floors + "
Material: " + feature.properties.material);
                            layer.on({
                                click: zoomToFeature
                            })
                        }
                    }).addTo(dataset3);
                }
            });

Once requested each JSON is assigned to a specific dataset.
Now my problem: every time I open the page everything work just fine, but sometimes when I refresh the page everything breaks apart. For example some times neither data is displayed, some times data ends up on the wrong dataset. When I get this bug I get the following message in the console:
ows?service=WFS&version=2.0.0&request=GetFeature&typeName=PastDenver:dataset1&maxFeatures=300&outpu…:1 Uncaught TypeError: undefined is not a function

On my research it seems that this type of error is quite common when running multiple AJAX calls. What I don't understand is why this error does not occur 100% of the time. What type of techniques can be used to fix it? I heard of Deffered Objects but could not apply it on my code, my expertise level on this is far from great.
Here is the full code
Although this may tend towards a GIS question I believe that this type of issue is more related to ordinary jQuery and Asynchronous calls.
Answer: From the jQuery documentation

jsonpCallback
Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.

The function is probably undefined because jQuery is probably cleaning up after itself and deleting the function after it is called.
Remove jsonpCallback: 'getJson', to let jQuery generate the function names itself, then you won't overwrite your previous functions (and delete them before they get called a second time).
Comment: Wow, your response quite fixed my issue! First I deleted all the callbacks and nothing worked, then I just created unique values for each of my callback. This seems to have fixed everything!  But for the records: How do I allow jQuery to create its own names?
Comment: @RicardoOliveira — By not telling it you want a specific name, as per the last paragraph of the answer.


Android layout_weight iframe and scroll

Question: sorry for my poor english in advance
I have a design problem on android studio.
I used multiples devices (From version 8 to 10) and it works fine, and one device (version 6) which has a different output (you can check my screens below)wrong display click here
good display click here
unfortunately i don't know why it goes wrong, it might be a problem with layout_weight, in my code i use a Frame layout to switch out between differents Views, it looks like the Framelayout doesn't take any height (i want it to take the available space)
Thanks in advance

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/choose_model"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0">

        <Spinner
            android:id="@+id/select_your_model"
            android:layout_width="43dp"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/text_model_title"
            android:layout_alignParentEnd="true" />

        <TextView
            android:id="@+id/text_model_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="5dp"
            android:layout_marginTop="20dp"
            android:text="@string/choose_mod"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/Spinner_model_preference_text"
            android:layout_width="160dp"
            android:layout_height="26dp"
            android:layout_alignTop="@+id/select_your_model"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="45dp"
            android:gravity="center"
            android:textColor="@android:color/darker_gray"
            android:textSize="16sp"
            android:textStyle="bold" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="15dp"
        android:layout_weight="1"
        android:background="#FAFAFA">

        <FrameLayout
            android:id="@+id/Frame_layout_preferences_setting"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp" />
    </ScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_weight="0">

        <Button
            android:id="@+id/save_user_preferences"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:text="@string/save" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view_preferences_model"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" />

        <View
            android:id="@+id/divider2"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_above="@+id/recycler_view_preferences_model"
            android:layout_alignParentStart="true"
            android:background="?android:attr/listDivider" />
    </RelativeLayout></LinearLayout>

Comment: what is the wrong with your picture?
Comment: there is nothing displayed (ahead of the save button you should see the content of the good picture)
Comment: you xml  is contened in activity or fragment
Comment: it's contained in a fragment
Answer: You have the problem, because you have a FrameLayout inside a fragment. I recommend the next
If you only want to have a view  and it has different content, you can have a activity

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0">

    <Spinner
        android:id="@+id/select_your_model"
        android:layout_width="43dp"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/text_model_title"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/text_model_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="5dp"
        android:layout_marginTop="20dp"
        android:text="@string/choose_mod"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/Spinner_model_preference_text"
        android:layout_width="160dp"
        android:layout_height="26dp"
        android:layout_alignTop="@+id/select_your_model"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="45dp"
        android:gravity="center"
        android:textColor="@android:color/darker_gray"
        android:textSize="16sp"
        android:textStyle="bold" />
</RelativeLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginTop="15dp"
    android:layout_weight="1"
    android:background="#FAFAFA">

    <FrameLayout
        android:id="@+id/Frame_layout_preferences_setting"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp" />
</ScrollView>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_weight="0">

    <Button
        android:id="@+id/save_user_preferences"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="@string/save" />
</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.2">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view_preferences_model"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

    <View
        android:id="@+id/divider2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_above="@+id/recycler_view_preferences_model"
        android:layout_alignParentStart="true"
        android:background="?android:attr/listDivider" />
</RelativeLayout></LinearLayout>

Replace the FrameLayout with an imageview
if you want  to have fragments.  i recommend the next
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Call the fragment in activity

getSupportFragmentManager().beginTransaction()
                    .replace(R.id.main_container, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

Comment: i'll try to use an activity then, but i don't understand the problem of using fragment, i'm just adding views dynamically into my FrameLayout
Comment: Because you have a FrameLayout  inside a fragmen, it is not correct, because the fragment must be inside an activity

Android layout_weight iframe and scroll


Anode Rod replaced but short on hot water

Question: We just had our anode rod replaced on our 8 year old gas water heater. Water starts very hot but cools down quickly. Able to put hand under it after a couple minutes without being too hot when running bath. This is with tap turned to hottest.
What could the problem be?
Comment: What is the size of your water heater unit Gallons. Your thermostat might not be working correctly.
Comment: @damon this is a gas water heater.
Answer: Check the dip tube on the cold inlet.
The dip tube directs the incoming cold water down to the flame, if the dip tube is missing or fell off then the cold water coming in stays on top of the hot water and you're getting the cold water from the top and the hot water stays at the bottom and not coming up into the pipes.
Comment: we like more than a 1 line answer and can you explain what to check on the dip tube and how this would affect the water heater?
Answer: You said you replaced your anode but you did not mention anything about flushing your tank. If there is a large amount of sediment build up from the old rod and especially if on a well there can be a huge amount if stuff built up in the bottom of the tank that needs to be flushed using the bottom drain on the heater. I usually turn the gas valve to pilot for safety while flushing gas water heaters. If after cleaning the tank out you still have issues and the burner looks good the thermostat would be next on my list. If the flame on the burner looks uneven that may need to be cleaned.


Minimizing $R_1^2+R_2^2$ subject to $RT=I$

Question: $$\begin{array}{ll} \text{minimize} & R_1^2+R_2^2\\ \text{subject to} & RT=I\end{array}$$
where $R\in\mathbb{R^{2\times2}}$, $T\in\mathbb{R^{2\times2}}$, $R=\begin{bmatrix}R_1 & R_2\\R_3 &R_4\end{bmatrix}$, $T=\begin{bmatrix}T_1 & T_2\\T_3 &T_4\end{bmatrix}$.
My attempt: I know that if $RT=I$ then $\min R^{}R^*=(T^*T^{})^{-1}$. Then $R_1^2+R_2^2 \geq (T^*T^{})^{-1}_{1\times 1}$, where $(T^*T^{})^{-1}_{1\times1}$ is the first diagonal element of $(T^*T^{})^{-1}$. Can we get tighter bound?
Comment: @Lee if $RT=I$ then both $R,T$ are invertible.
Comment: Do you know if $T$ is invertible?
Comment: @MichaelMcGovern actually no, but I saw that I have divided by $\det(T)$, so my attempt works only for invertible $T$
Comment: What is $T^*$ in this problem?
Comment: it is transpose
Comment: thanks, now I get it. Then indeed $(T^*T^{})^{-1}_{1\times 1}=(T_2^2+T_4^2)/\det(A)$ is the tightest bound
Comment: $(T^*T^{})^{-1}_{1\times 1}=(T_2^2+T_4^2)/\det(T)$
Answer: We can make $R_1^2 + R_2^2$ arbitrarily close to $0$.  To show this, consider the identity, for any $x \not= 0$,
$$\begin{bmatrix}0 & 1/x \\ 1/x &0 \end{bmatrix}\begin{bmatrix}0 & x \\ x & 0\end{bmatrix} = I$$
Comment: Maybe I misunderstand.  Is $T$ fixed and we are minimizing $R_1^2 + R_2^2$ in terms of fixed $T_i$? Or do we have control over $T$? I interpreted the second way, in which case I'm saying $0 < R_1^2 + R_2^2 < \epsilon$ is achievable for every $\epsilon > 0$, and it doesn't get any tighter than that
Comment: this is same as my attempt: $R_1^2+R_2^2 \geq (T^*T^{})^{-1}_{1\times 1}$, where you have reached equality. But I believe there must be even tighter bound
Comment: the first way is correct, sorry for not mentioning it in the question. We need to minimize $R_1^2+R_2^2$ in terms of fixed $T$.
Comment: So I think I will close this question and mark your answer as accepted. Thanks for @Lee for his hint as well. The lower bound is $(T^*T^{})^{-1}_{1\times 1}=(T_2^2+T_4^2)/\det(T)$


how to add default text to an input field in a form in WP

Question: I am using a plugin in WP that generates a form based on input in the admin area. I have five fields that are set to url validation and such types appear in a form with a second field for optional link text, meaning if the user enters "http://stackoverflow.com" in the first field they have the option to type "Stackoverflow" in the second, and that is what will appear as the link text in the resulting listing in the web site directory. If the user leaves this field empty, the plugin will insert the url from the first field to fill it.
I have set these links to be styled as buttons, thus I need to control what appears on them so they are the right size. I want to add specific default text to each of these five fields, but I can't edit the form because it is generated dynamically.
One of these input fields for optional text is coded thus:
<code><input type="text" id="wpbdp-field-12-title" name="listingfields[12][1]" class="intextbox" value="" placeholder="">
</code>
Is there a way to use css or javascript or magic to insert text in the fields so it is submitted with the form? I want one, for example, to have the default text "Official Website" and other to read "Facebook" and so forth.
BTW, this field will be hidden by css so the form filler doesn't alter it. I just need these fields pre-filled to save labor by the admin.
Thank you, all.
Answer: Are you sure there is no way to edit the input in the plugin you're using? If you wanted you can change it after the page load with the jQuery included in WP.
CODE
<code>$(function() {
    $('input#wpbdp-field-12-title').attr('value','your additional value text');
});
</code>
this is really not a full proof way of doing it as the plugin you use will change the ID of the field if you edit it in the future. Maybe look into using a different one or making your own php form.
EDIT
You could also have inputs with values predefined that are hidden and submitted along with it. I'm not sure if thats a possiblity for you.
Comment: Where would I put this code you recommend? It looks like what I need.
Comment: Put that code on the page where the form appears like this: ``. You can put that in  head or in the body right above the `` tag, depending where you have access to inject it into your WP templates.
Comment: @Josh KG yep that's pretty much how, are you using a custom template?
Comment: It is a purchased template, but the template isn't the issue. Now I have also found that when viewing the page with the form that the form's html is not visible in code view. idk how that is possible. So, while I expect the above solution would work, it doesn't because of this. The form works in that you click a menu link to the form, then pick a category for your event, then click the continue button, which takes you to the main form, which is where these fields are displayed. When I view the source I see only the html for the first page for category selection. I've written to the programmer.
Comment: Finally got around to working on this again. My previous comment about the form code being not visible was in error, but the suggested code isn't working. It shows up in the head area, but not working. One of the fields I want to have filled is coded thus:
``
and for it's line in the script I wrote this:
`$(function() {
    $('input#wpbdp-field-10-title').attr('value','Buy Tickets');
});` Any ideas? Thanks.
Comment: The whole of my inserted script is this: ``
Comment: If anyone can help with getting this to work it would be fantastic. It's very important to get this resolved.
Comment: The page it is needed for is at [HERE](http://nextinthewest.com/next-in-the-west-calendar/?action=submitlisting)


Partial sum of exponential series strictly increases after certain step

Question: While trying to show that partial exponential series evaluated at two different values are strictly increasing provided that sufficient number of terms are applied I stuck at a problem. Given two rational numbers $p,q \in \mathbb{Q}$ with $p<q$, find  $n,k \in \mathbb{N}$ s. t. the following holds:
$$ \sum_{l=1}^{n} \frac{q^l - p^l}{l!} - \frac{|q|^{n+1}}{(n+1)!} - \frac{|p|^{n+1}}{(n+1)!} > \frac{1}{k}$$
The first term is the difference between two partial sums and the last two terms indicate the half-bounds in which the partial sums are located after $n$-th step. The best what I expect is a closed-form expression, and the least is an algorithm whose number of steps may be estimated beforehand. I pursue a routine which I might implement in a computer that would calculate those two numbers.
I also think it is possible to show that the inequality may be turned into this simplified one (provided $n$ is even):
$$ \sum_{l=1}^{n} \frac{q^l - p^l}{l!} > \frac{1}{k} $$
It follows from the fact  that for even $n$:
$$ \sum_{l=0}^{n-g-1} \frac{p^l}{l!} > \sum_{l=0}^{n-g-3} \frac{p^l}{l!} $$
with $n \geq |p| + g + 1$. It is done by subtracting maximal values of bottom margins in consecutive terms.
Answer: For the sake of simplicity consider a function $e_n(x)=\sum_{l=0}^{n} \frac{x^l}{l!}$. By Taylor formula in Lagrange form, there exist numbers $0<\theta_p,\theta_q<1$ such that $$e^p-e_n(p)= \frac{e^{p\theta_p }p^{n+1}}{(n+1)!}$$ and $$e^q-e_n(q)=\frac{e^{q\theta_q}q^{n+1}}{(n+1)!}.$$
Put $\Delta=e^q-e^p$, pick $1/k\le\Delta/3$, and $n$ such that both $\frac{|p|^{n+1}}{(n+1)!}$ and $(e^q+1)\frac{|q|^{n+1}}{(n+1)!}$ are not greater than $\Delta/3$ (here you can use Stirling approximation for $n!$, climing that there exists a number $0<\theta(n)<1$ such that $n!=\sqrt{2\pi n}\left(\frac ne\right)^n e^{\frac{\theta(n)}{12n}}$). Then $$ e_n(q)-e_n(p) - \frac{|q|^{n+1}}{(n+1)!} - \frac{|p|^{n+1}}{(n+1)!} =$$ $$
e^q-e^p-\frac{e^{q\theta_q}q^{n+1}}{(n+1)!}+ \frac{e^{p\theta_p}p^{n+1}}{(n+1)!}-
\frac{|q|^{n+1}}{(n+1)!} - \frac{|p|^{n+1}}{(n+1)!}>$$ $$\Delta-
(e^q+1)\frac{|q|^{n+1}}{(n+1)!}- \frac{|p|^{n+1}}{(n+1)!}\ge\frac{\Delta}{3}\ge \frac{1}{k}.$$
Comment: It seems that the function $e_n(x)$ is monotone when $n$ is odd and is positive when $n$ is even, and this can be easily proved by induction.
Comment: @ValerySaharov It seems so. Do you need a proof?
Comment: @ValerySaharov Do you mean "how to prove the monotonicity of the function $e_n(x)$?"


Which material for a sink bucket?

Question: I'm thinking about making a small sink for my DIY lab. Since there is no running water or drain, I was thinking about something similar to a camping sink like this one.
I'd make some modifications (e.g. using a ceramic basin rather than a plastic one, since it will be fixed).
Now, for the water reservoir any container is fine, but I have doubts about the material of the drain plumbing and container. I'd usually use it to wash the hands (so only water + soap), but I'd also occasionally use it to wash tools and items, which can include also chemicals (e.g. ferric chloride to etch PCBs).
What material is usually used in these cases, and what are its limitations? (e.g. this plastic is ok for acids but when used with gasoline breaks).
For instance I found containers and pipes in PE or PVC or PP; is any of these materials suitable?
Comment: I'm voting to close this question because it isn't about home improvement.
Comment: Gasoline? In a sink? Inside your house? Darwin award coming up.
Comment: *DIY lab. Since there is no running water or drain* - I'm guessing this is in a shed or detached garage.
Comment: Hello, and welcome to Home Improvement. Unfortunately, this really isn't about home improvement. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: @Ecnerwal the "gasoline" part was because I know that some plastic containers are not suitable for gasoline storage (because gasoline can "melt" them). That was just an example to show the kind of reply I'd like to receive: suggested material and associated limitations. I want to assure you, though, that no gasoline will be put in that storage container; I used that as an example because it is the first example of "not suitable plastic" that came to my mind
Comment: @DanielGriscom can you further explain why you think this is not suitable? Is it because it is not for a house but rather for a (DIYer's) lab? I think a garage lab is part of the house, this is definitely an improvement and the question is about the materials to use to get this done. TBH, though, I came to this website because of the "diy" name in it, and I did not consider the "Home Improvement", but after reading the page you linked I'm more confident that this is the right place to ask. If not, can you please point me to the more appropriate stackexchange site to ask?
Comment: You're asking about appropriate materials for a lab sink, which is either choosing materials, or non-home-related, neither of which is on-topic.
Comment: poly pro would likely be the most durable option, but if solvents are watered down it shouldn't make a lot of diff.
Comment: @DanielGriscom Believe me when I'm saying I'm not trying to be a troll, but I'm genuinely asking to understand how to best use this website. This said, in the page you linked there is a box saying "Ask about ..." "Which tools, materials, and best practices for home improvement task". So asking for materials is definitely on topic here. As for the usage, this is not for a professional lab, but for a DIYer's lab. Would it change if I say it will be my garage's sink?
Comment: @dandavis I suppose you mean Polypropylene. Do you think it is better than Polyethylene for this purpose?
Comment: And, it's about shopping, which is also off-topic. Also note that I was only one of five that thought this was off-topic.
Answer: #1- Plastic Buckets are cheap. Use one 'til it is no longer usable, buy three.  (My favorite are the Lowe's buckets. I have put all kind of nasty stuff in them.)
I lived for many years with a water jug on a shelf above a double sink with  plastic buckets under each bowl (and a camp toilet in the bathroom).  The key  to remember is LOOK UNDER THE SINK to see how full the buckets are.
A small galvanized trash can would hold more liquid. I am not sure how water tight they are. I have had ones that held water. Maybe a stainless steel one from a restaurant supply house would be a good investment.
A galvanized bucket would be a good choice.

Photo courtesy of It's still life No affiliation.
Comment: Thank you for your answer. I'd avoid metal because of rust and corrosion, so I'd go with plastic.
Since not all plastics are made equal, do you think some material has advantages over the others (usually I find around PP, PE or HDPE containers)

Which material for a sink bucket?


Manifest merger failed with multiple errors, see logs (PayUMoney integration)

Question: I am trying to integrate PayUMoney payment gateway in my app. The very first line of the integration documentation says to add -
compile 'com.payumoney.sdkui:plug-n-play:1.0.0'
in my app-level build.gradle file dependecies. But as soon as I do this i encounter an error -
Manifest merger failed with multiple errors, see logs also the line -
implementation 'com.android.support:appcompat-v7:26.1.0'
show the following error -
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 26.1.0, 23.2.1. Examples include com.android.support:animated-vector-drawable:26.1.0 and com.android.support:cardview-v7:23.2.1 less... (Ctrl+F1)
There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)

Help me resolve this issue.
Below is my build.gradle(Module:app) code -
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.learnturtle.payucheck"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.payumoney.sdkui:plug-n-play:1.0.0'
}

Comment: I also faced this error while integrating a payment gateway in my app and it turned out that the gateway needed some classes to be ignored in proguard file. So you can check the documentation of payu and confirm that you are not missing something there.
Comment: I feel the documentation is quite brief..
Comment: https://www.payumoney.com/dev-guide/mobilecheckout/android.html
Answer: Use the latest dependency
compile 'com.payumoney.sdkui:plug-n-play:1.5.0'

and change minSdkversion
minSdkVersion 20

Answer: Use the latest dependency
compile 'com.payumoney.sdkui:plug-n-play:1.6.0'

and change minSdkversion
minSdkVersion 20

and in Manifest add this
tools:replace="android:allowBackup,android:usesCleartextTraffic"

Answer: check gradle console in this case , maybe there is manifest issue / values which is already present in the support libs, or sdk version compatibiliy issue, you will get the whole detail of the error.
Answer:
Compile with following sdk

 implementation 'com.payumoney.sdkui:plug-n-play:1.5.0'

in same app label gradle

 minSdkVersion 20

Open manifest and make change inside application tag
tools:replace="android:allowBackup"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:ignore="GoogleAppIndexingWarning"
    tools:replace="android:allowBackup">

it worked for me fine.


google analytics api with python

Question: http://www.marinamele.com/use-google-analytics-api-with-python
Hi, I followed this tutorial to try access the google analytics api with python.
the code is like this:
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse

CLIENT_SECRETS = 'client_secrets.json'

# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message='%s is missing' % CLIENT_SECRETS
    )

# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'

def prepare_credentials():
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    # Retrieve existing credendials
    storage = Storage(TOKEN_FILE_NAME)
    credentials = storage.get()
    # If no credentials exist, we create new ones
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)
    return credentials

def initialize_service():
    # Creates an http object and authorize it using
    # the function prepare_creadentials()
    http = httplib2.Http()
    credentials = prepare_credentials()
    http = credentials.authorize(http)
    # Build the Analytics Service Object with the authorized http     object
    return build('analytics', 'v3', http=http)

if __name__ == '__main__':
    service = initialize_service()

After I run the python code, it gave me a new browser window and ask me the permission to access google analytics data, after I click allow, it shows: no data received.
What wrong did I do?
Thanks
Comment: did you create ID ???? and input that in your code ?
Comment: No idea about that tutorial, but if you want to access the API via a script (without browser authentication) you can use Google's own Python example: https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py .
Comment: Thanks a lot guys, I found the reason that my manager edited the wrong permission for my account.
Answer: Actually you did nothing wrong there:
The new browser window is only for the credential-checks.
You just have initalized an object, but did not call any reports.
You will need something like:
service.reports().batchGet(body={'reportRequests' : config['reportRequests']}).execute()

to get data from analytics.
In this example:
config['reportRequests'] =
"reportRequests": [
    {
    "viewId": "SOME FANCY VIEW ID",
    "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
    "metrics": [{"expression": "ga:pageviews"}, {"expression":"ga:sessions"}],
    "dimensions": [{"name": "ga:adContent"},{"name":"ga:landingPagePath"}],
    "dimensionFilterClauses":
    [
     {
    "filters": [{"dimensionName": "ga:source", "expressions":"SOME UTM-SOURCE"}]
     }
    ]
    }]

google analytics api with python