text:
Q: Express ${x^3 + 2x^2 + 61 \over (x + 3)^2 (x^2 + 4)}$ in partial fractions $$\eqalign{
  & {x^3 + 2x^2 + 61 \over (x + 3)^2(x^2 + 4)} \equiv {A \over (x + 3)} + {B \over (x + 3)^2} + {Cx + D \over (x^2 + 4)}  \cr
  &  \equiv {A(x + 3)(x^2 + 4) + B(x^2 + 4) + (Cx + D)(x + 3)^2 \over (x + 3)^2(x^2 + 4)} \cr} $$
so:
$$x^3 + 2x^2 + 61 \equiv A(x + 3)(x^2 + 4) + B(x^2 + 4) + (Cx + D)(x + 3)^2$$
Solving for $B$, making $x=-3$:
$$\begin{align}
 - 27 + 18 + 61 & = 0 + 13B + 0  \\[6pt]
  13B & = 52  \\[6pt]
  B & = 4 \end{align} $$
The other three variables are tricky as there is no value that I can see that is capable of eliminating two and leaving one, I've tried to "compare coefficients" but I am left with more than one unknown so I think the only other options available to me is solving simultaneously with 3 variables (something I do not know how to do), have i missed something that could make this easier to write in partial fractions?
Thank you.

A: You're doing the problem right.  I don't think there's a way of avoiding solving a $3\times 3$ system.  However, you can try "nice" values for $x$ to make it a nice system, e.g. $x=0, x=1, x=-1$.


text:
Q: What is the code to get the Processor Name and Processor Group Name Is there a way in Groovy Code to get the Processor Group Name the ExecuteScript Processor is in and Processor Name of the ExecuteScript Processor the Groovy Code is in. If so what would the code be. Any help would be greatly appreciated.

A: To get the processor name, use ProcessContext#getName(). The ProcessContext class is referenceable from ExecuteScript via the provided variable context, so the code would be String processorName = context.getName().
To get the process group name, I am not aware of an easy way through the framework code. You can, of course, use the Apache NiFi REST API to request the list of process groups and iterate through, checking to see if the process group contains a processor with the identifier of the current processor.

A: to get the name of all the processors and process groups name, you can use
the following code.
final EventAccess access = context.getEventAccess();
final ProcessGroupStatus procGroupStatus = access.getControllerStatus();
procGroupStatus.getProcessGroupStatus();
final ProcessorStatus processorstatus = procGroupStatus.getProcessorStatus()

ProcessorStatus class contains getName method, which can be used to get the name other processor.
Below is the source code of the same class for your reference.
https://github.com/apache/nifi/blob/master/nifi-api/src/main/java/org/apache/nifi/controller/status/ProcessorStatus.java

redpajama_set_name: RedPajamaStackExchange


text:
Q: Constraint - one boolean row is true, all other rows false I have a column: standard BOOLEAN NOT NULL
I would like to enforce one row True, and all others False. The are no FK's or anything else depending on this constraint. I know I can accomplish it with plpgsql, but this seems like a sledgehammer. I would prefer something like a CHECK or UNIQUE constraint. The simpler the better.
One row must be True, they cannot all be False (so the first row inserted would have to be True).
The row will need to be updated, which means I have to wait to check constraints until updates are done, since all rows may be set False first and one row True afterwards.
There is a FK between products.tax_rate_id and tax_rate.id, but it has nothing to do with the default or standard tax rate, which is user selectable to ease creating new products..
PostgreSQL 9.5 if it matters.
Background
The table is the tax rate. One of the tax rates is the default (standard since default is a Postgres command). When a new product is added, the standard tax rate is applied to the product. If there is no standard, the database must either do a guess or all kinds of unneeded checks. The simple solution, I thought, was to make sure there is a standard.
By "default" above, I mean for the presentation layer (UI). There is a user option for changing the default tax rate. I either need to add extra checks to ensure the GUI/user does not try to set the tax_rate_id to NULL, or then just set a default tax rate.

A: Variant 1
Since all you need is a single column with standard = true, set standard to NULL in all other rows. Then a plain UNIQUE constraint works, since NULL values do not violate it:
CREATE TABLE taxrate (
   taxrate int PRIMARY KEY
 , standard bool DEFAULT true
 , CONSTRAINT standard_true_or_null CHECK (standard) -- that's all
 , CONSTRAINT standard_only_1_true UNIQUE (standard)
);

DEFAULT is an optional reminder that the first row entered should become the default. It's not enforcing anything. While you cannot set more than one row to standard = true, you can still set all rows NULL. There is no clean way to prevent this with only constraints in a single table. CHECK constraints do not consider other rows (without dirty tricks).
Related:

*

*Restrict two specific column values from existing at the same time

*Add constraint to make column unique per group of rows
To update:
BEGIN;
UPDATE taxrate SET standard = NULL WHERE standard;
UPDATE taxrate SET standard = TRUE WHERE taxrate = 2;
COMMIT;

To allow a command like (where the constraint is only satisfied at the end of the statement):
WITH kingdead AS (
   UPDATE taxrate
   SET standard = NULL
   WHERE standard
   )
UPDATE taxrate
SET standard = TRUE
WHERE taxrate = 1;

.. the UNIQUE constraint would have to be DEFERRABLE. See:

*

*Constraint defined DEFERRABLE INITIALLY IMMEDIATE is still DEFERRED?
dbfiddle here
Variant 2
Have a second table with a single row like:
Create this as superuser:
CREATE TABLE taxrate (
   taxrate int PRIMARY KEY
);

CREATE TABLE taxrate_standard (
   taxrate int PRIMARY KEY REFERENCES taxrate
);

-- singleton!
CREATE UNIQUE INDEX taxrate_standard_singleton ON taxrate_standard ((true));

REVOKE DELETE ON TABLE taxrate_standard FROM public;  -- can't delete

INSERT INTO taxrate (taxrate) VALUES (42);
INSERT INTO taxrate_standard (taxrate) VALUES (42);

Now there is always a single row pointing to the standard (in this simple case also representing the standard rate directly). Only a superuser could break it. You might disallow that, too, with a trigger BEFORE DELETE.
dbfiddle here
Related:

*

*Constraint to enforce "at least one" or "exactly one" in a database
You might add a VIEW to see the same as in variant 1:
CREATE VIEW taxrate_combined AS
SELECT t.*, (ts.taxrate = t.taxrate) AS standard
FROM   taxrate t
LEFT   JOIN taxrate_standard ts USING (taxrate);

In queries where all you want is the standard rate, use (only) taxrate_standard.taxrate directly.

You later added:

There is a FK between products.tax_rate_id and tax_rate.id

A poor man's implementation of variant 2 would be to just add a row to products (or any similar table) pointing to the standard tax rate; a dummy product you might call "Standard tax rate" - if your setup allows it.
The FK constraints enforces referential integrity. To complete it, enforce tax_rate_id IS NOT NULL for the row (if that's not the case for the column in general). And disallow its deletion. Both could be put into triggers. No extra table, but less elegant and not as reliable.

A: You can use a Filtered index

create table test
(
    id int primary key,
    foo bool
);

CREATE UNIQUE INDEX only_one_row_with_column_true_uix
    ON test (foo) WHERE (foo);  --> where foo is true

insert into test values (1, false);
insert into test values (2, true);
insert into test values (3, false);
insert into test values (4, false);
insert into test values (5, true);

ERROR:  duplicate key value violates unique constraint "only_one_row_with_column_true_uix"
DETAIL:  Key (foo)=(t) already exists.

dbfiddle here

But as you said, first row must be true, then you could use a CHECK constraint, but even using a function you can delete first row later.

create function check_one_true(new_foo bool)
returns int as
$$
begin
    return
    (
        select count(*) + (case new_foo when true then 1 else 0 end)
        from test
        where foo = true
    );
end
$$
language plpgsql stable;

alter table test
    add constraint ck_one_true check(check_one_true(foo) = 1);

insert into test values (1, true);
insert into test values (2, false);
insert into test values (3, false);
insert into test values (4, false);

insert into test values (5, true);

ERROR:  new row for relation "test" violates check constraint "ck_one_true"
DETAIL:  Failing row contains (5, t).

select * from test;

id | foo
-: | :--
 1 | t
 2 | f
 3 | f
 4 | f

delete from test where id = 1;

dbfiddle here

You could solve it by adding a BEFORE DELETE trigger to ensure first row (foo is true) is never deleted.

create function dont_delete_foo_true()
returns trigger as
$x$
begin
    if old.foo then
        raise exception 'Can''t delete row where foo is true.';
    end if;
    return old;
end;
$x$ language plpgsql;

create trigger trg_test_delete
before delete on test
for each row
execute procedure dont_delete_foo_true();

delete from test where id = 1;

  ERROR:  Can't delete row where foo is true.

dbfiddle here


text:
Q: How can I convert Java code to Jasmin without compiling? I need to convert some pieces of a class into Jasmin (or if possible, Smali) and mix new codes with disassembled ones together.
What I want to know is: Is that possible? and if yes, How?
(I have diff patches of java files but don't have source code of Jar files, so I decided to do it this way)

A: That depend.
1) If you are talking about android code (calsses.dex), you can disasm it using apktool, and then inject/edit the disassembled code. Finally you can reassemble that code (still using apktool, and ofcourse your new code should not contain syntax errors). You will also need to sign your new apk to be able to run it on your android device.
2) If you are just trying to get the source code from some jar, you can just decompile them using a decompiler like JDGUI and the get the source code (in JAVA lang). Be aware that your jar files might be obfuscated, so the resulting source code might be confused or just not working.
I'd say that if you have an apk with that code you want to modify, your best bet is disassembling it with apktool. Else if you are trying to do that just to recover a source code form jars (maybe have you lost your original source code??) you can try a decompiler.
Hope this helps.


text:
Q: SQL SUM negative value not being returned I have an SQL Query that looks like this -
    CREATE PROCEDURE [dbo].[getMemberFundUnits]
    -- Add the parameters for the stored procedure here
    @member int,
    @fundcode varchar(15),
    @closingdate datetime
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT (CASE WHEN SUM(units) IS Null THEN 0 ELSE SUM(units) END) As fundunits
    FROM pe_minv
    WHERE pmi_member = @member AND pmi_fund = @fundcode AND pmi_invested <= @closingdate

