XSL / Schemas beginners question

Question: Been using XML for ages now for data storage & transfer, but have never had to validate or transform it. Currently starting a new project and making some design decisions and need to know some rudimentary things about XSL & Schemas.
Our XML is like this (excuse the boring book example :) ):
<Books>
  <Book>
    <ID>1</ID>
    <Name>Book1</Name>
    <Price>24.??</Price>
    <Country>US</Country>
  </Book>
  <Book>
    <ID>1</ID>
    <Name></Name>
    <Price>24.69</Price>
  </Book>
</Books>

Our requirements:

Transformation
a) Turn "US" into United States
b) if Price > 20 create a new lLement <Expensive>True</Expensive>
I'm guessing this is done with XSLT, but can anyone give me some pointers on how to achieve this?
Validation
a) is ID an integer, is Price a float (the most important job to be honest)
b) Are all tags filled, e.g. the name tag is not filled (2nd most important)
c) Are all tags present, e.g. Country is missing for book 2
d) [Probably tricky] Is the ID element unique through all books? (nice to have)

From what I have read this is done with a Schema or Relax NG, but can the results of the validation be outputted to a simple HTML to display a list or errors?
e.g.
Book 1: Price "Price.??" is not float
Book 2: ID is not unique, Name empty, Country missing
Or would it be better do do these things programatically in C#?
Thanks.
Answer: This stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:m="map"
exclude-result-prefixes="m">
    <xsl:key name="kTestIntID" match="Book"
             use="number(ID)=number(ID) and not(contains(ID,'.'))"
             m:message="Books with no integer ID"/>
    <xsl:key name="kTestFloatPrice" match="Book"
             use="number(Price)=number(Price) and contains(Price,'.')"
             m:message="Books with no float Price"/>
    <xsl:key name="kTestEmptyElement" match="Book"
             use="not(*[not(node())])"
             m:message="Books with empty element"/>
    <xsl:key name="kTestAllElements" match="Book"
             use="ID and Name and Price and Country"
             m:message="Books with missing element"/>
    <xsl:key name="kBookByID" match="Book" use="ID"/>
    <m:map from="US" to="United States"/>
    <m:map from="CA" to="Canada"/>
    <xsl:variable name="vCountry" select="document('')/*/m:map"/>
    <xsl:variable name="vKeys" select="document('')/*/xsl:key/@name
                                           [starts-with(.,'kTest')]"/>
    <xsl:variable name="vTestNotUniqueID"
                  select="*/*[key('kBookByID',ID)[2]]"/>
    <xsl:template match="/" name="validation">
        <xsl:param name="pKeys" select="$vKeys"/>
        <xsl:param name="pTest" select="$vTestNotUniqueID"/>
        <xsl:param name="pFirst" select="true()"/>
        <xsl:choose>
            <xsl:when test="$pTest and $pFirst">

                        <xsl:if test="$vTestNotUniqueID">

Books with no unique ID

                                <xsl:apply-templates
                                 select="$vTestNotUniqueID"
                                 mode="escape"/>

                        </xsl:if>
                        <xsl:variable name="vCurrent" select="."/>
                        <xsl:for-each select="$vKeys">
                            <xsl:variable name="vKey" select="."/>
                            <xsl:for-each select="$vCurrent">
                                <xsl:if test="key($vKey,'false')">

                                        <xsl:value-of
                                         select="$vKey/../@m:message"/>

                                        <xsl:apply-templates
                                         select="key($vKey,'false')"
                                         mode="escape"/>

                                </xsl:if>
                            </xsl:for-each>
                        </xsl:for-each>

            </xsl:when>
            <xsl:when test="$pKeys">
                <xsl:call-template name="validation">
                    <xsl:with-param name="pKeys"
                     select="$pKeys[position()!=1]"/>
                    <xsl:with-param name="pTest"
                     select="key($pKeys[1],'false')"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="Book" mode="escape">

            <xsl:call-template name="escape"/>

    </xsl:template>
    <xsl:template match="*" name="escape" mode="escape">
        <xsl:value-of select="concat('<',name(),'>')"/>
        <xsl:apply-templates mode="escape"/>
        <xsl:value-of select="concat('</',name(),'>')"/>
    </xsl:template>
    <xsl:template match="text()" mode="escape">
        <xsl:value-of select="normalize-space()"/>
    </xsl:template>

    <xsl:template match="@*|node()" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Country/text()">
        <xsl:variable name="vMatch"
                      select="$vCountry[@from=current()]"/>
        <xsl:choose>
            <xsl:when test="$vMatch">
                <xsl:value-of select="$vMatch/@to"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="Price[. > 20]">
        <xsl:call-template name="identity"/>
        <Expensive>True</Expensive>
    </xsl:template>
</xsl:stylesheet>

With your input, output:

Books with no unique ID

<Book><ID>1</ID><Name>Book1</Name><Price>24.??</Price><Country>US</Country></Book>

<Book><ID>1</ID><Name></Name><Price>24.69</Price></Book>

Books with no float Price

<Book><ID>1</ID><Name>Book1</Name><Price>24.??</Price><Country>US</Country></Book>

Books with empty element

<Book><ID>1</ID><Name></Name><Price>24.69</Price></Book>

Books with missing element

<Book><ID>1</ID><Name></Name><Price>24.69</Price></Book>

With proper input:
<Books>
    <Book>
        <ID>1</ID>
        <Name>Book1</Name>
        <Price>19.50</Price>
        <Country>US</Country>
    </Book>
    <Book>
        <ID>2</ID>
        <Name>Book2</Name>
        <Price>24.69</Price>
        <Country>CA</Country>
    </Book>
</Books>

Output:
<Books>
    <Book>
        <ID>1</ID>
        <Name>Book1</Name>
        <Price>19.50</Price>
        <Country>United States</Country>
    </Book>
    <Book>
        <ID>2</ID>
        <Name>Book2</Name>
        <Price>24.69</Price>
        <Expensive>True</Expensive>
        <Country>Canada</Country>
    </Book>
</Books>

Note: Ussing keys for performance. This is proof of concept. In real life, the XHTML output should be wrapped into an xsl:message instruction. From http://www.w3.org/TR/xslt#message

The xsl:message instruction sends a
  message in a way that is dependent on
  the XSLT processor. The content of the
  xsl:message instruction is a template.
  The xsl:message is instantiated by
  instantiating the content to create an
  XML fragment. This XML fragment is the
  content of the message.
NOTE:An XSLT processor might implement
  xsl:message by popping up an alert box
  or by writing to a log file.
If the terminate attribute has the
  value yes, then the XSLT processor
  should terminate processing after
  sending the message. The default value
  is no.

Edit: Compacting code and addressing country map issue.
Edit 2: In real life, with big XML documents and more enterprice tools, the best approach would be to run the transformation with XSLT 2.0 schema-aware processor for validating, or run validation independly with well-know schema validators. If for some reason these choices aren't aviable, don't go with my proof-of-concept answer because having keys for each validation rule make cause a lot of memory use for big documents. The better way for last case, is to add rules to catch validation errors ending transformation with message. As example, this stylesheet:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:m="map"
exclude-result-prefixes="m">
    <xsl:key name="kIDByValue" match="ID" use="."/>
    <m:map from="US" to="United States"/>
    <m:map from="CA" to="Canada"/>
    <xsl:variable name="vCountry" select="document('')/*/m:map"/>
    <xsl:template name="location">
        <xsl:param name="pSteps" select="ancestor-or-self::*"/>
        <xsl:if test="$pSteps">
            <xsl:call-template name="location">
                <xsl:with-param name="pSteps"
                                select="$pSteps[position()!=last()]"/>
            </xsl:call-template>
            <xsl:value-of select="concat('/',
                                         name($pSteps[last()]),
                                         '[',
                                         count($pSteps[last()]/
                                               preceding-sibling::*
                                               [name()=
                                                name($pSteps[last()])])
                                         +1,
                                         ']')"/>
        </xsl:if>
    </xsl:template>
    <xsl:template match="ID[not(number()=number() and not(contains(.,'.')))]">
        <xsl:message terminate="yes">
            <xsl:text>No integer ID at </xsl:text>
            <xsl:call-template name="location"/>
        </xsl:message>
    </xsl:template>
    <xsl:template match="Price[not(number()=number() and contains(.,'.'))]">
        <xsl:message terminate="yes">
            <xsl:text>No float Price at </xsl:text>
            <xsl:call-template name="location"/>
        </xsl:message>
    </xsl:template>
    <xsl:template match="Book/*[not(node())]">
        <xsl:message terminate="yes">
            <xsl:text>Empty element at </xsl:text>
            <xsl:call-template name="location"/>
        </xsl:message>
    </xsl:template>
    <xsl:template match="Book[not(ID and Name and Price and Country)]">
        <xsl:message terminate="yes">
            <xsl:text>Missing element at </xsl:text>
            <xsl:call-template name="location"/>
        </xsl:message>
    </xsl:template>
    <xsl:template match="ID[key('kIDByValue',.)[2]]">
        <xsl:message terminate="yes">
            <xsl:text>Duplicate ID at </xsl:text>
            <xsl:call-template name="location"/>
        </xsl:message>
    </xsl:template>

    <xsl:template match="@*|node()" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="Country/text()">
        <xsl:variable name="vMatch"
                      select="$vCountry[@from=current()]"/>
        <xsl:choose>
            <xsl:when test="$vMatch">
                <xsl:value-of select="$vMatch/@to"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="."/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="Price[. > 20]">
        <xsl:call-template name="identity"/>
        <Expensive>True</Expensive>
    </xsl:template>
</xsl:stylesheet>

With your input, this message stops the transformation:
Duplicate ID ar /Books[1]/Book[1]/ID[1]

With proper input, outputs the same as before.
Comment: Holy cow, I won't pretend to understand all of that yet (looks like XSLT is an aquired artform!), but it does exactly what we want in not too many lines!
One additional question: if the country code is a lookup list, e.g. US=United States, CA=Canada, would you still do it the same way?
Comment: @Andre White: See my edit addressing your request and a more real life sugestion.
Answer: Here is the RelaxNG schema:
<grammar xmlns="http://relaxng.org/ns/structure/1.0"
         datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">

  <start>
    <element name="Books">
      <zeroOrMore>
        <element name="Book">
          <element name="ID"><data type="ID"/></element>
          <element name="Name"><text/></element>
          <element name="Price"><data type="decimal"/></element>
          <element name="Country"><data type="NMTOKEN"/></element>
        </element>
      </zeroOrMore>
    </element>
  </start>

</grammar>

and this is the XML Schema version. (I think.)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  <xs:element name="Books">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="unbounded" ref="Book"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="Book">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="ID"/>
        <xs:element ref="Name"/>
        <xs:element ref="Price"/>
        <xs:element ref="Country"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="ID" type="xs:ID"/>
  <xs:element name="Name" type="xs:string"/>
  <xs:element name="Price" type="xs:decimal"/>
  <xs:element name="Country" type="xs:NMTOKEN"/>