END

When I run the stored procedure like this -
DECLARE @return_value as float /*int*/

EXEC    @return_value = [dbo].[getFundUnits]
        @member = 9738,
        @fundcode = N'58193',
        @closingdate = N'07/21/2011'

SELECT  'Return Value' = @return_value

I get two results. The first is the correct one which is -0.0060  and the second @return_value which is 0
This is also the case when I call the stored procedure from my code, I get a 0 back instead of the -0.0060 that I want.
This is how I am calling the stored procedure from my code:
 Dim ds As New DataSet()

    Dim cmd As New SqlCommand("getMemberFundUnits", conn)
    cmd.CommandType = CommandType.StoredProcedure

    Dim p_pm_member As New SqlParameter("@member", SqlDbType.Int)
    p_pm_member.Value = pm_member
    cmd.Parameters.Add(p_pm_member)

    Dim p_fund_code As New SqlParameter("@fundcode", SqlDbType.VarChar)
    p_fund_code.Value = fund_code
    cmd.Parameters.Add(p_fund_code)

    Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
    p_period_closing_date.Value = period_closing_date
    cmd.Parameters.Add(p_period_closing_date)

    Dim da As New SqlDataAdapter(cmd)
    da.Fill(ds)

Does anyone have any ideas why this might be happening?
Thanks!

A: DECLARE @return_value as int

Your variable is defined as int. Int can't hold decimal values, so the return value is rounded. Try to declare your var as float.
List of SQL Server data types

A: The RETURN is always int so it is truncated inside the stored procedure.
As per MSDN

RETURN [ integer_expression ]

You need to use an OUTPUT parameter that is float:
CREATE PROC [dbo].[getFundUnits]
    @member...,
    @fundcode...',
    @closingdate...,
    @SummedValue float OUTPUT
AS
...
SELECT @SummedValue = (CASE WHEN SUM(nits) IS Null THEN 0 ELSE SUM(units) END) As fundunits
...
GO

And you call it as
DECLARE @return_value as float

EXEC    [dbo].[getFundUnits]
        @member = 9738,
        @fundcode = N'58193',
        @closingdate = N'07/21/2011',
        @return_value OUTPUT

SELECT  'Return Value' = @return_value

RETURN is used (if at all) only for execution status usually: meaningful data is via output parameters or a resultset. I no longer use RETURN...

A: Try declaring the return value as Decimal with precision.
DECLARE @return_value as decimal(18,4)

Also, why are you filling a dataset for only returning one column. Use a sqldatareader and retrieve the values as decimal. Dataset is very resource intensive.


text:
Q: Python (Flask) - Show loading message/gif for matplotlib generated image (html) I am fairly new to web development in general, so this question might show some inexperience. My apologies.
Working application: user inputs x- and y values in the /showgraph route --> matplotlib generates the plot which is shown in the same route.
Here is the code part similar to my problem:
html:
...
<form class="graphs" method="POST", action="{{ url_for('showgraph') }}">
  <input placeholder="x-value" name="valx" id="xvalue">
  <input placeholder="y-value" name="valy" id="yvalue">
  <input type="submit" name="showgraph" value="Show Graph" id="inputvalues">
</form>
{% if buttonclick[0]=="Show Graph" %}

{% endif %}
...

Python (using Flask)
@app.route('/fig/<val>', methods=['GET', 'POST'])
def fig(val):
    import matplotlib.pyplot as plt
    import StringIO
    import ast
    val=ast.literal_eval(str(val))
    x=[float(i) for i in val[0][0].strip('[]').split(',')]
    y=[float(i) for i in val[1][0].strip('[]').split(',')]
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x,y)
    img = StringIO.StringIO()
    fig.savefig(img)
    img.seek(0)
    return send_file(img, mimetype='image/png')

@app.route('/showgraph/',methods=['GET','POST'])
def showgraph():
   valx=(request.form.getlist('valx'))
   valy=(request.form.getlist('valy'))
   val='('+str(valx)+','+str(valy)+')'
   buttonclick=request.form.getlist('showgraph')
   return render_template("graphs.html",buttonclick=buttonclick,val=val)

Now when I enter some x and y values (e.g x=[1,2,3] and y=[3,2,1]) the page shows the alt ("Image placeholder") first and after 5 or 6 seconds the image (graph) is shown.
Is there a way to to overcome this problem and just show a loading message,gif,..?
(I'm still working on a more efficient and cleaner method to make an array of the input values. I can imagine this method might look a bit devious for some. )
Thanks!

A: You can use the lowsrc attribute of the img tag. Instead of

try

where loading.gif is a placeholder image that shows a (possibly animated?) loading message.
Hint: You can create loading gifs at http://www.ajaxload.info/


text:
Q: How to do LU Factorization? I'm not 100% certain if I understand LU Factorization. EDIT: I'm trying to solve Ax=b END EDIT Here's my problem:
$$A = \begin{bmatrix} 4&3&-5\\ -4&-5&7\\ 8&6&-8\\ \end{bmatrix} =  \begin{bmatrix} 1&0&0\\ -1&1&0\\ 2&0&1\\ \end{bmatrix} \begin{bmatrix} 4&3&-5\\ 0&-2&2\\ 0&0&2\\ \end{bmatrix}$$
$$b = \begin{bmatrix} 2\\ -4\\ 6\\ \end{bmatrix}$$
I get that $ L = \begin{bmatrix}1&0&0\\ -1&1&0\\ 2&0&1\\ \end{bmatrix}$ and that $U = \begin{bmatrix}4&3&-5\\ 0&-2&2\\ 0&0&2\\ \end{bmatrix}$ but am i suppose to multiply a row in L by b after that?
EDIT
Realized that I made a mistake. I believe that [L b] is supposed to be represented like $ [L b] = \begin{bmatrix}1&0&0&2\\ -1&1&0&-4\\ 2&0&1&6\\ \end{bmatrix}$ while [U b] would be $[U b] = \begin{bmatrix}4&3&-5&2\\ 0&-2&2&-4\\ 0&0&2&6\\ \end{bmatrix}$
END EDIT
Also if I wanted to find Ax=b by ordinary row reduction would I just use row reduction on A or take A time b and then row reduce?
I'm still new to Linear Algebra and have no idea how to go about this.

A: You are trying to solve $Ax = b$. Since you already have the LU decomposition of the matrix $A$, this reduces to $LUx = b$. By the associativity of matrix multiplication this means solving $L(Ux) = b$, where $Ux$ is just another vector in $\mathbb{R}^3$.
What you can do here, is to introduce another variable $y = (y_1, y_2,y_3)^T$ and solve $Ly = b$ for $y$. Then solving $Ux = y$ will give you the solution $x$.
If you know how matrix multiplication works, then it should be quite easy how to solve a system like $Ly = b$ for $y$, especially when $L$ is a tringular matrix.
If you are still clueless, the box below should help:

 \begin{align} \begin{pmatrix} l_{11} & 0 & 0 \\ l_{21} & l_{22} & 0 \\ l_{31} & l_{32} & l_{33}  \end{pmatrix} \begin{pmatrix} y_1\\y_2\\y_3 \end{pmatrix} = \begin{pmatrix}y_1l_{11}\\l_{21}y_1+l_{22}y_2\\l_{31}y_1+l{32}y_2+l_{33}y_3\end{pmatrix} = \begin{pmatrix}b_1\\b_2\\b_3\end{pmatrix}\end{align}

Edit: Generally to solve a system like $Ax= b$, you can write down your augmented matrix $[A\ b]$ and then use row reduction on that matrix. This is the standard approach to solving systems of linear equations, which is explained in pretty much every linear algebra book way better than I could possibly explain.
However, if you have a LU factorization of a matrix, finding a solution of the system is possible without any row reduction. you can do what i described above and then directly solve for $x$ (after solving for $y$) by just multiplying out the matrices with vectors. (If you check the box above, you can see for example that $y_1$ is explicitly given by $\frac{b_1}{l_{11}}$. The same way you could then find $y_2$ and $y_3$)


text:
Q: Mirror for Fedora core 4 still available? I'm trying to rebuild ELDK 4.0, which uses Fedora Core 4 as its base. Can anyone direct me to a mirror that still hosts the files?

A: Old Fedora releases are kept in http://archive.fedoraproject.org/pub/archive/fedora/, for example Fedora Core 4.


text:
Q: Using a Qt library from a C program Qt is great for building applications, but once or twice I have wanted to show a nice Qt dialog from an existing application that is written in pure C.
I want to describe how to create a Qt-based shared or static library that is usable by a Qt-unaware program. To narrow down the problem, let's assume that we call a function that shows some dialogs or widgets, and does not return until all dialogs have been closed. Otherwise it can't be done without some 'cooperation' from the hosting process - it has to at least run the message pump for Qt.
In this example I will use the Windows program rundll32.exe to load and execute a function that shows the Qt about dialog.

A: Let's say our DLL is called MyQtBasedDll.dll, and it has a single exported function - void MyEntryPoint().
We will run it using the command line rundll32.exe MyQtBasedDll.dll,MyEntryPoint. Note you need to give full paths for the exe and dll.
In order for rundll32.exe to load and use the program, MyEntryPoint() should have a C-calling convention. Additionally, we need a QApplication instance to do any GUI stuff, and  rundll32.exe will obviously not create it for us.
To create the Qt library with Qt Creator, we can choose File->New File or Project->Libraries->C++ Library, and the project name should be MyQtBasedDll.
The code of the MyEntryPoint() function is pretty simple:
extern "C"
{
__declspec(dllexport) void MyEntryPoint()
{
    if (!QApplication::instance()) {
        QApplication a(__argc, __argv);
        QMessageBox::aboutQt(0);
    } else {
        QMessageBox::aboutQt(0);
    }
}
}

This function can be called multiple times by the same exe, and each time a new QApplication object is constructed, only for the duration of the function. Note that we check for an existing instance so our DLL will work even when called by a Qt application.
Now all you need to do is substitute QMessageBox::aboutQt(0); with your function that does useful stuff!


text:
Q: How can I remove an unwanted node from a list of XElements? I need to use C# to manicure the response from a service before handing it off to the caller. The service takes a series of requests in XML format, formats the message and send it to the service. The response looks similar to this:
<SvcRes>
    <SvcVer>1.0</SvcVer>
    <MsgUUID>12345678-1234-1234-1234-123456789012</MsgUUID>
    <Svc>
        <SvcParms>
            <ApplID>App</ApplID>
            <SvcID>AppSrch</SvcID>
            <SvcVer>1.0</SvcVer>
        </SvcParms>
        <MsgData>
            <AppResData>
                <Key>xxxxxxxx</Key>
                <Rslt>xxxxxxxx</Rslt>
                <ErrCde>0</ErrCde>
                <ApplMsgLst>
                    <ApplMsg>
                        <ApplMsgApplId>D6</ApplMsgApplId>
                        <ApplMsgNbr>0</ApplMsgNbr>
                        <ApplMsgTxt>INQUIRY COMPLETE     09:23:53</ApplMsgTxt>
                        <ApplMsgErrInd>N</ApplMsgErrInd>
                    </ApplMsg>
                </ApplMsgLst>
            </AppResData>
        </MsgData>
        <ErrCde>0</ErrCde>
        <ErrMsg/>
    </Svc>
    <Svc>
        <SvcParms>
            <ApplID>DP</ApplID>
            <SvcID>DPKywrd</SvcID>
            <SvcVer>1.0</SvcVer>
            <RqstUUID>12345678-1234-1234-1234-123456789012</RqstUUID>
        </SvcParms>
        <MsgData>
            <AppResData>
                <Key>xxxxxxxx</Key>
                <Rslt>xxxxxxxx</Rslt>
                <ErrCde>0</ErrCde>
                <ApplMsgLst>
                    <ApplMsg>
                        <ApplMsgApplId>D6</ApplMsgApplId>
                        <ApplMsgNbr>0</ApplMsgNbr>
                        <ApplMsgTxt>INQUIRY COMPLETE     09:23:53</ApplMsgTxt>
                        <ApplMsgErrInd>N</ApplMsgErrInd>
                    </ApplMsg>
                </ApplMsgLst>
            </AppResData>
        </MsgData>
        <ErrCde>0</ErrCde>
        <ErrMsg/>
      <Svc>
    <ErrCde>0</ErrCde>
    <ErrMsg>Success</ErrMsg>
</SvcRes>

I need to pull out the AppResData nodes, then strip out the ApplMsgLst nodes from each of them before sending the results back to the caller. The resulting XML should be like this:
<AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
</AppResData>
<AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
</AppResData>

I can get a list of XElement nodes using the following 2 lines of code:
var xml = XElement.Parse(xmlResponse);
var msgData = xml.DescendantsAndSelf("MsgData");

*

*then I can do string.Concat(msgData.Nodes()) to get the final string to return to the caller -- BUT at this point I don't know how to delete the inner ApplMsgLst nodes. I have tried converting it back to a string and reparsing, but of course it complains about multiple root elements. I have tried every Remove combination I can think of, but they always remove too much (everything) or nothing..

Is there another way to do this? There is no file, this is all string data in a SOAP web service.

A: Here is an XSLT based solution.
Parameters:

*

*Input XML as a string data type.

*XSLT as a file.

*Output XML as a string data type.

XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/SvcRes">
        <root>
            <xsl:for-each select="Svc/MsgData/AppResData">
                <xsl:copy>
                    <xsl:copy-of select="Key"/>
                    <xsl:copy-of select="Rslt"/>
                    <xsl:copy-of select="ErrCde"/>
                </xsl:copy>
            </xsl:for-each>
        </root>
    </xsl:template>
</xsl:stylesheet>

c#
void Main()
{
    const string XSLTFILE = @"e:\Temp\DaveN59.xslt";
    string inputXML = @"<SvcRes>
        ...
    </SvcRes>";

    try
    {
        StringReader rdr = new StringReader(inputXML);
        XPathDocument XPathDoc = new XPathDocument(rdr);

        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(XSLTFILE);

        StringWriter sw = new StringWriter();
        using (XmlWriter xwo = XmlWriter.Create(sw, xslt.OutputSettings))
        {
            xslt.Transform(XPathDoc, xwo);
        }

        Console.WriteLine(sw.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Output XML
<root>
  <AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
  </AppResData>
  <AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
  </AppResData>
</root>

A: You can try this with Cinchoo ETL - an open source library to do this transformation easily
StringBuilder xml = new StringBuilder();

using (var r = ChoXmlReader.LoadText("*** YOUR XML CONTENTS ***")
    .WithXPath("//AppResData")
    .WithField("Key")
    .WithField("Rslt")
    .WithField("ErrCde")
    )
{
    using (var w = new ChoXmlWriter(xml)
        )
    {
        w.Write(r);
    }
}
Console.WriteLine(xml.ToString());

Output:
<Root>
  <AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
  </AppResData>
  <AppResData>
    <Key>xxxxxxxx</Key>
    <Rslt>xxxxxxxx</Rslt>
    <ErrCde>0</ErrCde>
  </AppResData>
</Root>


text:
Q: Laravel - How to make unique two fields using rules request In Laravel-8 I have this unique rules request validation:
public function rules()
{
    return [
        //company
        'companyName' => [
            'required',
            'string',
            'min:3',
            'max:100',
        ],
        'country_id' => [
            'nullable',
        ],
      ];
 }

How do I make companyName unique in relation to country_id?
Thanks

A: You can create a custom validation rule for your set of rules.
I'm suggesting that your Country has hasMany() relationship to Company
public function rules()
{
    return [
        //company
        'companyName' => [
            'required',
            'string',
            'min:3',
            'max:100',
            function($attribute, $value, $fail) {
                $country = Country::findOrFail(request()->get('country_id'));

                if(!$country->companies()->whereName(request()->get('companyName'))->get()->isEmpty()) {
                    $fail('Woops, there\'s a country with this name. Type another one, please :)');
                }
            },
        ],
        'country_id' => [
            'nullable',
        ],
      ];
 }

Read more about Custom Laravel Validation Rules here: https://laravel.com/docs/8.x/validation#custom-validation-rules


text:
Q: string matching in prototypejs I have following string in javascript.
str = 'This is link';

I want to get "This is link" from above string but not succeeded.
I tried this also
str.innerHTML

but getting undefined

A: In PrototypeJS, you can use the stripTags() function:
'a link'.stripTags();
 // -> 'a link'
 'a link'.stripTags();
// -> 'a linkalert("hello world!");'
 'a link'.stripScripts().stripTags();
// -> 'a link'

A: A string is not a DOM object.
The variable you have - str is a string, the innerHTML property only exists on DOM (Document Object Model) nodes, so you'll have to convert to that first to use this approach.
var div = document.createElement('div');
div.innerHTML = str;
var domNode = div.firstChild;

var textYouWant = domNode.innerHTML;

Or with jQuery
$(str).html();

A: Prototype's stripTags() will do the job but depending on your requirements you may not want to actually strip out all the HTML tags. If for example you have a  tag inside your  tag, stripTags() will remove that too. Here's how you'd do it in plain JavaScript using a regular expression:
function textFromLink(linkText) {
    return linkText.replace(/.*]*>\s*(.+)\s*<\/a>.*/, '$1');
}

The above function will return the content of the  tag, trimmed of whitespace, without touching other tags inside the  tag.


text:
Q: If $f$ is non negative measurable, $ \int f \lt \infty $ if and only if $\sum_{n=-\infty}^{\infty} 2^{n} m{(f\gt 2^n)} \lt\infty $ Let $f$ be non negative measurable. Prove that $ \int f \lt \infty $ if and only if  $\sum_{n=-\infty}^{\infty} 2^{n} m{(f\gt 2^n)} \lt\infty $.
This is a very popular question in Lebesgue integration. I have seen similar type of question so frequently in which sum varies from $0$ to $\infty$. But I do not have valid ideas to prove  the current above one.

A: The sum $s = \sum_{2^n<a} 2^n$ evaluates to $2^n$ where $n$ is the smallest integer such that $2^n\ge a$. Hence, $s/2\le a\le 2s$.
The above observation made, the proof consists of introducing $$g=\sum_{n}2^n \chi_{\{f>2^n\}}$$
and using the inequalities
$$g/2 \le f \le 2g $$


text:
Q: My ASP.NET MVC project loads slower Hi I have project developed in ASP.NET MVC. I am using Entity framework database first approach. Problem I am facing now is, first time when user loads my website, it takes time to load which is unusual. So I am searching for the reason behind this. Can anyone help me in this?
For a moment, I am assuming since I am using database first approach, I have to load all database to my project first before i connect. So I think it is making my website to load slower.
If this is the case, can someone guide me to generate connection string dynamically during run time in entity framework and connect to database?
I have stored procedure from which I can get connection string. But I dont know how can i use that connection string and connect to database.

A: When you say "first time when user loads my website, it takes time to load which is unusual" could you give us a comparison of how slow is slow the first time. And by "first time" is you mean after re-starting IIS or re-starting the app-pool, it may take some time as some of your code would have to be turned into native code by the just-in-time computer.
EF may slow you down if you have many hundreds of tables and it has to re-construct the context based on all of those tables and relationships. Even if it is the case, you would see the delay in every time you create a new EF context. But if this is the case, you may have to create multiple contexts each with a limited number of tables to manage. A good read on that http://msdn.microsoft.com/en-us/magazine/jj883952.aspx
Other than that, I would suggest you do the usual things such as pre compile your views (http://geekswithblogs.net/Aligned/archive/2013/05/28/pre-compiling-your-mvc-views.aspx) and use caching
Love to hear how it went


text:
Q: Minimum value of $ab+bc+ca-abc$ If $a,b,c>0$ and $a+b+c=1$ find the minimum value of $$ab+bc+ca-abc$$
I just found that maximum value of $ab+bc+ca-abc$ is $8/27$ by Schur's inequality.And i couldn't find the minimum value.Any help would be appreciated.

A: From $a,b,c > 0$ and $a+b+c=1$ , it follows that $0 < a,b,c < 1$.

Let $f(a,b,c)=ab+bc+ca-abc$.

From $a+b+c=1$ , it follows that $f(a,b,c)=(1-a)(1-b)(1-c)$, hence $f(a,b,c) > 0$.

Letting $a$ approach $1$ from below, and $b=c=(1-a)/2$, we get that $f(a,b,c)$ approaches $0$ from above.

Thus $f$ has a greatest lower bound of $0$, but $f$ has no minimum.

A: For $b=c\rightarrow0^+$ we obtain a value $0$.
But, $$ab+ac+bc-abc=(a+b+c)(ab+ac+bc)-abc>0,$$ which says that $0$ is an infimum and the minimum does not exist.

A: This is equal to
$$(1-a)(1-b)(a+b)$$
since it is the specialization $x=1$ of $(x-a) (x-b) (x-(1-a-b))$. This has no minimum value.


text:
Q: Removing commit from git history I've discovered that I have a file committed to my repo year ago, which I never wanted to be there.
Before I make my repo public I'd like to revert, or actually remove commit which introduced this file so no one will be able to access this file.
I've used interactive rebase so I was able to delete unwanted commit. It looked promising but after applying ~400 commits from 800 there is a conflict.
The conflict is caused by nonlinear history - there was a branch and one file was modified in both branches (lets say feature1 and feature2). As far as I've noticed git rebase tried to make this parallel history linear and it failed at those parallel, conflicting modifications. I don't want to try to fix it as there are much more such situations and It would be a big effort to fix all of them.
So my question is: is it possible to simply remove one commit with reconstruction of branch history without any influence on other commits?
My file was added once and was never modified, so none of other commits touch it.

A: You could try the filter-branch command.
git filter-branch --prune-empty --tree-filter 'rm <filename-to-delete> || true' HEAD

If the wrong commit just added the file to remove, the entire commit will be skipped (option --prune-empty).
I've tested this with a simple repo with a branch and a merge, and the merge was quite cleverly preserved. So you should not expect conflicts. And filter-branch creates a backup branch as well, sir. :-)


text:
Q: SNMP Custom MIB's, How to send non-Windows data over SNMP I want to send my own values over SNMP. So I have a program that will generate data. I want this data to be available over SNMP. How do I do this? Any advice will be appreciated.
Kind regards

A: You can extend the Windows SNMP agent by writing your own extensions,
http://www.codeproject.com/Articles/9024/How-to-develop-a-SNMP-extension-agent-DLL


text:
Q: Missing contacts in ABAddressBookCopyArrayOfAllPeople Im trying to find a phone number in the address book from my app and I was surprised not to find it.
The thing is that I've printed all the numbers of my address book in the console accessed by my app and strangely some of the contacts are missing, I was comparing the output with my address book, it's only few, but still.
This is how Im accesing the AddressBook:
 ABAddressBookRef addressBook = ABAddressBookCreate();
 NSArray *people = (NSArray *)   ABAddressBookCopyArrayOfAllPeople(addressBook);

 BOOL found = NO;
 NSString *name;
 int i = 0;
 while (!found) {//Here I print all the contact info, name and phone number
       ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];
       ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
       NSLog(@"el telf: %@ y nombre %@",tempPhone2, [NSString stringWithFormat:@"%@ %@",ABRecordCopyValue(person, kABPersonFirstNameProperty) ? (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty) : @"",ABRecordCopyValue(person, kABPersonLastNameProperty) ? (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty) : @""]);
      if([[key objectForKey:@"phone"] isEqualToString:tempPhone2]){
           found = YES;
      }
 }

Any idea why Im not accesing all the contacts in my Address Book?
[EDIT]
Weirdest thing is that when I use ABPeoplePickerNavigationController those missing contacts appear.

A: Please try the below.
ABAddressBookRef lAddressBook = ABAddressBookCreate();
CFArrayRef lRawAddressBookEntries =
ABAddressBookCopyArrayOfAllPeople(lAddressBook);
CFIndex lTotalContactsCount = ABAddressBookGetPersonCount(lAddressBook);
for (CFIndex i = 0; i < lTotalContactsCount; i++) {
    ABRecordRef lRef = CFArrayGetValueAtIndex(lRawAddressBookEntries, i);

    ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(lRef, kABPersonPhoneProperty);
    NSArray* phoneNumbers1 = (NSArray*)ABMultiValueCopyArrayOfAllValues(phoneNumberProperty);
    CFRelease(phoneNumberProperty);

    // Do whatever you want with the phone numbers
    if(phoneNumbers1 && [phoneNumbers1 isKindOfClass:[NSArray class]]) {
        for(NSString *stringPhoneNUmber in phoneNumbers1) {
            if([stringPhoneNUmber isEqualToString:tempPhone2]){
                found = YES;
            }
        }
    }
}


text:
Q: How to obtain rows from the MySQL database by a few filters? I have two tables in the MySQL database, see the database structure bellow:
tbl_product
id
1
2
3

tbl_product_filter
id | product_id | product_filter_value
1    1            1
2    1            2
3    1            3
4    2            1
5    2            2
6    3            1

How can I obtain the products which have only the value of the field product_filter_value 1 and 2?

A: Using Sub-queries:
SELECT *
FROM tbl_product
WHERE id IN (
    SELECT product_id
    FROM tbl_product_filter
    WHERE product_filter_value IN (1, 2)
)

Using Joins (this query might display one product multiple times):
SELECT tbl_product.*
FROM tbl_product
INNER JOIN tbl_product_filter ON tbl_product.id = tbl_product_filter.product_id
WHERE product_filter_value IN (1, 2)

A: SELECT tbl_product.*
FROM tbl_product_filter
INNER JOIN tbl_product USING (product_id)
WHERE product_filter_value IN (1, 2)
GROUP BY tbl_product_filter.product_id


text:
Q: Can you echo/print a $variable name passed into a function? Let's say I have a function that is passed a string:
function foo($var) {
    echo 'Variable Passed: ' . ???
}

I want to print/access the ??? part, so when using the function, I could print the actual string name passed:
foo($myStringName);

Variable Passed: $myStringName

Does PHP have a way of doing the ??? part?

A: You can loop through the $GLOBALS variable and check for matching variable name as the one passed
function printVarName($var) {
    foreach($GLOBALS as $varName => $val) {
        if ($val === $var) {
            echo 'Variable Passed: $'.$varName;
        }
    }

    return false;
}

$vars = 1;
printVarName($vars); //prints Variable Passed: $vars


text:
Q: Do Soft Termination Caps Really Increase Reliability? I'm managing several designs. At one point I identified a few failures that were caused by 0603 caps failing short. After that I switched to all soft-term caps to hopefully eliminate the problem.
Well it's been several years and the problem has not re-occurred that I know of. So I guess it did work, but keeping these soft term caps adds a lot of cost to every board.
So here's what I'm wondering. To those of you who've produced a lot of boards: is this normal? I'm making products that need to last, but they're not safety critical or anything like that where extreme care is required. They're also not used in a high-shock environment (besides being shipped).
If it's really uncommon to have to do this, I'm considering reviewing the designs for board-flex and switching back to regular caps.

A: The more you use component the less you have reliability but some times it is not so. Normal MLCC capacitors are vulnerable against tensions due to assembly process and after that especially during lead free process that is much hotter.
soft termination caps are really more reliable but they are not the first choice for mass production even in safety critical applications.
In mass production the solution is using two serial normal MLCC capacitors those are assembled perpendicular to each other in the PCB. If one of them became short circuit due to tensions in one direction, the other could do part of the job obviously not as good as a single 0603 capacitor but more reliable than that and also more cheap than soft termination capacitors those are also hard to purchase from the market.


text:
Q: Forbidden: You don't have permission to access / on this server I keep having this access denied error. I'm using apache 2.2.15 on CentOs 6.4.
The server is running with user apache and group apache.
In home, I have a user staging. I added him to the apache group.
Permissions on the docs folder are:
drwxrwx--- 2 staging staging 4096 Oct  4 14:33 docs

I'm testing with an index.html file:
-rw-r--r-- 1 staging staging   13 Oct  4 14:28 index.html

SELinux is disabled. The address I'm using is staging.mysite.com
My httpd.conf looks like this:
<Directory "/home/*/docs">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
    Options FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride All

#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

I also have a virtual host set to my staging address:
<VirtualHost SERVERIP:80>
        ServerName staging.mysite.com
        DocumentRoot /home/staging/docs
        ServerAdmin staging@mysite.com
        CustomLog /home/staging/logs/access_log combined
</VirtualHost>

If you need more info let me know but any idea why it's giving me this error?

A: Well, as you stated it, the docs folder is only readable by the staging user and the staging group. So the apache user may not read it.
One solution would be to add the apache user to the staging group.

A: I can fixed the same error:
To Modify at your nagios configuration the options parameter +Indexes and add DirectoryIndex index.php
Maybe show be:
<Directory "/home/*/docs">

#
# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
    Options FollowSymLinks +Indexes

    DirectoryIndex index.php

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride All

#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

And, finally restart your apache service.
Check the permission /home/ can be +x and +r, like chmod +rx /home/.


text:
Q: Reset controlled value of single individual input in form upon button click My app gets initialized with a json payload of 'original values' for attributes in a task form. There is a shared state between various components through a context manager submissionState that also gets imported to this form component. This shared state is a copy of the original values json but includes any edits made to attributes in the payload. I would like to include individual 'reset' buttons for each input of the form which would update the shared state to the original value in the json payload. The original values get passed into the parent form component as props and the edited value state gets called from within the parent component as well.

const FormInput = ({ fieldName, fieldValue, onChange, originalValue }) => {

  const handleReset = e => {
    //????
  }

  return (

        {fieldName}

      <input type="text"
        name={fieldName}
        value={fieldValue}
        onChange={onChange}/>
      <button id="reset" onClick={handleReset}>↻</button>

{originalValue}

  );
};

const TaskForm = (payload: TaskPayload) => {
  const { submissionState, setSubmission } = useTask();

  function handleChange(evt) {
    const value = evt.target.value;
    setSubmission({
      ...submissionState,
      [evt.target.name]: value,
    });
  }

  const taskFields = ["name", "address", "address_extended", "postcode", "locality", "region", "website"];

  return (

      <form>
        {taskFields.map((field) => {
              <FormInput
                key={field}
                fieldName={field}
                fieldValue={submissionState[field]}
                onChange={handleChange}
                originalValue={payload[field]}
              />
          })
        }
      </form>

  );
};
export default TaskForm;

What I would like to do is include logic in the reset button function so that any edits which were made in a form input (from state) get reverted to the original value (stateless), which comes from the payload props: payload[field].
The form input is controlled through a global shared state submissionState, so the reset button logic can either modify the shared state itself with something like:
  const handleReset = (submissionState,setSubmissionState) => {
    setSubmission({
      ...submissionState,
      fieldName: originalValue,
    });

but I would need to pass the submissionState and setSubmission down through to the child component. It would be better if I can somehow update the value attribute in the input, which in-turn should potentially update the shared state? And the logic can just be something like this (assuming I can somehow access the input's value state in the reset button)
  const handleReset = (?) => {
    /*psuedo code:
      setInputValueState(originalValue)
     */
  }

A: I would highly recommend using react-hook-form if it's an option. I've implemented it across several projects and it has never let me down. If it's just not possible to use a library, then keep in mind that React is usually unidirectional. Don't try to work around it, since it works that way by design for most cases you can encounter. Otherwise…
const TaskForm = (payload: TaskPayload) => {
  const { submissionState, setSubmission } = useTask();

  const upsertSubmission = (upsert) =>
    setSubmission({
      ...submissionState,
      ...upsert,
    });

  const handleChange = ({ target }) => {
    upsertSubmission({
      [target.name]: target.value,
    });
  };

  const reset =
    (originalValue) =>
    ({ target }) => {
      upsertSubmission({
        [target.name]: originalValue,
      });
    };
  /* Also something like this. RHF will handle most of this for you!
   * const reset = (originalValue, fieldName) =>
   *   upsertSubmission({[fieldName]: originalValue})
   */

  const taskFields = [];

  return (

      <form>
        {taskFields.map((field) => (
          <FormInput
            key={field}
            fieldName={field}
            onChange={handleChange}
            reset={reset(originalValue)}
            value={submissionState[field]}
          />
        ))}
      </form>

  );
};


text:
Q: STL list - how to find a list element by its object fields I have a list:
list<Unit *> UnitCollection;

containing Unit objects, which has an accessor like:
bool Unit::isUnit(string uCode)
{
    if(this->unitCode == uCode)
        return true;
    else
        return false;
}

How do I search my UnitCollection list by uCode and return the corresponding element (preferably and iterator).
In pseudo code it would look something like this:
for every item in my UnitCollection:
  if the unit.isUnit(someUnitIpass)
    do something
  else
    next unit

I have looked at the find() method, but i'm not sure you can pass a boolean method in instead of a searched item parameter if that makes sense.

A: An Insignificant Comment First
You might change your accessor function to the simpler form
return unitCode == uCode;

Now To What We're Here For
You're better off looking for the position of the element rather than its index. Getting an element from its index is an O(n) operation, whereas getting an element from its position is an O(1) operation. So, with the STL and a little help from boost::bind():
#include <algorithm>
#include <boost/bind.hpp>

// ...
std::string uCode("uCode to search for");
std::list<Unit*>::iterator pos = std::find_if(unitCollection.begin(),
                                              unitCollection.end(),
                                              boost::bind(&Unit::isUnit,
                                                          _1, uCode));

The STL does have std::mem_fun(), which, along with std::bind2nd() would give the same result. The problem is that mem_fun() only works with member functions that take no arguments. boost::bind() on the other hand is much more powerful, and does solve the problem here very nicely. You should expect it in the next standard, which should be here immediately after the Messiah arrives.
But If You Don't Have Boost
If don't already have boost in your project then you really, really should install it. If the standard library is C++'s wife, then Boost is C++'s young lover. They should both be there, they get along fine.
Having said that, you can extract the function into a standalone function object as Peter mentioned already:
struct has_uCode {
    has_uCode(cont std::string& uc) : uc(uc) { }
    bool operator()(Unit* u) const { return u->isUnit(uc); }
private:
    std::string uc;
};

Then, you can call std::find_if() like so:
std::list<Unit*>::iterator pos = std::find_if(unitCollection.begin(),
                                              unitCollection.end(),
                                              has_uCode("this and that"));

And a Little Bit of Performance Consideration
One more thing: I don't know how uCode's look like, but if they're big then you might speed things up by maintaing hashes of these strings so that in your search predicate you only compare the hashes. The hashes might be regular integers: comparing integers is pretty fast.
One more one-more-thing: If you run this search procedure often you might also consider changing your container type, because this really is an expensive procedure: in the order of the list's length.

A: You could have a look at find_if as jpalecek suggests, and then use distance to find the distance between the iterator returned from find_if and UnitCollection.begin(), and that distance should be the index of the element in the list.
And as for the predicate, you could write a function object like this:
struct predicate
{
    predicate( const std::string &uCode ) : uCode_(uCode) {}

    bool operator() ( Unit *u )
    {
        return u->isUnit( uCode_ )
    }
private:
    std::string uCode_;
};

And then use it like this:
predicate pred("uCode");
std::list<Unit*>::iterator i;
i = std::find_if( UnitCollection.begin(), UnitCollection.end(), pred );

Or at least I think that would be a way to do it.

A: Your predicate might look something like:
struct unit_predicate {
    unit_predicate(const string& s): str(s) {}
    bool operator()(const Unit* unit) const {
        return unit->isUnit(str);
    }
    const string& str;
};

UnitCollection::const_iterator unit = std::find_if(units.begin(), units.end(), unit_predicate("Some Unit"));

A couple of other comments:
Your isUnit function would be better to take the string by (const) reference to avoid unnecessary copies.
You say you'd like to return the index of an item; that isn't normally sensible for linked lists, because you can't get items back by index. If you want to deal with them by index, maybe std::vector would be more useful to you.

A: Have a look at find_if.
If you can use boost, you can use it with boost::lambda.
namespace bl=boost::lambda;
std::find_if(...begin... , ...end... , bl::bind(&Unit::isUnit, *bl::_1, "code"))

or you can brew your own functor.
struct isUnitor // : public std::unary_function<Unit*, bool> -- this is only needed for the negation below
{
  string arg;
  isUnitor(const string& s) : arg(s) {}
  bool operator()(Unit* u) const { return u->isUnit(arg); }
};

std::find_if(...begin... , ...end... , isUnitor("code"))

or, if you want the index (for the negation, look here):
std::count_if(...begin... , ...end... , not1(isUnitor("code")))


text:
Q: How can I use DOMStringMap in TypeScript? Let's say I have a function:
angular.forEach(myElements, function prepareElements(myEl: HTMLElement, index) {
    myEl.dataset.myProperty = "whatever";
})

The problem I get is
error TS2094: The property 'myProperty' does not exist on value of type 'DOMStringMap'
I don't really understand the interface in lib.d.ts
interface DOMStringMap {
}
declare var DOMStringMap: {
    prototype: DOMStringMap;
    new (): DOMStringMap;
}

then later on...
interface HTMLElement {
    dataset: DOMStringMap;
    hidden: boolean;
    msGetInputContext(): MSInputMethodContext;
}

Is it just me or is this a little unclear?
I tried casting it <DOMStringMap>myEl.dataset.myProperty = "whatever", which did nothing...

A: The DOMStringMap interface is empty because the spec is not finalized : https://developer.mozilla.org/en/docs/Web/API/DOMStringMap
In the meantime you can simply use: myEl.dataset['myProperty'] = "whatever";

A: you can also cast it to user defined type
type IType = {myProperty: string}
....
(myEl.dataset) as IType.myProperty = "whatever";


text:
Q: Trying to copy SQLite database in Android and getting "No such file or directory" I have a database and I want to copy it to SD Card to keep a backup and I found this code:
private void exportDB(){
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.example.myapp" +"/databases/"+"mydatabase";
    String backupDBPath = "/storage/extSdCard/mydatabase";
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
    } catch(IOException e) {
        //e.printStackTrace();
        Toast.makeText(this, "Err:"+e, Toast.LENGTH_LONG).show();
    }
}

As I wrote in the title I get the No such file or directory ENOENT error when I try to do it.
Apparently the database should be stored right there.
I've tried changing the path to a few different things but still nothing...
I tried:
"/data/"+ "com.example.myapp" +"/"+"mydatabase.db"

and
"//data//"+ "com.example.myapp" +"//databases//"+"mydatabase"

Edit1: Also tried this and also doesn't work:
String currentDBPath = this.getDatabasePath("mydatabase").toString();

etc. nothing works and I also can't find a way to check the path in any way.
I basically have the database made, inserted a few rows into it and have some basic functions like add() and delete() etc. Am I missing something? I have no idea what else I can try.
Here's what logcat has to say about this:

01-18 11:34:46.215 10337-10337/com.example.myapp D/DBPATH: Database path is /data/data/com.example.myapp/databases/mydatabase.db
01-18 11:34:46.225 10337-10337/com.example.myapp W/System.err: java.io.FileNotFoundException: /data/data/com.example.myapp/databases/mydatabase.db: open failed: ENOENT (No such file or directory)
01-18 11:34:46.235 10337-10337/com.example.myapp W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:456)
01-18 11:34:46.235 10337-10337/com.example.myapp W/System.err:     at java.io.FileInputStream.(FileInputStream.java:76)
01-18 11:34:46.235 10337-10337/com.example.myapp W/System.err:     at com.example.myapp.TabsActivity.exportDB(TabsActivity.java:183)
01-18 11:34:46.235 10337-10337/com.example.myapp W/System.err:     at com.example.myapp.TabsActivity.onOptionsItemSelected(TabsActivity.java:119)

A: As below the issue may not be with the database, rather it could be with the external storage and because the directories do not exist. The fix is to create the directories. Hopefully the following will work (did for me):-
    try {
        source = new FileInputStream(currentDB).getChannel();
        (new File(backupDB.getParent())).mkdirs(); //<<<<<<<<<<<<<< ADDED
        destination = new FileOutputStream(backupDB).getChannel();
        //destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
    } catch(IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Err:"+e, Toast.LENGTH_LONG).show();
    }

*

*For testing I've commented out the transfer. P.S. ran OK with transfer.

*There could also be issues due to permissions (my testing was on a genymotion emulator).

*Just tested on a real device, the same error will occur if permission aren't granted.

*Just tested on real device setting permissions in Manifest and also in code for versions > 23. Copy then worked. :-

This may be of use Storage permission error in Marshmallow

Taking your code and adapting it as per (which checks the paths, see output) :-

java.io.FileNotFoundException:
  /mnt/sdcard/storage/extSdCard/mydatabase: open failed: ENOENT (No such
  file or directory)

private void exportDB(){
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ getPackageName() +"/databases/"+DatabaseHandler.DATABASE_NAME;
    String retreivedDBPAth = getDatabasePath(DatabaseHandler.DATABASE_NAME).getPath();
    String backupDBPath = "/storage/extSdCard/mydatabase";
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    File retrievedDB = new File(retreivedDBPAth);
    Log.d("PATHS", " CurrentDB=" +
            currentDBPath + "\n\t" + currentDB.getPath() +
            "\n\tExists=" + String.valueOf(currentDB.exists()) +
            "\nBackup=" + backupDBPath + "\n\t" + backupDB.getPath() +
            "\n\tExists=" + String.valueOf(backupDB.exists()) +
            "\nRetrieved DB=" + retreivedDBPAth + "\n\t" + retrievedDB.getPath() +
            "\n\tExists=" + String.valueOf(retrievedDB.exists())
    );
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        //destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
    } catch(IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Err:"+e, Toast.LENGTH_LONG).show();
    }
}

The ENOENT is not for the database but for the External storage as per :-
01-18 11:11:32.017 2689-2689/? D/PATHS:  CurrentDB=/data/example.com.so48304909_spinner/databases/spinnerExample
                                            /data/data/example.com.so48304909_spinner/databases/spinnerExample
                                            Exists=true
                                        Backup=/storage/extSdCard/mydatabase
                                            /mnt/sdcard/storage/extSdCard/mydatabase
                                            Exists=false
                                        Retrieved DB=/data/data/example.com.so48304909_spinner/databases/spinnerExample
                                            /data/data/example.com.so48304909_spinner/databases/spinnerExample
                                            Exists=true
01-18 11:11:32.021 2689-2689/? W/System.err: java.io.FileNotFoundException: /mnt/sdcard/storage/extSdCard/mydatabase: open failed: ENOENT (No such file or directory)
01-18 11:11:32.021 2689-2689/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:416)
01-18 11:11:32.021 2689-2689/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
01-18 11:11:32.021 2689-2689/? W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
01-18 11:11:32.021 2689-2689/? W/System.err:     at example.com.so48304909_spinner.MainActivity.exportDB(MainActivity.java:162)
01-18 11:11:32.021 2689-2689/? W/System.err:     at example.com.so48304909_spinner.MainActivity.onCreate(MainActivity.java:38)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.Activity.performCreate(Activity.java:5008)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.os.Looper.loop(Looper.java:137)
01-18 11:11:32.021 2689-2689/? W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:4745)
01-18 11:11:32.021 2689-2689/? W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
01-18 11:11:32.021 2689-2689/? W/System.err:     at java.lang.reflect.Method.invoke(Method.java:511)
01-18 11:11:32.021 2689-2689/? W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-18 11:11:32.021 2689-2689/? W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-18 11:11:32.021 2689-2689/? W/System.err:     at dalvik.system.NativeStart.main(Native Method)
01-18 11:11:32.021 2689-2689/? W/System.err: Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-18 11:11:32.021 2689-2689/? W/System.err:     at libcore.io.Posix.open(Native Method)
01-18 11:11:32.021 2689-2689/? W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-18 11:11:32.021 2689-2689/? W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:400)
01-18 11:11:32.021 2689-2689/? W/System.err:    ... 18 more