</xs:schema>

Couple of things to note here:

The ID simple type will cause validators to check for multiple occurrences of the identifier, and complain if there are any. A disadvantage of using ID tags however is that they cannot start with a number. So, A1, A2, ... An would be fine, but IDs like 1, 2, ...., n would be considered invalid anyway.
The price has been set to be of type decimal. Float is never a proper type for financial numbers, because of rounding errors.

Running this through xmllint with the original XML document as input (with modified identifiers) gives:
wilfred$ xmllint --noout --relaxng ./books.rng ./books.xml
./books.xml:5: element Price: Relax-NG validity error : Type decimal doesn't allow value '24.??'
./books.xml:5: element Price: Relax-NG validity error : Error validating datatype decimal
./books.xml:5: element Price: Relax-NG validity error : Element Price failed to validate content
./books.xml:8: element Book: Relax-NG validity error : Expecting an element , got nothing
./books.xml fails to validate

Answer: On general XSL education, you may find useful an XSL Primer I wrote some years back.  It's not current on all the latest trends, but covers the basics of how the XML document is processed.

XSL / Schemas beginners question


Marcar a data atual no DataPicker

Question: Colegas,
Como eu faço para que no dataPicker a data atual fique marcada e alterar as datas anteriores que estão desabilitadas? Veja:

Consegui desabilitar as datas anteriores usando o código abaixo, mas elas ficam pretas e acabam confundindo e a data atual não fica marcado.

Answer: Consegui resolver. Coloquei o código abaixo:
todayHighlight: true

Para mais configurações acesse esse site. Tem como configurar seu datapicker.

Marcar a data atual no DataPicker


How get contours between objects with OpenCV Watershed?

Question: I use OpenCV Watershed with my image:
#include "opencv2/opencv.hpp"
#include <string>

using namespace cv;
using namespace std;

class WatershedSegmenter{
private:
    cv::Mat markers;
public:
    void setMarkers(cv::Mat& markerImage)
    {
        markerImage.convertTo(markers, CV_32S);
    }

    cv::Mat process(cv::Mat &image)
    {
        cv::watershed(image, markers);
        markers.convertTo(markers,CV_8U);
        return markers;
    }
};

int main(int argc, char* argv[])
{
    cv::Mat image = cv::imread("d:\\projekty\\OpenCV\\trainData\\base01.jpg"); //http://i.imgur.com/sEWFHfY.jpg
    cv::Mat blank(image.size(),CV_8U,cv::Scalar(0xFF));
    cv::Mat dest;
    imshow("originalimage", image);

    // Create markers image
    cv::Mat markers(image.size(),CV_8U,cv::Scalar(-1));
    //Rect(topleftcornerX, topleftcornerY, width, height);
    //top rectangle
    markers(Rect(0,0,image.cols, 5)) = Scalar::all(1);
    //bottom rectangle
    markers(Rect(0,image.rows-5,image.cols, 5)) = Scalar::all(1);
    //left rectangle
    markers(Rect(0,0,5,image.rows)) = Scalar::all(1);
    //right rectangle
    markers(Rect(image.cols-5,0,5,image.rows)) = Scalar::all(1);
    //centre rectangle
    int centreW = image.cols/4;
    int centreH = image.rows/4;
    markers(Rect((image.cols/2)-(centreW/2),(image.rows/2)-(centreH/2), centreW, centreH)) = Scalar::all(2);
    markers.convertTo(markers,CV_BGR2GRAY);
    imshow("markers", markers);

    //Create watershed segmentation object
    WatershedSegmenter segmenter;
    segmenter.setMarkers(markers);
    cv::Mat wshedMask = segmenter.process(image);
    cv::Mat mask;
    convertScaleAbs(wshedMask, mask, 1, 0);
    double thresh = threshold(mask, mask, 1, 255, THRESH_BINARY);
    bitwise_and(image, image, dest, mask);
    dest.convertTo(dest,CV_8U);

    imshow("final_result", dest);
    cv::waitKey(0);

    return 0;
}

But this give me only individual mask. I also tried to create markers as two points - the result was only one mask. Is it possible with OpenCV to separate cells (objects) with contours as is in example http://biodynamics.ucsd.edu/ir/ ?
If not, is it possible create as result mask with values: 1 for first object, 2 - for second, .. 99 for 99 ?
Comment: See http://opencv-code.com/tutorials/count-and-segment-overlapping-objects-with-watershed-and-distance-transform/
Comment: but this is half of work, different color of objects, but not contours
Answer: after performing
cv::watershed(image, markers);
the markers image will be -1 at the boundaries of the regions, and will be 1 in the region corresponding to the seed that was labelled 1, and will be 2 in the region corresponding to the seed that was labelled 2, and so on. So you can do something like this:
cv::Mat region1 = markers==1;

Answer: I use the following approach for extracting objects countours after watershed segmentation. Watershed output is one markers image containing a segment code of each pixel. I create a binary mask image for each single object segment from the markers image. That can be done in one iteration over all pixels of the markers image. For the core "for loop", see opencv example https://github.com/Itseez/opencv/blob/master/samples/cpp/watershed.cpp. I have all the objects masks stored in a vector <Mat>. Then I run findContours on every such mask -> contour of each object. See http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/find_contours/find_contours.html. You just don't need to use the edge detector Canny as the mask images are already binary.


What is the second argument in Rails' dynamic finders?

Question: The devise_invitable gem has this code:
find_by_invitation_token(params[:invitation_token], true)

Whas is the true argument? Very hard to google for this...
Answer: The method definition can be found here.
Note that it is not a Rails dynamic finder (although it looks like one), it is a custom method defined in the gem.
Answer: Although it looks like a regular dynamic finder, that's actually a custom method.


Understanding expansion on base $k$

Question: There are some times when one might need to use expansion of real numbers on some base $k$. One example is when dealing with Cantor's set, one uses expansion of the numbers inside $[0,1]$ on base $3$. The point is that I simply can't understand these expansions. I'm asking here on the more general context of expansion on base $k$ in order to try to make the question more useful.
As I understood, expansion of a number $a\in \mathbb{R}$ in base 3 means to write
$$a = \sum_{n=1}^\infty \dfrac{a_n}{3^n} \quad a_n \in \{0,1,2\}.$$
In that setting, I imagine expansion of $a$ in base $k$ would mean to write
$$a = \sum_{n=1}^\infty \dfrac{a_n}{k^n} \quad a_n \in \{0,1,\dots, k-1\}.$$
Now what those expansions really mean? I simply can't understand, we are decomposing numbers as certain series. But what those series really mean? Why would anyone consider doing these expansions? What the coefficients $a_n$?
I believe this is related to decimal expansions, that is when we write a number $a = a_0.a_1a_2a_3\dots$ but I'm unsure how to make this connection rigorous. Also, I believe this would be true just for $k=10$, so for the other cases it would still be something hard to grasp.
In truth, I've seem quite a few times this being used in some proofs, the Cantor set being the most well-known example. But up to now I never understood correctly what these expansions are and how to work with them.
Comment: As I understood, expansion of a number $a\in \mathbb{R}$ in base 3 means to write

$$a = \sum_{n=1}^\infty \dfrac{a_n}{3^n} \quad a_n \in \{0,1,2\}.$$ I think you arenot right, since
$a = \sum_{n=1}^\infty \dfrac{a_n}{3^n}\leq  \sum_{n=1}^\infty \dfrac{2}{3^n}=2\frac {1}{1-\frac{1}{3}}=3$
Comment: So @RaziehNoori, expansion in base $k$ can only be used for numbers $a \in [0,3]$?
Answer: The basic idea is to slice the interval $[0,1)$ in $k$ intervals of equal length $$[0,\frac{1}{k}), \ [\frac{1}{k}, \frac{2}{k}), \dots ,\ [\frac{k-1}{k},1).$$ Then $a$ belongs to one and only one of those intervals. This interval defines the values of $a_1$.
Then, you can reproduce the process with the interval which was found above, which induces the value of $a_2$.  Doing that recursively, you define a set of nested intervals which concerge to a point, which is $a$ itself.
Hopefully, this gives a basic view of the devlopment of $a$ in base $k$.
Answer: Here is an example:

Here the number $x=0.6$ is written in the usual decimal notation.
When we go from $x=0.6$ on the axis following the vertical line down through the blue pattern corresponding to the binary expansion, writing down a $0$ if we enter the bottom half of the next subdivision and $1$ if we enter the upper half of the next subdivision, we get the sequence $1,0,0,1,1,0$.
If we instead go from $x=0.6$ on the axis up through the red pattern corresponding to the ternary expansion writing $0$ for entering the lower third, $1$ for entering the middle third, and $2$ for entering the upper third, we get the sequence $1,2,1,0$.
This corresponds to the relations
$$
0.6_{10}\approx 0.100110_2\approx 0.1210_3
$$
with the subscripts referring to the relevant bases. Equivalently
$$
\frac{6}{10}\approx\frac1{2}+\frac0{4}+\frac0{8}+\frac1{16}+\frac1{32}+\frac0{64}\approx\frac13+\frac29+\frac1{27}+\frac0{81}
$$

As you probably know, the binary system can often be handy when dealing with computer science. Both binary and ternary may be relevant in tree structures of trees branching into either two or three subdivisions at each vertex.

Another fun fact is that rational numbers always have a tail of repeating patterns of the coefficients in expansions in any base $k$. In the current example one may show that
$$
0.6_{10}=0.10\overline{1100}_2=0.\overline{1210}_3
$$
where the latter two repeat their overlined patterns forever, as can be seen here.
Answer: When we write a numbner in base $k$ we only write the 'digits' that are numbers in $\{0,1,\dots,k-1\}$, just the same as the decimal number $3.14159$ really means
$$3+1\cdot10^{-1}+4\cdot10^{-2}+1\cdot10^{-3}+5\cdot10^{-4}+9\cdot10^{-5}$$
These are simply examples of positional notation for numbers, a system of condensed notation for numbers.

Understanding expansion on base $k$


Android:Webview within Scrollview is not working properly

Question: I am trying to create a rich text editor by embedding webview in scrollview of android's relative layout. The webview displays a html file with editable divs.

The layout file:-

 <ScrollView
    android:id="@+id/blog_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="30dp"
    android:clipToPadding="false"
    android:layout_above="@+id/Footer"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
   >
    <RelativeLayout
        android:id="@+id/rlContent"
        android:layout_width="match_parent"
        android:layout_height="200px">
      <com.medicodesk.ionapp.utils.editor.RichEditor
          android:id="@+id/editor"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          />
    </RelativeLayout>
</ScrollView>

<LinearLayout
    android:id="@+id/Footer"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:orientation="horizontal"
    android:layout_alignParentBottom="true"
    android:visibility="invisible">

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/black"
    android:layout_above="@+id/blog_content"
    android:id="@+id/blog_editor_toolbar"
    >

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

        <ImageButton
            android:id="@+id/action_undo"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@null"
            android:contentDescription="@null"
            android:src="@drawable/undo"
            />

        <ImageButton
            android:id="@+id/action_blockquote"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:background="@null"
            android:contentDescription="@null"
            android:src="@drawable/blockquote"
            />

    </LinearLayout>