text:
Q: Using R package data in function without loading it Does anyone know of a way (creative hack or otherwise) that data from an R package can be utilized inside a function without actually loading it to the environment?
As a simple example:
 plot.sepals <- function() {
     data(iris);
     plot(Sepal.Length ~ Petal.Length, data=iris);
 }

You'll notice when you run the example that the iris dataset gets loaded. This is precisely what I wish to avoid. I'd like to use the data but not have it loaded to an environment.
Thanks for any help or ideas.

A: I'm still not allowed to comment yet, but I think that @user3293236 answered your question as I understand it.
You mean like this?
plot.sepals <- function() {
               plot(Sepal.Length ~ Petal.Length, data=datasets::iris) }


text:
Q: Does the process automatically clean up the resources taken by pthreads upon exit Assume that I have a code something like this :
void *my_thread(void *data)
{
    while (1) { }
}

void foo_init(struct my_resource *res)
{
    pthread_create(&res->tid, NULL, my_thread, res);

    /* Some init code */
}

void foo_exit(void)
{
    /* Some exit code */
}

The scenario is something like this. When the process gets initialized, the function foo_init() is called with a pointer to my allocated resources(the allocation is done automatically by some other function, which isn't under my control). Within the function I am creating a pthread, which runs in infinite loop.
After a while when the process is about to terminate, the function foo_exit() is called, but this time without the pointer to my resources, and hence I am unable to call pthread_join(), as my tid is contained within my_resource structure.
Now my question is that, whether the resources pertaining to the pthreads are destroyed upon the termination of the process by the OS or not? If yes, how can I make that sure.
Also is it safe to terminate the process without calling pthread_join()?
Thanks in advance.

A: If you're talking about allocated memory, yes. When a process exits all virtual memory pages allocated to that process are returned to the system, which will clean up all memory allocated within your process.
Generally the OS is supposed to clean up all resources associated with a process on exit. It will handle closing file handles (which can include sockets and RPC mechanisms), wiping away the stack, and cleaning up kernel resources for the task.
Short answer, if the OS doesn't clean up after a process it is a bug in the OS. But none of us write buggy software right?

A: All "regular" resources needed by a process are released automatically by the OS when the process terminates (e.g. memory, sockets, file handles). The most important exception is shared memory but also other resources can be problematic if they're managed not by OS but by other processes.
For example if your process talks to a daemon or to another process like a window manager and allocates resources, whether or not those are released in case the process terminates without releasing them depends on the implementation.

A: I think the question can be answered another way: pthreads do not own any resources, resources are owned by the process.  (A pthread may be the "custodian" of resources, such as memory it has malloc'ed, but it is not the owner.)  When the process terminates, any still running pthreads suddenly stop and then the usual process clean-up happens.
POSIX says (for _Exit()):

• Threads terminated by a call to _Exit() or _exit() shall not invoke their cancellation cleanup handlers or per-thread data destructors.

For exit() POSIX specifies a little more clean-up -- in particular running all atexit() things and flushing streams and such -- before proceeding as if by _Exit().  Note that this does not invoke any pthread cancellation cleanup for any pthread -- the system cannot tell what state any pthread is in, and cannot be sure of being able to pthread_cancel() all pthreads, so does the only thing it can do, which is to stop them all dead.
I can recommend the Single UNIX® Specification (POSIX) -- like any standard, it's not an easy read, but worth getting to know.


text:
Q: Visual Studio in OSX: Installing Android SDK Platform-Tools v26.0.0 failed I'm trying to compile to Android using Unity3D. The normal procedure is installing Android Studio. However I want to use Visual Studio Community (Preferences -> SDK Locations -> Android) to avoid downloading Android Studio because I do not plan to use it:

The rest of components seems to be installed well. However the Android SDK Platform-Tools installation outputs the following error:

Installing Android SDK Platform-Tools v26.0.0 failed
Could not find a
part of the path
"/Users/username/Library/Developer/Xamarin/android-sdk-macosx/platform-tools/package.xml".

I have been able to install it after creating an empty folder named platform-tools manually. Unfortunately it seems it has not been installed correctly because the folder only contains one file named: package.xml of much less than 7 Mb. Unity also output the following error:

Android SDK is outdated
SDK Tools version 0.0.0 < 24.0.0.

Workarounds seem easy (both can be downloaded from here: https://developer.android.com/studio/index.html):

*

*Install Android Studio: it seems the easier and quick way, but >500Mb HardDisk space

*Install only command line tools: not so easy and quick

However I guess I'm very stubborn and curious: why could it be failing?

A: Hey mate for me it worked to create the missing folder manually.
So this folder:
/Users/username/Library/Developer/Xamarin/android-sdk-macosx/platform-tools/

Is actually missing so if you do this:
$ cd /Users/username/Library/Developer/Xamarin/android-sdk-macosx/
$ mkdir platform-tools

And try to run the installer from VS UI
it should install the platform-tools package.

Complement from @benjamingranados:
Also check that the destiny folder in the "Locations" Tab is the same.


text:
Q: extract a field from a json file through a network request in react native hi everyone I have recently started using react native and I have a problem. when I make the network call helpme.php it asks me for the json:
{"person":[{
"girl":{"name":"Alice","id":1},
"boy":{"name":"Json","id":2}},
{"girl":{"name":"Sophia","id":3},
"boy":{"name":"Mark","id":4}}]}

I want to extract the fild name of all names from the json help:me.php file.My code is:
async getDid () {
  let httpResponse = await fetch("https://ewserver.di.unimi.it/mobicomp/treest/getLines.php", {
    method: 'POST',
    headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({sid:"Zcoc8cPbnTeXrVJB"})
    });
    const status = httpResponse.status;
    if (status == 200) {
    let deserializedObject = await httpResponse.json();
    console.log(deserializedObject.lines.sname);
    return deserializedObject;

    } else {
    let error = new Error("Error message from the server. HTTP status: " + status);
    throw error;
    };
}

My rusult is: undefined. Why?How can I extract the name field of the file json help_me.php(so i want print Alice,Json,Sophia,Mark) ? What if I want to extract the name field: "Mark"?

A: For you to print  Alice,Json,Sophia,Mark, you need to do
let deserializedObject = await httpResponse.json();

const personArray = deserializedObject?.person ?? [];

const nameArray = []
personArray.map((data) => {
nameArray.push(data?.girl?.name)
nameArray.push(data?.boy?.name)
})

console.log(nameArray,"array of anmes")

try this


text:
Q: Spring Boot Application Failed to start I am currently new to spring boot and I am having trouble in resolving the error ,
I would be glad if anyone could help me out
This is the Error I am getting
This the Complete Exception
My Dialect is InnoDb
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.6.RELEASE.jar:1.5.6.RELEASE]
    at com.mediaocean.hotelproject.Application.main(Application.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.10.RELEASE.jar:4.3.10.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table review add constraint FKi0ly7ivbh8ijdgoi7cwtuoavt foreign key (hotel_id) references hotel (hotel_id)]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:59) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlString(SchemaMigratorImpl.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applySqlStrings(SchemaMigratorImpl.java:420) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:386) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
Caused by: java.sql.SQLException: Can't create table 'hotelproject.#sql-95c_2d' (errno: 150)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2490) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1552) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2607) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1480) ~[mysql-connector-java-5.1.43.jar:5.1.43]
    at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:228) ~[commons-dbcp-1.4.jar:1.4]
    at org.apache.commons.dbcp.DelegatingStatement.executeUpdate(DelegatingStatement.java:228) ~[commons-dbcp-1.4.jar:1.4]
    at org.hibernate.tool.schema.internal.TargetDatabaseImpl.accept(TargetDatabaseImpl.java:56) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 32 common frames omitted

My application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/hotelproject
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

Hotel Model Code
It has a OneToMany Mapping To Review Model And ManyToOne Mapping To City Model
package com.mediaocean.hotelproject.model;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Hotel {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)

    private int hotelId;
    private String name;
    private String address;
    private String zip;

//  private int city_id;

    @ManyToOne
    @JoinColumn (name="city_id",referencedColumnName="id",nullable=false,insertable=false,updatable=false)
    private City city;

    @OneToMany(mappedBy = "hotel", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    List<Review> review;

    public Hotel() {
        super();
    }

//  public Hotel(int hotelId, String hotelName, String hotelAddress, String hotelZip) {
//      this.hotelId = hotelId;
//      this.name = hotelName;
//      this.address = hotelAddress;
//      this.zip = hotelZip;
//  }
//
    public int getHotelId() {
        return hotelId;
    }

//  public int getCityId() {
//      return city_id;
//  }

    public String getHotelName() {
        return name;
    }

    public String getHotelAddress() {
        return address;
    }

    public String getHotelZip() {
        return zip;
    }

}

A: it seems hibernate is trying to alter table which is violating some constraint, simply drop all your tables or at least the table with the problem and change ddl to create this will solve the issue but you will lose your data.
If you do not want to lose your data you can either specify a new table using @Table annotation but again the old table will be ignored and data will be lost or you can alter your table manually.