</HorizontalScrollView>
</LinearLayout>

The RichEditor layout is weblayout child, and interacts with html by invoking javascript.
The problem is that i am not able to set the editor window height to fit into android mobile layout size. The editor will be in display mode showing all the content the user has entered or will be in editing mode where the keyboard layout pops from bottom. The editor should be scrollable vertically only. It is not clear for me whether i should rely on html scroll or android scroll view to get smooth scrolling.
Please help me.
Comment: Possible duplicate of [Android WebView inside ScrollView scrolls only scrollview](http://stackoverflow.com/questions/13257990/android-webview-inside-scrollview-scrolls-only-scrollview)
Answer: Try to change your XML layout like below:
<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    android:id="@+id/blog_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/Footer"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:clipToPadding="false"
    android:paddingBottom="30dp">

    <RelativeLayout
        android:id="@+id/rlContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.medicodesk.ionapp.utils.editor.RichEditor
            android:id="@+id/editor"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </RelativeLayout>
</ScrollView>

<LinearLayout
    android:id="@+id/Footer"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal"
    android:visibility="invisible">

    <HorizontalScrollView
        android:id="@+id/blog_editor_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/blog_content"
        android:background="@android:color/black">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/action_undo"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:background="@null"
                android:contentDescription="@null"
                android:src="@drawable/undo" />

            <ImageButton
                android:id="@+id/action_blockquote"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:background="@null"
                android:contentDescription="@null"
                android:src="@drawable/blockquote" />

        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

I hope its helps you.
Comment: Sorry for confusion. I want to create a richtexteditor in android using webview, html div and javascript document.exec() commands.  My requirement is show a webpage containing just editable document (like this below snippet)

 in android activity layout (any layout).  The activity should show the webpage as text-area for user to enter. When user attempts to type the keyboard opens and size of the layout will be reduced. the webpage should be scrollable as per the available size.


What are the possible sums of an $n \times n$ magic square?

Question: An $n\times n$ magic square summing to $S$ is an assignment of distinct integers to the $n^2$ entries of an $n \times n$ grid such that each row, column, and main diagonal sums to $S$.
It is well known that for $n>2$, an $n\times n$ magic square with sum $M_n=n(n^2+1)/2$ can be formed using the integers $1,2,\ldots,n^2$. Note that adding $c$ to each entry of such a magic square yields another magic square with sum $M_n +cn$; this implies that any sum that is $M_n$ modulo $n$ works.
For $n=3$, it is easy to show that the sum must be 3 times the middle entry, and thus that the sum being $M_n$ modulo $n$ is both necessary and sufficient. But what about $n>3$?
Comment: Are you asking if there is an $n \times n$ magic square with sum $S$ that is not a multiple of $n$?
Comment: I am asking whether there is an $n\times n$ magic square with sum $S$ for arbitrary $S$.
Answer: I don't know about the 4x4 case, but here are some things we can do for the 5x5 case.
Start with a typical 5x5 magic square (sum = 65):
\begin{array}{|c|c|c|c|c|}
\hline
    17 & 24 & 1 & 8 & 15\\
\hline
   23 & 5 & 7 & 14 & 16 \\
\hline
   4 & 6 & 13 & 20 & 22 \\
\hline
   10 & 12 & 19 & 21 & 3 \\
\hline
   11 & 18 & 25 & 2 & 9 \\ \hline
\end{array}
Multiply all entries by 2 (sum = 130):
\begin{array}{|c|c|c|c|c|}
\hline
    34 & 48 & 2 & 16 & 30\\
\hline
   46 & 10 & 14 & 28 & 32 \\
\hline
   8 & 12 & 26 & 40 & 44 \\
\hline
   20 & 24 & 38 & 42 & 6 \\
\hline
   22 & 36 & 50 & 4 & 18 \\ \hline
\end{array}
Add 1 to selected cells (sum = 131)
\begin{array}{|c|c|c|c|c|}
\hline
    34 & \color{red}{49} & 2 & 16 & 30\\
\hline
   \color{red}{47} & 10 & 14 & 28 & 32 \\
\hline
   8 & 12 & \color{red}{27} & 40 & 44 \\
\hline
   20 & 24 & 38 & 42 & \color{red}{7} \\
\hline
   22 & 36 & 50 & \color{red}{5} & 18 \\ \hline
\end{array}
OK, so this immediately shows that the sum need not be a multiple of n.
Obviously, I could have added 3 to those cells as well, so then the sum would be 133.  I can't add 2, for then I would get duplicate entries. However, I can get a sum of 132 by adding 67 to these 5 cells in the original square. In fact, I could just stick to the original square and add any number greater than 25 to those 5 cells to get any sum of 90 or more. And by picking those 5 cells a little more carefully (or by choosing a different original 5x5 square), we can go even lower than that, though 65 is of course the minimum ... if we stick to positive numbers.
Assuming we are allowed to use negative numbers though, I can get any sum I want, since if the number I want is a multiple of 5, then add or subtract the appropriate number to each cell of the original magic square, and if what I want is not a multiple of 5, then multiply all entries by 5, and add or subtract the appropriate number to the 5 selected cells as we did above (we multiplied by 5 so as to ensure that we don't get duplicate entries when we add or subtract the number which is not a multiple of 5). E.g:
Wanted: sum = 10. OK, then take original square and subtract 11 from each entry:
\begin{array}{|c|c|c|c|c|}
\hline
    6 & 13 & -10 & -3 & 4\\
\hline
   12 & -6 & -4 & 3 & 5 \\
\hline
   -7 & -5 & 2 & 9 & 11 \\
\hline
   -1 & 1 & 8 & 10 & -8 \\
\hline
   0 & 7 & 14 & -9 & -2 \\ \hline
\end{array}
Wanted: sum = 1. OK, then multiply all entries by 5 (sum = 325), and subtract 324 from the 5 selected cells:
\begin{array}{|c|c|c|c|c|}
\hline
    85 & -204 & 5 & 40 & 75\\
\hline
   -209 & 25 & 35 & 70 & 80 \\
\hline
   20 & 30 & -259 & 100 & 110 \\
\hline
   50 & 60 & 85 & 105 & -309 \\
\hline
   55 & 90 & 125 & -314 & 45 \\ \hline
\end{array}
OK, so this is just the 5x5 case, but it works for other n as well. For example, here is how you can pick 6 cells for a 6x6 to play with:
\begin{array}{|c|c|c|c|c|c|}
\hline
    \color{red}{X} & X & X & X & X & X\\
\hline
    X & X & X & X & \color{red}{X} & X\\
\hline
    X & \color{red}{X} & X & X & X & X\\
\hline
    X & X & X & X & X & \color{red}{X}\\
\hline
    X & X & \color{red}{X} & X & X & X\\
\hline
    X & X & X & \color{red}{X} & X & X\\
\hline
\end{array}
In fact, you can easily convince yourself that for any n>4 we can find these n cells for any nxn so that each row, column, and main diagonal has exactly one of those n cells.
Edit
OK, the 4x4 is also possible! (Thanks @RossMillikan !)
\begin{array}{|c|c|c|c|}
\hline
    \color{red}{X} & X & X & X\\
\hline
    X & X & \color{red}{X} & X\\
\hline
    X & X & X & \color{red}{X}\\
\hline
    X & \color{red}{X} & X & X\\
\hline
\end{array}
Comment: Very nice. This indeed generalizes to 4x4, and probably to all n>3. As long as you can prove the lemma that there exists an nxn magic square of sum 1 consisting of only 0 and 1 entries, your approach can generate all possible sums.
Comment: Oh, it does generalize to 4x4?  Can you show me?
Comment: @Bram28:  I can't get a sum of $1$, but I can get a sum of $2$ with $$1001\\0110\\1001\\0110$$ so we can at least get all even numbers as sums in the $4 \times 4$ case.
Comment: Are you uncertain how to demonstrate my lemma for n=4? Or are you uncertain how to utilize the lemma in the proof?
Comment: @RossMillikan Thanks!  Do you think odd sums are impossible for n=4?
Comment: Here we go $$1000\\0001\\0100\\0010$$  You are welcome to incorporate it into your answer.
Comment: @RossMillikan Cool, thanks!
Comment: The lemma is usually known as the $n$ queens problem.  See also Demirörs et al. 1992.
Comment: @AndrásSalamon Actually, it's a little different. In the Queens problem, you can't have any two cells on *any* diagonal, but in this case we were merely looking at the main diagonals. Indeed, notice how in all squares above we do have entries on the same diagonal ... Just not the main diagonals. Also, in this case we wanted to make sure we end up with 1 cell on the main diagonal, while in the Queens problem you can have no cells on the main diagonal at all.
Comment: @Bram28, the $n$ numbers that allow the sum to be shifted to any value form an $n$-queen solution.  Conversely, any $n$-queen solution forms a template of locations that can be used to shift an $n$ by $n$ magic square to any desired value.
Comment: @AndrásSalamon No, I still disagree. Take a look at the highlighted cells in the 4x4, 5x5, and 6x6 squares in my post: those are *not* acceptable solutions to the Queens problem.  And vice versa, there are solutions to the n queens problem that are *not* what we were looking for for the purposes of this problem, as for this problem we need a cell on the main diagonals, and you don't necessarily have that for the n queens problem. For example, take any solution to the 4-Queens problem: there will not be a queen on the main diagonals.
Comment: @Bram28 you are correct, have amended my answer.
Answer: Here is a general construction based on the examples given by Bram28 and Ross Millikan, and comments by dshin.
Revised claim: for any integer $S$, an $n$ by $n$ magic square with sum $S$ exists for all $n\ge 4$.
To see this, first notice that there are two transformations that preserve the property of being a magic square: adding an integer constant $c$ to each entry (which increases the sum by $cn$, as already observed in the question), and multiplying each entry by a non-zero integer constant $d$ (which multiplies the sum by $d$, as noted in Bram28's answer).
Second, any set of $n$ squares in the $n$ by $n$ grid which has exactly one square in each row, column, and long diagonal, provides a set of locations which can be used to shift the sum of an $n$ by $n$ magic square.
Let's call such an arrangement a template.
Shifting the values in the locations determined by a template works as long as the values in the square differ from each other by a "large enough" value to avoid collisions with values used elsewhere in the magic square.
We need to make this second observation more precise.
There are $n$ by $n$ magic squares for each $n \ge 3$.
Hence to prove the claim, it is enough to construct a magic square for each $n \ge 4$ and to show how to modify it to obtain another magic square with the desired sum, based on a template.
To see that a template exists for $n=4$ or each odd integer $n \ge 5$, pick squares $(1,3),(2,2),(n,1)$ as well as the squares $(3,4),(4,5),\dots,(n-1,n)$ that are just off one of the long diagonals.
For even $n\ge 6$, pick $(n,1),(n/2-1,n/2+1),(n/2,n/2)$, as well as $(1,2),(2,3),\dots,(n/2-2,n/2-1)$ and $(n/2+1,n/2+2),(n/2+2,n/2+3),\dots,(n-1,n)$.
This choice of squares guarantees one square in each row and column, while the long diagonals are taken care of by $(2,2)$ or $(n/2,n/2)$ for the one diagonal and $(n,1)$ for the other, so it is a template.
(This construction seems to be a version of dshin's suggestion.)
Now start with any magic square with values $1$ to $n^2$ as outlined in the question.
There are two different constructions, depending on whether $S=0$ or $S\ne 0$.
First suppose $S=0$.
If $n$ is odd, then subtract $(n^2+1)/2$ from each value.
Otherwise $n$ is even, so multiply each value by $2$, and then subtract $n^2+1$.
Now suppose $S\ne 0$.
In this case, first multiply each entry by $2n^2S \ne 0$.
This intermediate magic square uses values $2n^2S, 4n^2S, 6n^2S, \dots, 2n^4S$; these all differ pairwise by at least $2n^2S$, and the square has sum $Sn^3(n^2+1)$.
Subtract $Sn^2(n^2+1)$ from each entry in the magic square, giving a magic square with sum $0$.
Now add $S$ to each of the entries that form a template.
Since the template contains precisely one entry from each row, column, and long diagonal, this results in a final magic square with sum $S$.
(I have removed my earlier suggestion using solutions of the $n$ queens problem, since the above construction is simpler and more general.)
Comment: This almost works. But an N-queens solution does not have rows+columns+diagonals of equal sum. You can construct a square instead by, for $1 \leq i,j \leq n$, setting $A[i][j] = 1$ if $i+1 \equiv j$ mod $n$ and 0 else, and then choosing an appropriate pair $1 \leq a < b \leq n$ and setting $A[i][j] \rightarrow 1 - A[i][j]$ for $i,j \in \{a,b\}$.
Comment: You are right, my claim only works for $n$ queens solutions in which there are entries on both long diagonals.  Will edit.
Comment: Your template construction fails for all even $n>5$. My construction should work for all $n$.
Comment: I'm afraid I can't parse the "choosing..." part of your construction.
Comment: I'm saying to just flip the 4 corners of a subrectangle. You need to choose the subrectangle well, based on whether n is even or odd.
Comment: Ok, got it, thanks for clarifying.
Comment: And sorry, I realized my $a,b$ part didn't make sense. I really meant something like, choose $a_1, a_2, b_1, b_2$, and flip $A[a_i][b_j]$ for $i,j \in \{1,2\}$.
Comment: Your even n template suggestion is a bit hard to parse. Can you clean it up?
Comment: Never mind, I realized my phone was just not rendering correctly. This solution looks good, accepting.


Anyway to type convert all elements in solidity array?

Question: I have been trying Solidity lately.
While trying to create a public int array.
Test.sol
pragma solidity >=0.8.12 <0.9.0;

contract Test {
    int[5] public array = [1, 2, 3, 4, 5];
}

The following error is thrown:

TypeError: Type uint8[5] memory is not implicitly convertible to
expected type int256[5] storage ref.
--> first.sol:4:27:
|
4 | int[5] public array = [1, 2, 3, 4, 5];
| ^^^^^^^^^^^^^^^

So I tried with type conversion, like below:
pragma solidity >=0.8.12 <0.9.0;

contract Test {
    int[5] public array = [int(1), int(2), int(3), int(4), int(5)];
}

Which works, but type converting every element doesn't seem conventional to me.
Is there any other way?
--------------------- Edit ------------------------------
In solidity, just type casting first element works.
So following solved the problem:
int[5] staticArray = [int(1), 2, 3, 4, 5];
Answer: This seems to be a bug in the compiler.
A small enough number literal (such as 1 or 2 in your example) fits into the type for uint8 (max value 255), so the compiler treats the literal as uint8 type by default.
You need to workaround this by using the typecast function, just as shown in your question.
int[5] public array = [int(1), int(2), int(3), int(4), int(5)];

Hopefully it's fixed in a later Solidity version.


What is the purpose of the XML Doctype file in a DotNetNuke Skins folder?

Question: I noticed this XML file in the DNN skins folder. Does this set the document type for a specific skin page in DotNetNuke? What will happen if a page does not have an XML file?

When I open the XML file I notice this:
Comment: If the file does not exist DNN will just revert to it's default DocType.
Answer:
In the context of web pages,the doctype declaration refers to a
  Document Type Definition (DTD). The DTD specifies the rules for the
  markup language, so that the browsers can render the content follows
  the rules of that markup language i.e. different versions of the
  doctype render content in different ways.
In early versions of DotNetNuke the doctype was a fixed part of
  default.aspx and was set to "HTML 4.0 Transitional" which was not
  ideal for sites wanting to create valid XHTML markup. With 4.4, the
  declaration has been made dynamic, to allow users to declare
  particular doctypes with particular skins.

Source: http://www.dnnsoftware.com/wiki/doctype


How to correctly register in my DNS servers whose IPs and names are handled by someone else?

Question: I use a virtual server (several similar cases) set up and registered by someone else. Its IP is 10.0.0.1 and name a.example.com (both handled by the "someone else" above).
I manage the domain sub.example.com and would like to also register this server as b.sub.example.com.
There are two ways of doing this in my DNS: either
b IN CNAME a.example.com.

or
b IN A 10.0.0.1

Since the IP is not distributed by DHCP (it is therefore hardcoded in the server config) there will be a problem in either case if it changes without me knowing and neither solution above would help. The PTR will point to a.example.com (I do not control the IP reverse mapping)
So what is the proper way (= canonical / best practice) to do the registration on my side?
EDIT: since b is also referenced in the NS I will have to go for the second solution. Please see my answer below for details.
I accepted MadHatter's answer because even though it does not address the best practices / standards for the case above (before the NS update which forces a solution anyway) it gives interesting insights. Thanks!
Comment: You talk to the person in charge and get him do his part of the job?
Comment: @TomTom: everyone did their job. The virtualization group registered the servers in the correct domain (from their perspective) and I want to register them in mine (for various reasons).
Comment: Is this IP address static or not?
Comment: @MadHatter: it is static (I mentioned in my question that DHCP is not used and the IP is hardcoded in the server - it is actually automatically reserved (and communicated to me) and updated in the `example.com` DNS)
Comment: So why do you fear it changing without your knowledge?
Comment: @MadHatter: I do not particularly fear it changing - what I meant is that neither of the solutions would protect me from a change of the IP  (as opposed to having, say, `myowngoogle IN CNAME www.google.com` which would automatically adapt to changes on the `www.google.com`server). This is why the question is about best practices and possibly standards in such a registration.
Answer: I will finally have to use
b IN A 10.0.0.1

because b is also referenced in the NS record (which I did not pay attention to intially)
 IN NS b

It is illegal for b to be a CNAME so there is no choice but to go with the explicit A record.
Answer: The CNAME option will still work, as you say their infrastructure knows of the VPS's IP and they properly update their nameservers.
EDIT: About the PTR record; the only thing you can do is ask them. I myself have a few  hosted VMs and all my providers except for one agreed to it. If their policy allows it you are fine.
Comment: That won't fix the PTR issue.
Answer: The DNS isn't well-designed to handle changes in static IP addresses without manual intervention.  There are technologies for allowing records to be propagated automatically, such as TSIG, but they require quite a lot of co-operative setup, and even then don't deal well with changes to PTR records.
Manual IP changes happen all the time in the real world. They have to be scheduled well in advance, and handled appropriately. That involves well-timed and thoughtful changes to the DNS, the acceptance that DNS propagation is imperfect and that there will be business effects as a result of the change, and a consequent dislike of such changes.
TomTom's comment above is right; if everyone involved does their jobs, a change will go through with the minimum of effort - but some effort will be needed.
Comment: I completely understand this and it is not my question. I know that a change of the IP will break both of the configurations and that the `PTR` will point to the example.com entry. Now since both of the configurations work I wanted to understand if one is preferred over the other.


I was reading a post and someones comment confused me.

Question: OK, so I was looking up the goto statement in java, and I stumbled on this post:
Is there a goto statement in Java?
(I know, I'm a scrub :P )
Anyways, I stumbled across this chuck of code in the comments:
public static void main(String [] args) {

 boolean t = true;

 first:
 {
    second:
    {
       third:
       {
           System.out.println("Before the break");

           if (t) {
              break second;
           }

           System.out.println("Not executed");

       }

       System.out.println("Not executed - end of second block");

    }

    System.out.println("End of third block");

 }
}

And I am confused as to why the second block wouldn't have been executed after the break. Can someone explain this to me?
I would've commented to ask, but I don't have a high enough Rep to do so.
Thank you!
Comment: "*And I am confused as to why the second block wouldn't have been executed after the break.*" I am confused about your confusion. That is kind of whole point of `break second;`, to break code block labelled with `second` (to move flow of control right after this block). What other behaviour did you expect?
Comment: I misunderstood the usage of break then, I thought it was to break away from where you are in the code, then start at the specified label.
Comment: @AustenClay you confused break with goto.
Comment: @zubergu, I realize that now :P
Answer:
And I am confused as to why the second block wouldn't have been
  executed after the break.

Because the break statement with label terminates the labeled block and does not take the execution back to the label.


how to use apply family instead of nested for loop for my problem

Question: I want to fill a new data frame called hd5 based on a conditions from a old data frame called dfnew1.
Can I do it without a nested for loop ?
   for(  j in 2 : length(hd6)  )
   {
     for( i in 1: length(hd5$DATE) )
    {
     abcd= dfnew1 %>%
     filter( (Date == hd5$DATE[i]) , (StrikePrice== hd6[j]) , (OptionType== "CE"))  %>%
     arrange( dte  )
     hd5[i,j]= abcd[1,9]
     }
   }

hd6= [13900,14000,14100,14200]
dfnew1 looks like this
Date     expiry     optiontype strikeprice closeprice  dte
1/1/2019  31/1/2019  ce          13900      700        30
1/1/2019  31/1/2019  ce          14000      650        30
1/1/2019  31/1/2019  ce          14100      600        30
1/1/2019  31/2/2019  ce          14100      900        58
1/2/2019  31/1/2019  ce          13900      800        29
1/2/2019  31/1/2019  ce          14000      750        29
1/2/2019  31/1/2019  ce          14100      700        29

i want to fill my new dataframe hd5 from this dfnew1 dataframe by maching the date and strtkeprice and optiontype
hd5 which i want to filled should look like
Date         13900  14000 14100 14200
1/1/2019     700     650   600   550
1/2/2019     800     750   700   650

Comment: Could you please add (a) some representative data from `hd5` - say, 5 - 10 lines, and (b) what you want `hd6` to look like?
Comment: @r2evans   is it correct now??
Comment: Yes, but I'm asking that you edit your post so that we can see what `hd5` looks like, and what you _want_ `hd6` to look like.
Comment: do you have 3 datasets i.e hd6, hd5  along with dfnew1
Comment: yes. i have 3 datasets.
Comment: arrange( dte  ) . this i do because after filterind based on date and strike price and option type  i will get 3 rows with same date. so  i arrange them in ascending order. and select the 1st row by doing   hd5[i,j]= abcd[1,9]
Comment: Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557 (and https://xkcd.com/2116/). Please just include the code, console output, or data (e.g., `dput(head(x))` or `data.frame(...)`) directly.
Comment: Thank you for the edit, Hammysidhu. I've suggested an edit to format data as code, which can make a big difference for readability. See https://stackoverflow.com/editing-help if you want more info there.
Answer: Here's a tidyverse option:
library(dplyr)
# library(tidyr)
dat %>%
  group_by(Date, strikeprice) %>%
  summarize(closeprice = min(closeprice)) %>%
  ungroup() %>%
  tidyr::pivot_wider(names_from = "strikeprice", values_from = "closeprice")
# # A tibble: 2 x 4
#   Date     `13900` `14000` `14100`
#   <chr>      <int>   <int>   <int>
# 1 1/1/2019     700     650     600
# 2 1/2/2019     800     750     700

(You might see online tutorials referencing tidyr::spread. It does effectively the same thing here, but has been retired (source: https://tidyr.tidyverse.org/reference/spread.html, along with tidyr::gather), so it is generally recommended that new code should use the pivot_* functions.)
Note: based on your expected output, it looks like you took the minimum for
1/1/2019  31/1/2019  ce          14100      600        30
1/1/2019  31/2/2019  ce          14100      900        58

I might be more inclined (when "price" is involved) to use sum instead, but it depends heavily on your actual intent and use. Replace min with your aggregation of choice, be it max, sum, or something else.
I'll note that having numeric column names is a little non-standard, and can cause confusion (dat[,14100] will fail, dat[,\14100`]<code>or</code>dat[,"14100"]` should generally work).
You may find that having numeric column headers makes sense for some comparisons and for depicting a table, but if you plan on plotting things (e.g., using ggplot2), often a longer version (your original layout, summarizing notwithstanding) might be preferred.

Data:
dat <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "
Date     expiry     optiontype strikeprice closeprice  dte
1/1/2019  31/1/2019  ce          13900      700        30
1/1/2019  31/1/2019  ce          14000      650        30
1/1/2019  31/1/2019  ce          14100      600        30
1/1/2019  31/2/2019  ce          14100      900        58
1/2/2019  31/1/2019  ce          13900      800        29
1/2/2019  31/1/2019  ce          14000      750        29
1/2/2019  31/1/2019  ce          14100      700        29")

Answer: We can also use spread after summarizing to get the min of 'closeprice' after grouping by 'Date', 'strikeprice'
library(dplyr)
library(tidyr)
dat %>%
  group_by(Date, strikeprice) %>%
  slice(which.min(dte)) %>%
  ungroup() %>%
  spread(strikeprice, closeprice)
# A tibble: 2 x 4
#  Date     `13900` `14000` `14100`
#  <chr>      <int>   <int>   <int>
#1 1/1/2019     700     650     600
#2 1/2/2019     800     750     700

Or using pivot_wider by making use of values_fn to pass a function.  Here, we select only the column of interest
dat %>%
  select(Date, strikeprice, closeprice) %>%
  pivot_wider(names_from = strikeprice, values_from = closeprice,
       values_fn = list(closeprice = min))
# A tibble: 2 x 4
#  Date     `13900` `14000` `14100`
#  <chr>      <int>   <int>   <int>
#1 1/1/2019     700     650     600
#2 1/2/2019     800     750     700

Or another option is dcast
library(data.table)
dcast(setDT(dat), Date  ~ strikeprice, min, value.var = 'closeprice')
#       Date 13900 14000 14100
#1: 1/1/2019   700   650   600
#2: 1/2/2019   800   750   700

data
dat <- structure(list(Date = c("1/1/2019", "1/1/2019", "1/1/2019", "1/1/2019",
"1/2/2019", "1/2/2019", "1/2/2019"), expiry = c("31/1/2019",
"31/1/2019", "31/1/2019", "31/2/2019", "31/1/2019", "31/1/2019",
"31/1/2019"), optiontype = c("ce", "ce", "ce", "ce", "ce", "ce",
"ce"), strikeprice = c(13900L, 14000L, 14100L, 14100L, 13900L,
14000L, 14100L), closeprice = c(700L, 650L, 600L, 900L, 800L,
750L, 700L), dte = c(30L, 30L, 30L, 58L, 29L, 29L, 29L)),
class = "data.frame", row.names = c(NA,
-7L))

Comment: i do not want min(close). i want close price corresponding to  min(dte).


Counting "good" strings of octal numbers of length $n$?

Question: My professor asked me to create a combinatorics problem. I have created one, i think it is a good problem, but I am having trouble solving it. Can anyone help me?

A string of octal numbers of length $n$
is called "good" if $k=n(0)+n(7)$ and $l=n(3)+n(4)$ are odd numbers, where $n(i)$, $i=0,1,\ldots,7$ represents the number of $i$'s found in the string. How many strings of octal numbers of length $n$ are "good", where $n$ is an element of $\mathbb{N}$?

For example: 00334221, isn't a "good" octal string because $k=2$ is even number. But 007334221 is a "good" octal string, because $k=3$ and $l=3$ are both odd numbers.
We know that $a_1=0$, $a_2=8$, $a_3=96$, $a_4=896$. Where $a_n$ is the number of "good" octal string of length n.
I have tried in this method $a_n=4a_{n-1}+4b_{n-1}$. Where $b_n$ is string of octal numbers of length $n$ where $k$ is even and $l$ is odd (due to the symmetry of $k$ and $l$). But couldn't eliminate $b_n$.
Comment: Looking more closely, all of these terms are divisible by 8. Then starting from $n=0$ we have $$a_n/8 = 0, 1, 12, 112, 960, 7936, 960, 7936, 64512, 520192, 4177920,\ldots$$ This sequence _does_ appear on OEIS as [A016152](https://oeis.org/A016152). In particular, this yields $a_n=8\cdot 4^{n-1}(2^n-1)$. (This still leaves the question of _why_ $a_n/8$ is identical to this sequence.)
Comment: This question was posted a few days ago. Are you sure that you created it yourself? If yes, then someone else agrees with you that it's a good question.
Comment: @Semiclassical as I calculated a_4=896 (if didnt make any mistake). And i didnt find this serie in OEIS.
Comment: Perhaps you should include $c_n$, counting the number of strings with both k and l being even. Then you could use $a_n+2b_n+c_n=8^n$
Comment: $896$ is correct. The next five are $\{7680,63488,516096,4161536,33423360\}$. The sequence is not in OEIS.
Comment: This sequence has closed form $a_n=\frac{8^n}{4}-\frac{4^n}{2}$ @Semiclassical
Comment: Try to create a problem that you *can* solve. If you must solve this problem, you need to show some effort. At the very least, count the good strings of length two and three.
Comment: @CalvinLin I reposted it to give more details because I'm new here and in response to feedback from some critics.
Comment: @DanielMathias We were asked to create good math problems. There wasn't a requirement for us to solve them. I have tried hard, but I couldn't solve it. I just wanted to know its solution, if i cant solve it.
Comment: [Edit](https://math.stackexchange.com/posts/4823257/edit) your question to show what you have tried. Include your count for strings of length two and three.
Comment: @DanielMathias Done!
Comment: If you have the first few numbers in the sequence, you can go check whether it's extant on [OEIS](https://oeis.org/). If not, neat! If it is, then the sequence you came up with has been of interest to others already.
Comment: @DanielMathias Yes, you're right: I missed that the OEIS sequence started at $n=0$ rather than $n=1$.
Answer: One approach is to find the exponential generating function of the number of good strings.
With no restrictions on their numbers, the EGF of the number of strings of $0$s and $7$s is $e^x \cdot e^x=e^{2x}$; so the EGF of strings of an odd number of $0$s and $7$s is $(1/2)(e^{2x}-e^{-2x})$.  The same EGF counts the number of strings of $3$s and $4$s when the total number of $3$s and $4$s must be odd. So the EGF of the number of good strings is
$$\begin{align}
f(x) &= (e^x)^4 \left( \frac{e^{2x}-e^{-2x}}{2} \right)^2 \\
&= \frac{e^{8x} -2 e^{4x} +1}{4}
\end{align}$$
The number of good strings of length $n$ is $n!$ times the coefficient of $x^n$ when $f(x)$ is expanded in a series, i.e.
$$n![x^n]f(x) = \frac{8^n - 2 \cdot 4^n}{4}$$
for $n \ge 1$.


Probability distribution of a random variable

Question: The table below shows the number of ice creams brought and the number of customers brought that number of ice creams.
 ice_cream     No_of_customers
     1             225
     2             170
     3              55
     4              20
     5              20
     6              10

The estimated probability of purchasing the number of ice cream is shown below. e.g. probability of purchasing 1 ice cream is 225/500 = 0.45. This table below shows that distribution of number of ice cream sold
ice_cream    Probability
     1        0.45
     2        0.34
     3        0.11
     4        0.04
     5        0.04
     6        0.02

while showing this above distribution as a graph with the below code I was expecting my y- axis in histogram plot to have same values as in probability column
 ggplot(data = ice_cream)+
 geom_histogram(aes(x = ice_cream,y = ..density..))

I tried density plot but y axis is not the one in probability column for each ice cream column.
I am missing something very basic here.
Can someone please suggest how to get that probability in the graph?
Sample data:
ice_cream <- data.frame(ice_cream = c(rep(1,225),rep(2,170),rep(3,55),rep(4,20),rep(5,20),rep(6,10)))

Answer: The issue is that you're not specifying the binwidth when constructing your histrogram even though the discrete nature of your data makes that critical. Try:
ggplot(data = ice_cream) +
    geom_histogram(aes(x = ice_cream, y=..density..),
                   binwidth=1,
                   colour="black", fill="white")

Note that we specified binwidth = 1.
To see how things can go wrong, try setting binwidth = 0.5 and observe what happens. As I wrote below in the comment, the problem with omitting binwidth entirely is that it will default to 30 bins and treat your data as continuous, so that you are now estimating a density of a continuous variable, which can certainly be greater than $1$ at certain regions. Here, at each of these $30$ bins that does not contain an integer, the density is $0$, and at bins that do contain an integer $k$, the density is $P(\text{icecream} = k)/\text{binwidth}$ and since $\text{binwidth} < 1$, this is inflating the numbers.
Comment: Thanks. That solve the problem. What does the value in y axis means if the bandwidth is not specified
Comment: When you don't specify binwidth or bins and run the code I provide, you get a warning message saying "`stat_bin()` using `bins = 30`. Pick better value with `binwidth`." So it's resorting to 30 bins, and treating the observed data as continuous. So then you're just seeing a histogram for continuous data, with y axis showing the density of a continuous distribution, which can certainly be greater than 1. Here, at each bin that contains an integer $k$, its doing something like $P(\text{icecream} = k)/\text{binwidth}$, and since binwidth < 1, it's inflating the numbers! Does that make sense?
Comment: Thanks a ton for answering in intuitive way
Answer: A couple ways to do this:
a) Plot the probability column using the probability column and geom_col
library(tidyverse)
ice_cream = 1:6
no_cust = c(225, 170, 55, 20, 20, 10)
d = tibble(ice_cream, no_cust)

d %>%
  mutate(y = no_cust/sum(no_cust)) %>%
  ggplot(aes(ice_cream, y))+
  geom_col()

b) uncount the ice creams
library(tidyverse)
ice_cream = 1:6
no_cust = c(225, 170, 55, 20, 20, 10)
d = tibble(ice_cream, no_cust)

d %>%
  uncount(weights = no_cust) %>%
  ggplot(aes(ice_cream))+
  geom_histogram(aes(y = ..count../sum(..count..)))

```


How to avoid counting numbers when do calculation in a for loop in python

Question: I am working on a python algorithm. I have built a for loop to generate the numbers i want. I am going to use these numbers as indices to generate a string called constraint_sty3.
Here is a part of my code:
def constraint():
    val=4
    ind=[]
    for i in range(1,7):
        for j in range(val,val+i):
            val = val+1
            ind.append(j)
            if(i < 6):
                boundNode.insert(j, 'x%d' % (j-(2*i+1)))
            constraint_sty3 = str(boundNode[(j+1])]

My problem is when calculating j+1 , it appears it is not doing the right calculation but doing the counting at the same time. Like a j=j+1. All the other j ,i -related str(boundNode[])like str(boundNode[j]) work well but only this contains j+1 return a problematic result.
Answer: You have an error on the last line of your code:
constraint_sty3 = str(boundNode[(j+1])]

it should be:
constraint_sty3 = str(boundNode[(j+1)])

But i dont think this is the error
But by putting (j+1) inside brackets [ ] it will count plus one on that array/list
You should do the calculation before and then append it.
Comment: But I have already generate `boundNode[]` list. I want to use `j+1` as an index. Is there any solution to this?


Find the same date from two sets of data

Question: I am new to Python. I got two sets of data shown as below.
Set 1:
Gmt time,Open,High,Low,Close,Volume,RSI,,Change,Gain,Loss,Avg Gain,Avg Loss,RS
15.06.2017 00:00:00.000,0.75892,0.76313,0.7568,0.75858,107799.5406,0,,,,,,,
16.06.2017 00:00:00.000,0.75857,0.76294,0.75759,0.76202,94367.4299,0,,0.00344,0.00344,0,,,
18.06.2017 00:00:00.000,0.76202,0.76236,0.76152,0.76188,5926.0998,0,,-0.00014,0,0.00014,,,
19.06.2017 00:00:00.000,0.76189,0.76289,0.75848,0.75902,87514.849,0,,-0.00286,0,0.00286,,,
...

Set 2:
Gmt time,Open,High,Low,Close,Volume
15.06.2017 00:00:00.000,0.75892,0.75933,0.75859,0.75883,4777.4702
15.06.2017 01:00:00.000,0.75885,0.76313,0.75833,0.76207,7452.5601
15.06.2017 02:00:00.000,0.76207,0.76214,0.76106,0.76143,4798.4102
15.06.2017 03:00:00.000,0.76147,0.76166,0.76015,0.76154,4961.4502
15.06.2017 04:00:00.000,0.76154,0.76162,0.76104,0.76121,2977.6399
15.06.2017 05:00:00.000,0.7612,0.76154,0.76101,0.76151,3105.4399
...

I want to find lines in Set 2 in the same date with Set 1. I tried this: print(daily['Gmt time'][0].date == hourly['Gmt time'][0].date), but I don't know why it came out False. Isn't there a way to compare the date(just date, not including time) from two sets of data?
Comment: Load both the dataset pandas dataframe. change column datetime format to just date. compare for equality
Comment: @Vikash Singh Thanks but do I have to use dataframe to solve this?  And why the comparison came out false?
Comment: try this `print(daily['Gmt time'][0].date, hourly['Gmt time'][0].date)` this will clarify why the comparison came out false.
Comment: you can solve this without dataframe also, but your data is in tabular format. dataframes are good for handling tabular data.
Comment: @Vikash Singh I'll try to figure it out as you said. Thanks anyways.
Comment: @Vikash Singh so sorry to bother you again but I'm not quite familiar with dataframe, could you tell me that how can I load these sets to data frame and change the column to just date?
Comment: sure, are the 2 data sets in files ??
Comment: what kind of comparison you want to do?? df_two has multiple times the date present in df_one.. how do you want to perform the comparison?
Comment: @Vikash Singh Thanks for all the efforts! I wish to find out the lines of in set 2 that has the same date with a line in set 1 since one is daily and one is hourly. for example I want to find the lines in set 2 that in 15.06.2017
Comment: @CG : updated my answer how you can compare. hope that helps.
Answer: First read the data sets into dataframes:
import pandas as pd
df_one = pd.DataFrame.from_csv('data_set_one.csv', index_col=False)
df_two = pd.DataFrame.from_csv('data_set_two.csv', index_col=False)

Convert date column to date
df_one['Gmt date'] = pd.to_datetime(df_one['Gmt time']).dt.date
df_two['Gmt date'] = pd.to_datetime(df_two['Gmt time']).dt.date

now compare both the dataframes:
for i, row in df_one.iterrows():
    df_one_date = row['Gmt date']
    print('df_one_date', df_one_date)
    print(df_two[df_two['Gmt date'] == df_one_date])
    print('----')

it's still unclear how you want to handle for different dates from df_one to match df_two. Hope this gives you enough idea on how to handle it.
Comment: Thank you so much. It's really helpful.
Answer: Since using iterrows can be slow, a better option might be to use merge.
import pandas as pd

# load data
df_one = pd.read_csv('data_set_one.csv', index_col=False)
df_two = pd.read_csv('data_set_two.csv', index_col=False)

# convert times to datetime and then strip off the time to leave the date
df_one['Gmt date'] = pd.to_datetime(df_one['Gmt time']).dt.date
df_two['Gmt date'] = pd.to_datetime(df_two['Gmt time']).dt.date

# merge
# selecting only the date in each dataframe for clarity
df_merge = df_two[['Gmt date']].merge(df_one[['Gmt date']], on=['Gmt date'], how='inner', right_index=True)

# get list of indices from df_two where dates exist in both frames
ix = list(df_two.index.unique())
print ix

[0, 1, 2, 3, 4, 5]
Comment: Thanks a lot! I will try it out later:D


Multiple levels of .htaccess files with RewriteRule, only deepest level processed

Question: I have .htaccess files at multiple levels of a directory heirarchy, each with RewriteRules in them. However, when arequest is made for a file in a subdirectory, only the rules in the most deeply nested .htaccess file (up to the level of the requested file) are ever processed. Even having only a single line with "RewriteEngine On" is a subdirectory is enough to "disable" all rewrites defined in higher directories. This happens both for apache and litespeed httpd.
I had expected (and can't find any information otherwise) that all the RewriteRules would be combined into a single ruleset (presumably with deeper levels being processed last). However this doesn't seem to be happening.
Quite confused :) What am I not understanding?
Thanks,
Mike.
Answer: Have you set RewriteOptions Inherit in each .htaccess?

In per-directory context this means
  that conditions and rules of the
  parent directory's .htaccess
  configuration are inherited. Rules
  inherited from the parent scope are
  applied after rules specified in the
  child scope.

http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriteoptions
Comment: Yes, thanks for your help, I had mistakenly thought that that only inherited "options," such as RewriteBase etc... as I had tried it but it wasn't working, I think due to some [L] flags (also though parent rules were applied first!). At any rate inheriting options in this way seems a bit limited, as it (for me at least) strips the _current_ directories prefix (i.e. not that of the parent directory), and also keeps adding the path-info from the _initial_ request URI (not the current state of the substitution). Is this the only mechanism for combining RewriteRules across multiple directories?


Determine the Kernel and Homomorphisms

Question: Suppose that $\phi$ is a homomorphism from $S_{4}$ onto $Z_{2}$. Determine Ker $\phi$. Determine all homomorphisms from $S_{4}$ to $Z_{2}$.
What I have so far: We know by the First Isomorphism Theorem that |$S_{4}$|/ |Ker $\phi$| =| $Z_{2}$|. So $24$/ |Ker $\phi$|= $2$. Hence, |Ker $\phi$| =$12$. Not sure what else to do after this.
Comment: What is denoted by $Z_2$ in this context?
Comment: The set of integers modulo 2.
Comment: Seen as $\{-1,1\}$, I suppose?
Comment: Just $\{$ $0$,$1$$\}$ I think.
Answer: You already deduced that the order of the group must be $12$. Try to prove that $A_n$ is the only subgroup of index $2$ in $S_n$ and you are done, because the kernel must be exactly $A_n$. This tells us that the image of an element in $A_n$ is $0$ and the image of every other element is $1$(Since the only options are $0$ and $1$ and we know the kernel is $A_4$), this determines the homomorphism uniquely.
Comment: What do you mean by $A_n$ is the only subgroup of index 2 in $S_n$. don't we need $n<5$?
Comment: No, gary. For every n , $A_n$ is the only subgroup of index $2$ in $S_n$.

Determine the Kernel and Homomorphisms


RelativeLayout causes lag on Listview

Question: Just to make sure that the RelativeLayout causes the lag I replaced it will a simple layout, then no lags experienced.
I am using cardslib.
I have no nested layout on the rel layout 2-level hierarchy, but still I am getting lags when I used it. Are there any options messing up or priority options messed up?
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="30dip">

<TextView
        android:id="@+id/textView6"
        android:layout_width="fill_parent"
        android:textColor="@color/card_activated"
        android:layout_height="3dip"
        android:layout_below="@+id/card_header_inner_simple_title"
        android:layout_centerHorizontal="true"
        android:background="@color/card_activated"
        android:layout_margin="10dip"/>

  <ImageView
        android:id="@+id/imageDisplay"
        android:layout_width="120dip"
        android:layout_height="120dip"
        android:layout_alignLeft="@+id/textView6"
        android:layout_alignTop="@+id/textView6"
        android:layout_marginTop="46dp"
        android:layout_marginLeft="46dp"
        android:adjustViewBounds="true"
        android:src="@drawable/content_picture" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="100dip"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
         android:entries="@array/quanitiy"
        android:layout_alignTop="@+id/textView2"
        android:layout_toRightOf="@+id/imageDisplay" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="fill_parent"
        android:textColor="@color/card_activated"
        android:layout_height="2dip"
        android:layout_below="@+id/spinner1"
        android:layout_centerHorizontal="true"
        android:background="@color/card_activated"
        android:layout_margin="10dip"
         />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/card_header_inner_simple_title"
        android:layout_below="@+id/autoCompleteTextView1"
        android:layout_marginTop="10dip"
        android:layout_marginLeft="20dip"
        android:textSize="20sp"
        android:textStyle="bold"
        android:text="Total" />

    <ImageView
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView6"
        android:layout_below="@+id/textView6"
        android:src="@drawable/cancel" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageDisplay"
        android:layout_marginBottom="23dp"
        android:layout_marginLeft="10dip"
        android:layout_marginTop="10dip"
        android:layout_toRightOf="@+id/imageDisplay"
        android:text="$ 10"
        android:textColor="@color/light_green"
        android:textSize="20sp"
        android:textStyle="bold" />

     <ImageView
        android:id="@+id/checkout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:layout_below="@+id/textView4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:adjustViewBounds="true"
        android:layout_gravity="center"
        android:src="@drawable/checkout" />

     <AutoCompleteTextView
         android:id="@+id/autoCompleteTextView1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignRight="@+id/card_header_inner_simple_title"
         android:layout_below="@+id/textView3"
         android:alpha=".4"
         android:ems="9"
         android:focusable="false"
         android:gravity="center"
         android:text="Add optional note to chef"
         android:textColor="@color/abs__background_holo_dark"
         android:textStyle="italic" >

         <requestFocus />
     </AutoCompleteTextView>

     <TextView
         android:id="@+id/textView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignLeft="@+id/textView2"
         android:layout_alignTop="@+id/imageDisplay"
         android:gravity="center_vertical"
         android:text="Red Horse"
         android:textSize="20sp"
         android:textStyle="bold" />

     <TextView
         android:id="@+id/subtotal"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_above="@+id/checkout2"
         android:layout_toLeftOf="@+id/cancel"
         android:gravity="center"
         android:text="$ 10"
         android:textSize="20sp"
         android:textStyle="bold" />

</RelativeLayout>

Update:
  @Override
  public View getView(final int position, View convertView, final ViewGroup parent) {

    Viewholder v = new Viewholder();
    View rowView = convertView;

    if(!imageLoader.isInited()){

        imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));

    }

    if(rowView == null){
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         rowView = inflater.inflate(R.layout.inner_base_header_cutom, null);
         v.img = (ImageView)rowView.findViewById(R.id.imageDisplay);
         v.remove = (ImageView)rowView.findViewById(R.id.cancel);

         //Viewholder viewHolder = new Viewholder();

         rowView.setTag( v);
    }
    else{
        v = (Viewholder) rowView.getTag();
    }

     if(v.img!=null && imageLoader != null){
            imageLoader.displayImage("http://assets.bigdealsmedia.net/images/13407.jpg",  v.img, options);

     }
     v.remove.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            remove(list.get(position));

            //adapter.notifyDataSetChanged();

            //

        }
    });

    return rowView;
  }

Comment: post the adapter code. layout probabky has nothing to do with this
Comment: I am using cardslib. I added a link above. Thanks
Answer: It's probably not the item, check your listview width/height they should both be set to match_parent. Setting the listview width to wrap_content kills your render times.
You generally want to avoid wrap_content on any xml layout. Try setting the parent element's width and height to match_parent as well, and for some of the children views you can probably atleast set the width to match_parent.
maybe post some of the getView() code from your adapter as well.
Also change your inflation from this
 rowView = inflater.inflate(R.layout.inner_base_header_cutom, null);

to this
 rowView = inflater.inflate(R.layout.inner_base_header_cutom, parent,false);

Comment: It was in a google io presentation by one of the core android developers. https://www.youtube.com/watch?v=wDBM6wVEO70  basically wrap_content has to measure atleast twice before its drawn, usually a lot. I probably increased the efficiency of my adapters 100 fold. Use view holders, and for your images have some sort of caching, LRU cache is super easy to use. Check out my edited solution
Comment: Thanks for a very useful tips! I got `wrap_content` only on listview height, so I changed that. I added the code for my adapter
Comment: By the way, In which part of the documentation did you learn the `match_parent` vs `content_wrap` rendering? I wanted to learn more.
Comment: Does this mean that `wrap_content` could eat up the memory while its being rendered a couple of times, right?
Comment: I dont know how much memory it consumes but onMeasure will be called multiple times for views with wrap_content
Comment: one last tip, in your adapter, I would just get the layoutInflater when the class first loads and reference it instead of each time in getView(), not sure how big of a performance increase that will be but  it should help
Comment: Just imagine a whole bunch of `warp_content` on my application, this will be scary. I will be optimizing my codes on this end.
Comment: the only time you're going to notice is in something like a listview otherwise the performance is negligible
Comment: Very very helpful! you made my day!
Answer: In my few experimentation, the library does not cater heavy UI.
So what I did, I just used a simple listview, then in my cutom array adapter i still used viewholder class, and use a style to look the layout like a card.

RelativeLayout causes lag on Listview


Criar Dto pelo Construtor com um parametro List de uma entidade Hibernate

Question: Eu tenho uma @Query do Spring, que realiza uma consulta ao banco por uma Entidade, para criar alguns Objetos DTO. E as propriedades desse objeto DTO, eu passo via Construtor, mas eu precisava passar como parâmetro no Construtor um List que tem na Entidade.
public OperacaoDTO(List<Staging> stagings, BigDecimal valor) {
        this.stagings = stagings;
        this.valor = valor;
    }

meu @Query
@Query("SELECT NEW br.com.teste.OperacaoDTO(operacao.stagings, operacao.valor) FROM Operacao operacao")
    List<OperacaoDto> findAll();

O problema que ele reclama dizendo que não tem um construtor apropriado no OperacaoDTO.
Existe algum modo de esse List da Entidade e passar no Construtor? porque eu vou realizar alguns tratamento nessa List
Comment: Você poderia fornecer o erro completo? Como está o mapeamento da entidade `Operacao`?
Answer: Você deve cria um construtor da seguinte forma para o objeto
OperacaoDTO(operacao.stagings, operacao.valor)

Os tipos devem ser iguais ao Objeto, por exemplo:
se valor for Double e stagings for String ficaria assim
public OperacaoDTO(String stagings, Double valor){
  this.stagings=stagings;
  this.valor=valor;
}

Você criou um construtor com uma lista
List<Staging> stagings, BigDecimal valor,

Tua query não retorna isso e sim um objeto com dois atributos.

Mais, se OperacaoDTO for do tipo @Entity deve ter o construtor vazio também, requisito do hibernate


Puppeteer with Nativescript workaround

Question: I'm trying to use Nativescript and puppeteer but currently it doesn't work. I tried to find another headless browser solution but i dont know if it exists for nativescript.
Answer: Puppeteer replaces Selenium while testing browser application. For mobile you use Appium (iOS / Android), where you will set isHeadless capability to true.
There is already an issue at Github repo which explains how it's done.

Set "isHeadless":true on desired device in appium.capabilities.json
Comment: @Vaviloff Thank you for pointing, I have corrected my statement.
Comment: Actually puppeteer is not used with Selenium, it can be used *instead* of it.

Puppeteer with Nativescript workaround


Connecting to unbalanced inputs from balanced XLR output

Question: I'm looking at setting up something like the Behringer RX1602 in front of my current mixer to add more stereo inputs to it. These stereo inputs are chiefly regular consumer audio devices such as an old cassette deck with an RCA output - all unbalanced stereo which it seems the mixer should deal with easily enough.
I then need to split the output of this mixer into two separate stereo outputs, one of which will be fed to a line in on a PC and the other to a further mixer (ultimately for listening with headphones; I already have this final mixer set up). I'm looking at something like the MX882 splitter/mixer for splitting, the mixer part giving slight additional flexibility if i need to change this configuration in the future.
The problem I have is that the splitter/mixer only has balanced XLR connectors, while all inputs and one output from it are going to be unbalanced signals over RCA or 1/4" TS connectors. Can I simply get (or solder) cables with the inverted and ground wires connected normally on the XLR side but both connected to ground on the unbalanced mono connector side? Will this work for outputs? If not, what kind of a device or setup would be advisable in between?
Comment: ...but even if I do have enough gain to compensate for whatever attenuation there is, I *probably* should at least put in some kind of balun ("passive DI") in, right?
Comment: I don't think simply making some custom TS/XLR cables is likely to work well due to mismatched impedance. The unbalanced signals coming from your audio sources will be high impedance, while the mixer expects low impedance inputs. The usual solution for this problem is a a [DI box](https://en.wikipedia.org/wiki/DI_unit).
Comment: Alex Basson's suggestion is probably the best idea, although it's quite feasible to connect differing impedance mics, etc., hi into low, low into hi, but it can introduce noise, and the volume/trim pots may not be able to compensate.
Comment: I suppose that's about what I expected, though I was mostly worried about what happened if you connected the inverted signal on the output to ground instead of impedance. I didn't even think to think of impedance, honestly, but it's worth considering since I'm not completely sure how much wiggle room I have with the gain.
Answer: Before spending money or making custom cables, try the headphone output of the RX1602 as your second output. With its level control initially set way down of course.  Don't argue why it won't work, just try!   You may have a nice surprise.
Comment: That does seem like an acceptable solution to the specific problem of needing a splitter, though I think I'll be getting the splitter/mixer I'm looking at *anyway* at some point because it allows for some interesting configurations (looking at the documentation it looks like it allows you to pass main in through one output while mixing additional inputs to main out) - in which case I'll still need to figure out how to deal with it. I've drawn some potential topologies, I'll have to see how this meshes with what I have.


A seemingly simple ANOVA problem in R: Factor naming changes result output

Question: I suspect this is an easy question but I don't know what the answer is and would appreciate any help.
I have a dataset (UWb) like this...
  subject whitelvl stainlvl bwhite  aged stained fresh wellbeing
1       2     1       1     80.75  10.50   85.50 14.75     16.50
2       2     2       2     72.25  71.50   54.25 40.00     28.50
3       2     3       6     67.50  58.50   48.50 39.25     33.75
4       2     1       1     66.00  64.00    0.25 72.75     69.50

When I do an ANOVA with this I get a normal output, like the following
                    Df Sum Sq Mean Sq F value    Pr(>F)
Whitelvl             1  95755   95755 752.265 < 2.2e-16 ***
Stainlvl             1  77918   77918 612.135 < 2.2e-16 ***
Whitelvl:Stainlvl    1   1745    1745  13.712 0.0002182 ***
Residuals         2246 285890     127
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

However, in order to make this easier for others to read I have changed the names of the levels of the two factors: whitelvl and stainlvl, with the following code...
UWb$Whitelvl<-factor(c("1","2","3"))
levels(UWb$Whitelvl)
UWb$Stainlvl<-factor(c("1","2","6"))
levels(UWb$Stainlvl)
UWb$Whitelvl<-revalue(UWb$Whitelvl, c("1"="Bright", "2"="Dull", "3"="Grey"))
UWb$Stainlvl<-revalue(UWb$Stainlvl, c("1"="None","2"="Light","6"="Strong"))

This creates the following changes...
  subject whitelvl stainlvl bwhite  aged stained fresh wellbeing
1       2   Bright     None  80.75 10.50   85.50 14.75     16.50
2       2     Dull    Light  72.25 71.50   54.25 40.00     28.50
3       2     Grey   Strong  67.50 58.50   48.50 39.25     33.75
4       2   Bright     None  66.00 64.00    0.25 72.75     69.50

However when I do an anova with the same code as above...
whiteness.aov = aov(BWhite ~ Whitelvl*Stainlvl, data=UWb)
summary(whiteness.aov)

I get the following...
              Df Sum Sq Mean Sq F value Pr(>F)
whitelvl       2      0     0.0       0      1
Residuals   2247 461309   205.3

I presume its something about turning the conditions into factors, but that is what they are so why is this causing R a problem? Is there a way to rename and get the same results as the first ANOVA?
Answer: Ah. Simple.
UWb$Whitelvl<-factor(c("1","2","3"))
UWb$Stainlvl<-factor(c("1","2","6"))

The code above replaces whitelvl and stainlvl with two perfectly correlated sequences of factors.
In R, if you attempt to insert a shorter vector in a longer one, if the longer is a multiplicity of the shorter, you don't get an error. By a freak chance, the number of rows in Uwb is divisible by three, so you don't get an error.
I guess you meant
UWb$Whitelvl<-factor(Uwb$Whitelvl, levels=c("1","2","3"))
UWb$Stainlvl<-factor(Uwb$Stainlvl, levels=c("1","2","6"))

Comment: It seems so obvious now, which is always the sign of a great answer! Thank you so much.


PHP - Unir array com array multidirecional PHP

Question: Como fazer para unir arrays com um array multidimensional:
Array (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => Array ( [cod_setor] => 1 )
        [6] => Array ( [cod_setor] => 2 )
        [7] => Array ( [cod_setor] => 3 )
        [8] => Array ( [cod_setor] => 5 )
)

Veja como esta meu código:
//$item_inventarios = valor recebido da controller codeigniter

$inicial = $listar_menor_maior_setor[0]['menor_cod_setor'];
$final = $listar_menor_maior_setor[0]['maior_cod_setor'];

$lista = range($inicial, $final);
$total = array_merge($lista,$item_inventarios);

print_r($total);

O resultado esperado seria este:
Array (
        [0] => Array ( [ambiente_setor] => 1 )
        [1] => Array ( [ambiente_setor] => 2 )
        [2] => Array ( [ambiente_setor] => 3 )
        [3] => Array ( [ambiente_setor] => 4 )
        [4] => Array ( [ambiente_setor] => 5 )
        [5] => Array ( [cod_setor] => 1 )
        [6] => Array ( [cod_setor] => 2 )
        [7] => Array ( [cod_setor] => 3 )
        [8] => Array ( [cod_setor] => 5 )
)

Comment: Que tipo de união seria essa? Qual seria o resultado esperado?
Comment: O resultado esperado seria este:

`Array (
        [0] => Array ( [ambiente_setor] => 1 )
        [1] => Array ( [ambiente_setor] => 2 )
        [2] => Array ( [ambiente_setor] => 3 )
        [3] => Array ( [ambiente_setor] => 4 )
        [4] => Array ( [ambiente_setor] => 5 )
        [5] => Array ( [cod_setor] => 1 )
        [6] => Array ( [cod_setor] => 2 )
        [7] => Array ( [cod_setor] => 3 )
        [8] => Array ( [cod_setor] => 5 )
)`
Answer: Existem várias operações possíveis com o arrays, diversas.
Por exemplo você pode usar o operador + para fazer isso, exemplo:
$array = [1,2,4];
$array_b = [5,6,7];
$array_sum = $array + $array_b;
print_r($array_sum); // [1,2,4,5,6,7]

Outra forma é através da função array_map:
$array_sum = array_map(function () {
   return array_sum(func_get_args());
 }, $array_a, $array_b);

 print_r($array_sum);

Voce também pode usar veridic functions:
$array_sum = array_map(function (...$arrays) {
    return array_sum($arrays);
}, $a, $b);

print_r($array_sum);

Somar dois arrays não se trata de framework, e sim lógica, mas basciamente é isso, agora é só pegar o contexto e aplicar na sua aplicação e lógica.
Para mais e duvidas sobre como funciona arrays sempre olhe a documentação antes, pois a documentação principalmente em inglês está cheia de referencias que possa ser uteis para voce e dicar e problemas em relação a sua duvida (principalmente a parte de arrays).
Comment: Obrigado por sua opinião.
A duvida não é somar somar dois arrays. ..Preciso unir dos arrays sendo que um deles é arrays multidimecional.

Nenhum os exemplos acima traria o resultado desejado.
Comment: Posso tá errando, mas tanto `array_merge` quanto `array_merge_recursive` apenas concatena os arrays.

No meu caso tenho um array criado dinamicamente com a função `range` que cria o array com valores de 1 a 5 e as chaves são geradas na sequencia também. queria que essas chaves fossem geradas com uma string com um valor único para todas as chaves do array.
Comment: Perfeito. Acabei mudando a logica do meu sistema para para tratar esses dados de um outra forma.
Comment: O termo correcto seria concatena-los, para isso você pode usar o `array_merge` ou `array_merge_recursive`, tem também o `array_replace_recursive`, os 3 resolvem seu problema de maneiras diferentes. Eu acredito que o `array_merge_recursive` será o suficiente para o seu caso, mas novamente, oriento que dê uma olhada na documentação para verificar como as funções vai resolver o seu problema dentro do contexto da sua aplicação.
Comment: Bem, entendi, talvez seja necessário voce manipular algumas coisas no seu array antes de reindexa-los, aqui tem uns exercicios sobre arrays e eu acho que a lógica por trás desse poderá te ajudar -> https://www.geeksforgeeks.org/minimum-sum-two-elements-two-arrays-indexes-not/
Comment: Olá, mas voce pode marcar qual é a resposta certa por favor? Assim ajudará outras pessoas com o mesmo problema.


collision detection program won't work in Turtle

Question: When I run the program it freezes up and doesn't work. The point of the program is to print something out when the x and y position coordinates of the user controlled turtle which is controlled by key-bindings is less then 10 pixels from the other turtle x and y position coordinates.
import turtle
import random
wn = turtle.Screen()
wn.setup(width = 450, height = 450)
player = turtle.Turtle()
player2 = turtle.Turtle()

def up():

    y  = player.ycor()
    y = y + 5
    player.sety(y)
    if y>=310:
        player.sety(y-15)

def down():
    y = player.ycor()
    y = y - 5
    player.sety(y)
    if y<-310:
        player.sety(y+15)

def left():
    x = player.xcor()
    x = x - 5
    player.setx(x)
    if x<=-625:
        player.setx(x+15)

def right():
    x = player.xcor()
    x = x + 5
    player.setx(x)
    if x>=625:
        player.setx(x-15)

player.penup()
player.setpos(0,0)
player.showturtle()
player.shape("square")
wn.bgcolor("green")
player2.shape("square")
player2.penup()
player2.setpos(300,300)
player2.showturtle()

turtle.listen()
turtle.onkeypress(up,"Up")

turtle.onkeypress(left,"Left")

turtle.onkeypress(right,"Right")

turtle.onkeypress(down, "Down")

def checkcollision(player,player2):
        if abs(player.xcor() - player2.xcor()) < 10 and abs(player.ycor() - player2.ycor()) < 10:
            player.write("collision")

while True:
    checkcollision(player,player2)

Comment: Good question. One thing: what actually happens when you run it?
Answer: I think it freezes because of the loop in your code:
while True:
    checkcollision(player,player2)

It's always checking the collision, move that code to the movement functions Up, Down, Left, Right etc and then call it after doing the movement.
Comment: I put the checkcollision inside the keystroke functions as you said and that worked great and the checkcollision works now however now I want to move the second turtle across the window set to a certain speed however the turtle isn't moving as seen here:
player.penup()
player.setpos(0,0)
player.showturtle()
player.shape("square")
wn.bgcolor("green")
player2.shape("turtle")
player2.penup()
player2.setpos(300,300)
player2.showturtle()
player2.setheading(-100)
player2.speed(2)
The only code i'v changed at all being the heading and the speed.
Comment: Thanks! Don't forget to accept answers which solved your problem. As for your next issue you'll have to ask another question as you can't combine them in a single thread.


How to find the eigenvectors of this $3 \times 3$ matrix?

Question: I need to find eigenvectors of the following matrix?
\begin{bmatrix}2&6&-15\\1&1&-5\\1&2&-6\end{bmatrix}
What I have done: I found eigenvalue $\lambda = -1$, then
\begin{bmatrix}3&6&-15\\1&2&-5\\1&2&-5\end{bmatrix}
\begin{bmatrix}1\;&2\;&-5\:\end{bmatrix}
$$x_1 = \begin{bmatrix}3\\ 1\\ 1\end{bmatrix}\qquad x_2 = \begin{bmatrix}-2\\1\\0\end{bmatrix}$$ How to find the last one?
Comment: There is no third eigenvector. Instead, there is a 2 by 2 Jordan block, as the minimum polynomial is $(x+1)^2.$
Comment: Take your original matrix as $A,$ let the next be $B = A + I.$ We have $B^2 = 0.$ So, take any vector $w$ that is not already an eigenvector of $A,$ meaning $Bw \neq 0.$  Relatively small numbers if we choose $w = (1,0,0)^T$ column vector. Then calculate $v=Bw,$ this $v$ really is an eigenvector. Finally, take an independent eigenvector, call it $u.$ The change of basis matrix is going to be $P,$ where the three columns of $P$ are $u,v,w$ in order. Find $P^{-1},$ and $J= P^{-1}AP$ will be in Jordan form.
Comment: @WillJagy Are you saying then that there is a generalized eigenvector associated to $-1$ so that we can complete a basis for $\mathbb R^3$?
Comment: There is no third eigenvector because the first two columns of your matrix are just multiples of each other.
Comment: @Math1000 yes.. I put an answer, the columns of $P$ are a basis
Comment: subtract $\lambda$ from  the diagonals and take the determinant and set it equal to 0 and solve for $\lambda$ usually by factoring this will give you all the eigen values then use those to find the vectors
Answer: As I indicated in comment, take
$$
P =
\left(
\begin{array}{rrr}
-2 & 3 & 1 \\
1&1&0 \\
0&1&0
\end{array}
\right)
$$
then calculate $P^{-1}$ and finally $ J=P^{-1} AP,$ where $A$ is your original matrix. I got lucky, as this $\det P = 1.$
The reason it is important to practice finding such a $P$ is that most applications use the reverse order, namely expressing $A = PJ P^{-1}$