text:
Q: How to apply click method on google maps Markers?? (React - Google Maps) I am using react and google maps to create a map with full functionality, markers, infoWindow. now i added the functionality that pop up an infowindow when click a marker by adding the listener to all markers in a loop
this.state.markers.forEach(marker => {
    marker.addListener('click', e => {this.openInfoWindow()})
});

but i have a sidebar that contains the names of locations of these markers, what is required is when clicking a list item in the sidebar, an info window pops up from the corresponding marker, i tried this but did not work
this.state.markers.forEach(marker => marker.click());

but this did not work and i have an error

marker.click() is not a function

I am not using any libraries like google-map-react.
So why it works only when the click even done by mouse but not click() method and is there a way to make it work????


text:
Q: Regular expression to replace second occurrence of dot String is Hello.world.hello. I wanted to replace the second occurrence of the dot with '_'.
str = "Hello. world. Hello!"
x = re.sub(r'^((.){1}).', r'\1_', str)
#x = str.find(str.find('.')
print(x)

The output I am getting is 'H_llo. world. Hello!'. What should be the correct solution

A: You can use
import re
text = "Hello. world. Hello!"
print( re.sub(r'^([^.]*\.[^.]*)\.', r'\1_', text) )
# => Hello. world_ Hello!

See the Python demo and the regex demo.
Details:

*

*^ - start of string

*([^.]*\.[^.]*) - Group 1: any zero or more chars other than a ., a dot and again any 0+ non-dots

*\. - a dot.

The replacement is Group 1 value + _.
It is also possible to do without a regex:
text = "Hello. world. Hello!"
chunks = text.split('.', 2) # split the text twice
if len(chunks) > 2:         # if there are more than 2 items
    print( fr'{".".join(chunks[0:2])}_{chunks[2]}' )
else:
    print(text)             # Replace the second dot or print the original
# => Hello. world_ Hello!

See the Python demo.

A: With your shown samples, could you please try following. Written and tested in Python3.8
import re
str1 = "Hello. world. Hello!"
re.sub(r'^(.*?\.)([^.]*)\.(.*)$', r'\1\2_\3', str1)
'Hello. world_ Hello!'

Explanation: Simply importing re function of Python3.8 then creating str1 variable with value. Then using re.sub function to replace 2nd dot with _ as per requirement. In re.sub function on first argument giving regex to match everything apart from 2nd dot(in 3 capturing groups) and replacing them as per need with respective capturing groups placing _ on place of 2nd dot.
Explanation of regex:
^(.*?\.)  ##Creating 1st capturing group, where Matching till 1st dot from staring of value.
([^.]*)   ##Creating 2nd capturing group, matching just before dot(2nd dot) here.
\.        ##Matching exact literal dot here.
(.*)$     ##Matching/keeping everything else till last of value in 3rd capturing group.


text:
Q: how do I enable mongodb cli pretty print? - db.col.find().pretty() not working Using mongo v2.4.5 shell, db.col.find().pretty() does not pretty print for me on either osx console or linux ubuntu 12.04 bash.
There is no diff in the output with and without pretty()
> db.people.find()
{ "_id" : ObjectId("520d293752cfe6ece5d3fd77"), "name" : "Andrew" }
{ "_id" : ObjectId("520e448b77803f8f15fcfedb"), "name" : "Amy" }
>
> db.people.find().pretty()
{ "_id" : ObjectId("520d293752cfe6ece5d3fd77"), "name" : "Andrew" }
{ "_id" : ObjectId("520e448b77803f8f15fcfedb"), "name" : "Amy" }
>

What am I missing?  (something crazy basic no doubt)
Thx

UPDATE:  doh! answered below.  I had not realized such a simple doc would not be prettified.  Nested docs pretty fine for me.

A: You can add these lines to your file in $HOME/.mongorc.js in order to enable pretty print.
DBQuery.prototype._prettyShell = true

Alternatively, you can use this command that prints docs in array format:
db.collection.find().toArray()

cheers!

A: .pretty will only really change things when you have nested or larger documents:
> db.so.insert( { name: "Derick" } );
> db.so.insert( { f: 'Derick', s: 'Rethans', t: 'derickr' } );
> db.so.insert( { name: { f: 'Derick', s: 'Rethans' } } );

> db.so.find();
{ "_id" : ObjectId("520e49a21d7b77441eaf6446"), "name" : "Derick" }
{ "_id" : ObjectId("520e49b11d7b77441eaf6447"), "name" : { "f" : "Derick", "s" : "Rethans" } }

> db.so.find().pretty();
{ "_id" : ObjectId("520e49a21d7b77441eaf6446"), "name" : "Derick" }
{
    "_id" : ObjectId("520e4f895a4563e39f06b030"),
    "f" : "Derick",
    "s" : "Rethans",
    "t" : "derickr"
}
{
    "_id" : ObjectId("520e49b11d7b77441eaf6447"),
    "name" : {
        "f" : "Derick",
        "s" : "Rethans"
    }
}

So I presume it works just fine for you!


text:
Q: Prevent Default with formToWizard.js I have a form wizard and need to block the user from moving from step 1 to step 2. It's easy enough to do this with validation, but this isn't a requirement, just a warning if a certain combination of boxes is checked. I have it working to a point, unfortunately it doesn't stop the user from moving from step 1 to step 2 and displays the alert on step 2. Ideally it would display the alert/confirm dialogue on step one and only allow the user to go to step 2 if they select ok, selecting cancel would close box and remain on that page. Can anyone help out here? Much appreciated. And now, the code:
$("#step0Next").live('click', function(event) {
if($("#RT").is(":checked") && !$(".ex").is(':checked')) {

alert("You have not selected any exchanges for which to receive real time market data from. If
you continue, you will only receive real time data for market metrics and ten minute delayed
data for everything else. Do you wish to continue?");
$(this).die('click');
}
});

so if a user checks "#RT" and no boxes with a class of .ex are checked, it goes to step 2 and displays the alert. I will replace alert with custom jConfirm box.
Thanks,

A: Sounds like you need a confirm box - see here: http://www.w3schools.com/js/js_popup.asp

A: @Nick Craver - thanks man.
<script type="text/javascript">
    $("#step0Next").live('click', function(event) {
        $('#step1Prev').click();  //go back to step 1
        if($('#RT').is(':checked') && !$('.ex').is(':checked')) {
            if(!confirm("You have not selected any exchanges for which to receive real time market data from. If you continue, you will only receive real time data for market metrics and ten minute delayed data for everything else. Do you wish to continue?")) return;
            $('#step0Next').die('click');
        }
    $(this).triggerHandler('click');
    });
</script>


text:
Q: Add new attribute dynamically to the existing model object in Yii2 framework In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?
Example
//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);

If it is not possible, please suggest an alternate best method to implement it.
Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:
'formats' => [
               'application/json' => Response::FORMAT_JSON,
             ],

A: You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:
class Result extends \yii\db\ActiveRecord implements Arrayable
{
    public $dynamic;

    // Implementation of Arrayable fields() method, for JSON
    public function fields()
    {
        return [
            'id' => 'id',
            'created_at' => 'created_at',
            // other attributes...
            'dynamic' => 'dynamic',
        ];
    }
    ...

..in your action pass some dynamic values to your model, and return everything as JSON:
public function actionJson()
{
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    $model = Result::findOne(1);
    $model->dynamic = [
        'field1' => 'value1',
        'field2' => 2,
        'field3' => 3.33,
    ];

    return $model;
}

In result you will get JSON like this:
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}


text:
Q: I cannot resolve the path from Storyboard.TargetProperty in my WPF app In my WPF application I have an animation of a certain element. The element to be animated looks like this.
    <Path x:Name="theX" StrokeThickness="7" StrokeStartLineCap="Round" StrokeEndLineCap="Round">
        <Path.Data>
            <GeometryGroup>
                <LineGeometry StartPoint="4, 4" EndPoint="60, 60"/>
                <LineGeometry StartPoint="4, 60" EndPoint="60, 4"/>
            </GeometryGroup>
        </Path.Data>
    </Path>

The color of the LineGeometry elements should be animated, but I don't know how the Storyboard.TargetProperty path is resolved. In this case the GeometryGroup element causes problems. How is the GeometryGroup element accommodated in the path of the Storyboard.TargetProperty, see the three "???".
I've already tried the following:
...).GeometryGroup.(... ...).(GeometryGroup.Children).(... ...).GeometryCollection.(... ... also i've tried that (Path.Stroke).(SolidColorBrush.Color)
    <ColorAnimationUsingKeyFrames BeginTime="0:0:1" Duration="0:0:1"
                                                              Storyboard.TargetName="theX"
                                                              Storyboard.TargetProperty="(Path.Stroke).???.(SolidColorBrush.Color)"
                                                              FillBehavior="Stop">
                <DiscreteColorKeyFrame Value="#333333" KeyTime="0:0:0"/>
                <LinearColorKeyFrame Value="#6AFF00" KeyTime="0:0:0.2"/>
                <DiscreteColorKeyFrame Value="#6AFF00" KeyTime="0:0:0.5"/>
                <LinearColorKeyFrame Value="#333333" KeyTime="0:0:0.9"/>
     </ColorAnimationUsingKeyFrames>

The Geometry-elements are part of a DataTemplat of an ItemsControl with data binding. And I get an exception on the .NET property linked via data binding.

The translation of the exception:
System.InvalidOperationException: "Not all property references in property path" (0) .GeometryGroup. (1) "can be resolved. Make sure that suitable objects support the properties."
In the application there is a similar element, an EllipseGeometry, in which the animation works in this way. The difference is the GeometryGroup element.
<Path x:Name="theO" StrokeThickness="6" Stroke="Transparent">
    <Path.Data>
        <EllipseGeometry Center="25, 25" RadiusX="22" RadiusY="22"/>
    </Path.Data>
</Path>

<ColorAnimationUsingKeyFrames BeginTime="0:0:1" Duration="0:0:1"
                                                              Storyboard.TargetName="theO"
                                                              Storyboard.TargetProperty="(Path.Stroke).(SolidColorBrush.Color)"
                                                              FillBehavior="Stop">
                <DiscreteColorKeyFrame Value="#333333" KeyTime="0:0:0"/>
                <LinearColorKeyFrame Value="#FF4F00" KeyTime="0:0:0.2"/>
                <DiscreteColorKeyFrame Value="#FF4F00" KeyTime="0:0:0.5"/>
                <LinearColorKeyFrame Value="#333333" KeyTime="0:0:0.9"/>
</ColorAnimationUsingKeyFrames>

Many thanks for the help.

A: Notice in the working example you have a transparent brush set to the Stroke property.
But in the first example, nothing is set to this property.
Hence it is null.
And null has no properties to animate them.
You can explicitly set  SolidColorBrush instance in this property, give this instance a name, and access its Color property directly.
It will be much easier than all these casts.
Example:
        <Path x:Name="theX" StrokeThickness="7" StrokeStartLineCap="Round" StrokeEndLineCap="Round">
            <Path.Stroke>
                <SolidColorBrush x:Name="PathStroke" Color="Transparent"/>
            </Path.Stroke>
            <Path.Data>
                <GeometryGroup>
                    <LineGeometry StartPoint="4, 4" EndPoint="60, 60"/>
                    <LineGeometry StartPoint="4, 60" EndPoint="60, 4"/>
                </GeometryGroup>
            </Path.Data>
        </Path>

        <ColorAnimationUsingKeyFrames BeginTime="0:0:1"
                                      Duration="0:0:1"
                                      Storyboard.TargetName="PathStroke"
                                      Storyboard.TargetProperty="Color"
                                      FillBehavior="Stop">
            <DiscreteColorKeyFrame Value="#333333" KeyTime="0:0:0"/>
            <LinearColorKeyFrame Value="#6AFF00" KeyTime="0:0:0.2"/>
            <DiscreteColorKeyFrame Value="#6AFF00" KeyTime="0:0:0.5"/>
            <LinearColorKeyFrame Value="#333333" KeyTime="0:0:0.9"/>
        </ColorAnimationUsingKeyFrames>


text:
Q: AngularJS Animations ng-switch ng-repeat I am trying to do what looks like a simple process: to display a list of items received from an HTTP request with animation.
First of all, here is my way of doing it ( I am open to any suggestions to do it in a better angular way ):

*

*I define a scope variable state that I initialize to loading in my controller and that I change to loaded when I receive data from the HTTP request.

*I initialize a scope variable items with the received data.

*In my view, I use ng-switch for the states, and ng-repeat with the items.

*I define an animation with css on ng-repeat.

Here is a plunkr ( with a $timeout instead of the request ).
I cannot understand why the animation does not work.
Any help will be appreciated. Thanks.

A: The reason it is happening is because your ng-when. The same thing happens with ng-if, but would work fine if you used ng-show.
The problem is that when your ng-when condition returns true, the ng-when first renders it's content in a detatched dom (so animations do not happen). This dom is then attached to the dom tree (this step is animated but you would have to put your animation class on the ng-when).
When using something like ng-show or ng-hide things work as expected because the dom is always attached (it is simply shown/hidden).
This might be considered either a bug or a limitation of ng-animate, you might want to post a github issue and see if the angular guys have any thoughts.

A: It seems to be a "feature" of angular that it won't add .ng-enter to repeat items inside ng-switch-when block. You can remove ng-switch-when="loaded" and it will work (You don't really need it as ng-repeat won't do anything if there is no items)

Please wait...

{{item}}

http://plnkr.co/edit/ocEj7BSQPSeIdnnfAOIE?p=preview


text:
Q: Node.js: HTML as string parser I'm trying to find a NodeJS library/package that can parse HTML with complex queries.
For example, for input:
var html-parser = require('magical-parser');
var htmlStr = '

';

var parsedHtml = html-parser.parse(htmlStr);

console.log(parsedHtml.findById('spanny'));
// prints

console.log(parsedHtml.findByclass('spanny'));
// prints

A: You can use cheerio (implementation of core jQuery designed specifically for the server)
var cheerio = require('cheerio');
var htmlStr = '

';
var $ = cheerio.load(htmlStr);

console.log($('#spanny')); // get element by id
console.log($('.spanny')); // get element by class

A: You can use Cheeriojs to use jQuery in a parsed dom.  Here's some sample code.
var cheerio = require('cheerio'),
    $ = cheerio.load('

');

console.log($('#spanny').text());


text:
Q: How to use \num for all numbers in text? (siunitx) I want to use \num (from the package siunitx) for all the numbers in my document, tables included. (I have a lot and it would take a lot of time to do it manually.)
Is there a way to do that?
Thanks!

A: Applying a macro to all numbers in a document globally is so far I know not possible.
What you can do is using an advanced feature of many text editors called regular expressions to search and replace all numbers in your document files to add the \num this way.
Just get an text editor which has this feature, like the free Notpad++, and try the following text as regular expression:
([+-]? *\d+(?:\.\d*)?)

and as replacement text:
\\num{\1}

This regular expression searches for all numbers with or without + or -, maybe followed by spaces, and with or without a fractional part. It then adds the found number into \num{..}.

Make sure that you make a backup of your files first!


text:
Q: iPhone - picking a video... URL with two bars? I have a UIPickerController to select videos in my App and it is crashing when selecting videos using the picker. When I feed the MPMoviePlayerController with the URL directly it works fine, but when the URL comes from the UIPickerController, it loads the movie correctly but crashes when the thumbnails are being created.
I have dumped the URL to the console, just after the file is selected and this is what I see
file://localhost/private/var/mobile/Applications/FA667F85-B009-46FA-A0B9-A7345A072651/tmp//trim.Ir0gqx.MOV

first question: why is the double bar before the file name?
second question: why the file name comes with a trim prefix if I have editing NO on the picker?
this is the picker code:
- (void) selectMovie:(id) sender {

    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypePhotoLibrary]) {

        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        NSArray *mediaTypesAllowed = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];

        picker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie, nil];
        picker.delegate = self;
        picker.allowsEditing = NO;
        picker.videoQuality = UIImagePickerControllerQualityTypeHigh; // I've added this trying to make it stop compressing the video, but it won't... any clues?

        UIPopoverController *aPopover =
            [[UIPopoverController alloc] initWithContentViewController:picker];

        aPopover.delegate = self;

        CGRect myRect = [sender frame];

        [aPopover presentPopoverFromRect:myRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];

    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ( [ mediaType isEqualToString:@"public.movie" ]){
            movieURL =  [info objectForKey:UIImagePickerControllerMediaURL];
    }

    NSLog(@"%@", movieURL);

    [self loadMovie:movieURL];

}

A: My thought is that your app does not have permission to generate thumbnails in the location where the movie is stored.  Try copying the movie file out of the photo albums and into your documents directory:
NSFileManager *fm = [NSFileManager defaultManager];
[fm moveItemAtURL:fromURL toURL:toURL error:&error];

Assuming you have a toURL pointing to a filename in your docs directory.

A: I only know about the first one, because you need to feed to MPMoviePlayerController a url, a url has to start with a scheme, http://, smtp://, kind of that. file:// is also a scheme for file url