text:
Q: How to Ignore HTML Tags when Using document.write I have this line of Javascript code that is supposed to show the line
document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");

This is done by using document.write. So it is basically
document.write("document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");");

Firstly, I pass the above string to an array, and then later on in the program display it using document.write.
The problem is that when display it, it actually makes a text box and shows it. I believe this is happening because HTML just goes through and checks for tags, regardless of their position in quotes, etc.
How do I fix this? I just want to display the actual line, not the output from the line. Is there anyway to do this? Can I use something different than document.write? Can I output it to a text box that simply display it? Is that enough?

A: You need to escape the tags. These symbols: < > must be encoded as < >.
Your example should be similar to this:
document.write(" `<textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">");

A: Replace < by < and > by >
Try this :

document.write("document.write(\" <textarea name='Text1' cols=\"+col+\" rows=\"+row+\" id='textbox' style='HelveticaNeue-Light'>\");");

A: You can add your string directly to an element by setting its innerText:
var myDiv = document.getElementById('myDiv');
myDiv.innerText = '
These p tags will be displayed as text
';

A: You to HTML encode it, like so
document.write("document.write(\" <textarea name=\"Text1\" cols=\"+col+\"rows=\"+row+\" id=\"textbox\" style=\"HelveticaNeue-Light\">\");".replace('<', '<').replace('>', '>'));


text:
Q: Get XML child nodes and concatanate values with ; in Groovy I have bellow XML document:
xmlIn:
<SalesOrder>
<Parameter>Parameter1</Parametro>
<Method>Method1</Metodo>
<Orders>
<Order>
    <Salesman>44</Salesman>
    <Customer>12345</Customer>
    <OrderNumber>100200300</OrderNumber>
</Order>
<Order>
    <Salesman>45</Salesman>
    <Customer>67890</Customer>
    <OrderNumber>400500600</OrderNumber>
</Order>
</Orders>

And I have a request to transform into a string in Groovy:
Field1;Field2;Field3
44;12345;100200300
45;67890;400500600
My source code is:
def parser = new XmlSlurper().parseText(xmlIn)
        String header = 'Field1;Field2;Field3'
        def lines = parser.Orders.Order.children().each {
            it.text()
        }.join(";")
        prinln(header + "\n" + lines)

However this is producing:
Field1;Field2;Field3
44;12345;100200300;45;67890;400500600
Does anyone can help me on this?
Thank you very much!

A: def lines = parser.Orders.Order.collect{order->
    order.children().collect{it.text()}.join(';')
}.join('\n')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show a subring of the ring of formal power series is finite generated Let $F$ be a field, and $F[[X]]$ be the ring of formal power series over F.
Let $$R=\{a+X^2 f(X):a∈F,f(X)∈F[[X]]\}$$ and let $\alpha\in F[[X]]$. Show the subring of $F[[X]]$ that generated by $R$ and $\alpha$, $R[\alpha]$, is a finite generated $R$-module.
I am not sure about this question, any help is appreciated!

A: Hint. Write $\alpha = a_0 + a_1X + X^2f_\alpha(X)$, $f_\alpha(X) \in F\def\p{[\![X]\!]}\p$. Then
\begin{align*}
  \alpha^2 &= a_0^2 + 2a_0a_1X + X^2g_\alpha(X)
\end{align*}
for some $g_\alpha(X) \in F\p$. Hence
$$ \alpha^2 = 2a_0\alpha - \underbrace{\bigl(a_0^2 + 2a_0X^2f_\alpha(X) - X^2g_\alpha(X)\bigr)}_{\in R} $$


text:
Q: what is the difference between lambda function and std::function in C++11? In my case, i defined a function in two different ways, fun1 is a lambda function, func2 is a regular std function,but the lambda one doesn't work with variadic arguments template funcction(vat_function).
the code below shows the problem:
#include <functional>
using namespace std;

template <typename... ParamTypes>
void vat_function(std::function<void(ParamTypes...)>,ParamTypes... parames)
{//this is a variadic arguments template function
};

void faa_function(std::function<void(bool,int)>,bool b,int i)
{//this is a std::function as parameter function
};

int main()
{
    auto func1 = [](bool,int)->void
    {
    };
    std::function<void(bool,int)> func2 = [](bool,int)->void
    {
    };

    bool b=false;
    int i=0;
    vat_function<bool,int>(func1,b,i);//only this one doesn't work
    vat_function<bool,int>(func2,b,i);//OK

    faa_function(func1,b,i);//OK
    faa_function(func2,b,i);//OK
}

vat_function(func1,b,i) doesn't work, why faa_function(func1,b,i) works?


text:
Q: Multiple ornaments between the corners I would like to bring in several ornamental elements in the lines between the corners. I'am usigng,
\begin{tikzpicture}[every node/.style={inner sep=0pt}]
\node[shift={(1.cm,-1cm)},anchor=north west](CNW)
at (current page.north west) {\pgfornament[width=1.75cm]{61}};
\node[shift={(-1cm,-1cm)},anchor=north east](CNE)
at (current page.north east) {\pgfornament[width=1.75cm,symmetry=v]{61}};
\node[shift={(1cm,1cm)},anchor=south west](CSW)
at (current page.south west) {\pgfornament[width=1.75cm,symmetry=h]{61}};
\node[shift={(-1cm,1cm)},anchor=south east](CSE)
at (current page.south east) {\pgfornament[width=1.75cm,symmetry=c]{61}};
\pgfornamentline{CNW}{CNE}{87}
\pgfornamentline{CSW}{CSE}{87}
\pgfornamentline{CNW}{CSW}{87}
\pgfornamentline{CNE}{CSE}{87}
\end{tikzpicture}%

but i could not define the majority of ornaments between the corners.
The normal definition is known from the package description,
\begin{tikzpicture}[bullet/.style={% circle,draw,fill=black!30,inner sep=2pt}] \draw [help lines,color=black!60] (0,0) grid (5,2); \node[bullet] (A) at (0,0) {}; \node[bullet] (B) at (6,4) {}; \pgfornamentline[color=red]{A}{B}{4}{88} \end{tikzpicture}

but does not lead to the desired result here.
I need help, thank you very much!
For a better understanding of the problem, a sketch.

The background option should be enough.
So far so good. I tried to modify it with a colored frame.
\documentclass{article}
\usepackage{xcolor}
\usepackage[object=vectorian]{pgfornament}
\usepackage{background}
\usetikzlibrary{calc}
\usepackage{lipsum}

\begin{document}

\backgroundsetup{
scale=1,
opacity=1,
angle=0,
color=black,
contents={%
\begin{tikzpicture}[every node/.style={inner sep=0pt}]
\node[shift={(1cm,-1cm)},anchor=north west](CNW)
at (current page.north west) {\pgfornament[width=1.75cm]{61}};
\node[shift={(-1cm,-1cm)},anchor=north east](CNE)
at (current page.north east) {\pgfornament[width=1.75cm,symmetry=v]{61}};
\node[shift={(1cm,1cm)},anchor=south west](CSW)
at (current page.south west) {\pgfornament[width=1.75cm,symmetry=h]{61}};
\node[shift={(-1cm,1cm)},anchor=south east](CSE)
at (current page.south east) {\pgfornament[width=1.75cm,symmetry=c]{61}};
\pgfornamentline{CNW.north east}{CNE.north west}{3}{87}
\pgfornamentline{CSW.south east}{CSE.south west}{3}{87}
\pgfornamentline{CNW.south west}{CSW.north west}{5}{87}
\pgfornamentline{CNE.south east}{CSE.north east}{5}{87}
\fill[blue] (current page.south west) rectangle ( $ (current page.north west) + (3cm,0) $);
\fill[blue] (current page.south east) rectangle ( $ (current page.north east) + (-3cm,0) $);
\fill[blue] (current page.north west) rectangle ( $ (current page.north east) + (0,-3cm) $);
\fill[blue] (current page.south west) rectangle ( $ (current page.south east) + (0,3cm) $);
\end{tikzpicture}%
}
}

\lipsum[1-20]

\end{document}

But the ornament structure is overwritten. Can I determine a corresponding level order or is there another solution. Wouldn't lose the ability to manually adjust the colored frame if possible.

A: Amended answer
After examining the layout sketch added, and some other information surfacing, several paths to a solution become available.
The question is many-parts.
Dealing with the first part, an ornamental frame, we have:
(1) eso-pic package, and drawing on the PDF picture background layer (adapting @user11232 solution at ornaments in pgfornament to be at the corners at every page)
(2) background package (which runs on top of TikZ), and drawing a tikzpicture (adapting @GonzaloMedina solution at the same link as above)
(3) picture mode, and making a zero-width picture and placing it in the footer using fancyhdr package (Thanks to @BarbaraBeeton for the link to the Peter Wilson 2011 TUGboat article v32 p202).
As to the second matter, the question how many ornamental glyphs should go along an edge, aside from it being a judgemental/opinion-based question, an automatic solution (or solutions) could be designed and built (using some set of as-yet unspecified aesthetic rules), but, since the definition is only ever done once, manually implementing it is much more practical (and simpler).
For example, because \pgfornamentline can take a scale= option, thus making the number of ornaments discretionary according to taste, the ratio of the long:short edges of the page can be used as a guideline (or not): 5:3 (left:top) for A4 portrait, say; or 2:3 (left:top) for A5 landscape.
An automated solution sounds desirable and a method like this would involve tracking three dimensions, the page-edge ratio, the ornament scale factor, and the ornament height/width ratio, keeping two of them constant while varying the third, but won't be pursued further here (at least not tonight, anyway).

So:
The Frame
(1)eso-pic package drawing on the background layer with \AddToShipoutPictureBG.
Positioning and layout is manual.
The ornament line is assembled, so individual items are accessible (although, an assembled set of elements could be fed in, and repeated once only).
For completeness, for a version with an on/off switch for the frame, see (1a).

MWE
\documentclass[12pt]{article}
\usepackage{pgfornament}
\usepackage{eso-pic}
\usepackage{rotating}
\usepackage{xcolor}
\usepackage{lipsum}

\newcommand\AtPageUpperRight[1]{\AtPageUpperLeft{%
 \put(\LenToUnit{\paperwidth},\LenToUnit{0\paperheight}){#1}%
 }}%
\newcommand\AtPageLowerRight[1]{\AtPageLowerLeft{%
 \put(\LenToUnit{\paperwidth},\LenToUnit{0\paperheight}){#1}%
 }}%

\newcommand\ornscale{0.42}
\newcommand\ornscalev{0.44}

\newcommand\leavesthree{\pgfornament[scale=\ornscale]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscale]{87}}

\newcommand\leavesfive{\turnbox{-90}{\pgfornament[scale=\ornscalev]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscalev]{87}}}

\AddToShipoutPictureBG{%
   \AtPageUpperLeft{\put(25,-50){\textcolor{blue}{\pgfornament[width=1.75cm]{61}}}}
   \AtPageUpperRight{\put(-75,-50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=v]{61}}}}
   \AtPageLowerLeft{\put(25,50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=h]{61}}}}
   \AtPageLowerRight{\put(-75,50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=c]{61}}}}
   \AtPageUpperLeft{\put(78,-25){\leavesthree}}%top border
   \AtPageLowerLeft{\put(78,27){\leavesthree}}%bottom
   \AtPageUpperLeft{\put(25,-78){\leavesfive}}%left side
   \AtPageUpperRight{\put(-25,-78){\leavesfive}}%right side
   }

\begin{document}
\lipsum[1-40]
\end{document}

(1a)
To make the frame switchable on/off, create a new IF variable:
\newif{\ifbgoff}
\bgofftrue

where (in this methodology) true will mean "no frame" (as in "background off").
Add the if-condition to the \AddToShipoutPictureBG command like so:
\AddToShipoutPictureBG{%
 \ifbgoff\else  *<existing code>* \fi}

Usage: Toggle the frame on (with \bgofffalse)/off (with \bgofftrue) in conjunction with a \newpage or equivalent.
\begin{document}
\section{Off}
\lipsum[1-15]
\bgofffalse
\section{On}
\lipsum[1-15]

\newpage
\bgofftrue
\section{Off Again}
\lipsum[1-8]

\newpage\bgofffalse
\section{On Again}
\lipsum[1-15]

\newpage
\bgofftrue
\section{And Off Once More}
\lipsum[1-8]

\end{document}

Full MWE:
\documentclass[12pt]{article}
\usepackage{pgfornament}
\usepackage{eso-pic}
\usepackage{rotating}
\usepackage{xcolor}
\usepackage{lipsum}

\newcommand\AtPageUpperRight[1]{\AtPageUpperLeft{%
 \put(\LenToUnit{\paperwidth},\LenToUnit{0\paperheight}){#1}%
 }}%
\newcommand\AtPageLowerRight[1]{\AtPageLowerLeft{%
 \put(\LenToUnit{\paperwidth},\LenToUnit{0\paperheight}){#1}%
 }}%

\newcommand\ornscale{0.42}
\newcommand\ornscalev{0.44}

\newcommand\leavesthree{\pgfornament[scale=\ornscale]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscale]{87}}

\newcommand\leavesfive{\turnbox{-90}{\pgfornament[scale=\ornscalev]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscalev]{87}}}

\newif{\ifbgoff}
\bgofftrue

\AddToShipoutPictureBG{%
 \ifbgoff\else  \AtPageUpperLeft{\put(25,-50){\textcolor{blue}{\pgfornament[width=1.75cm]{61}}}}
   \AtPageUpperRight{\put(-75,-50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=v]{61}}}}
   \AtPageLowerLeft{\put(25,50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=h]{61}}}}
   \AtPageLowerRight{\put(-75,50){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=c]{61}}}}
   \AtPageUpperLeft{\put(78,-25){\leavesthree}}%top border
   \AtPageLowerLeft{\put(78,27){\leavesthree}}%bottom
   \AtPageUpperLeft{\put(25,-78){\leavesfive}}%left side
   \AtPageUpperRight{\put(-25,-78){\leavesfive}}%right side
   \fi}

\begin{document}
\section{Off}
\lipsum[1-15]
\bgofffalse
\section{On}
\lipsum[1-15]

\newpage
\bgofftrue
\section{Off Again}
\lipsum[1-8]

\newpage\bgofffalse
\section{On Again}
\lipsum[1-15]

\newpage
\bgofftrue
\section{And Off Once More}
\lipsum[1-8]

\end{document}

(2) background package plus tikzpicture in the \backgroundsetup command.
Positioning elements is much easier with TikZ.
The ornament line is a unit.
Backgrounds can be switched on/off or changed within the document on a page(s) basis.

MWE
\documentclass[12pt]{article}
\usepackage{background}
\usepackage{pgfornament}
\usepackage{lipsum}
\usetikzlibrary{calc}

\backgroundsetup{
scale=1,
opacity=1,
angle=0,
color=black,
contents={%
\begin{tikzpicture}[every node/.style={inner sep=0pt}]
\node[shift={(1cm,-1cm)},anchor=north west](CNW)
at (current page.north west) {\pgfornament[width=1.75cm]{61}};
\node[shift={(-1cm,-1cm)},anchor=north east](CNE)
at (current page.north east) {\pgfornament[width=1.75cm,symmetry=v]{61}};
\node[shift={(1cm,1cm)},anchor=south west](CSW)
at (current page.south west) {\pgfornament[width=1.75cm,symmetry=h]{61}};
\node[shift={(-1cm,1cm)},anchor=south east](CSE)
at (current page.south east) {\pgfornament[width=1.75cm,symmetry=c]{61}};
\pgfornamentline{CNW.north east}{CNE.north west}{3}{87}
\pgfornamentline{CSW.south east}{CSE.south west}{3}{87}
\pgfornamentline{CNW.south west}{CSW.north west}{5}{87}
\pgfornamentline{CNE.south east}{CSE.south east}{5}{87}
\end{tikzpicture}%
  }
}

\begin{document}
\lipsum[1-40]
\end{document}

(3) a picture mode zero-width picture in the footer (or header, if desired)
Picture mode is used, so positioning is manual here.
Footers and headers (and associated pagestyles) can be modified using fancyhdr package commands.

MWE
\documentclass[12pt]{article}
\usepackage{pgfornament}
%\usepackage{eso-pic}
\usepackage{rotating}
\usepackage{xcolor}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{lipsum}

\newcommand\ornscale{0.39}
\newcommand\ornscalev{0.45}

\newcommand\leavesthree{\pgfornament[scale=\ornscale]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscale]{87}}

\newcommand\leavesfive{\turnbox{-90}{\pgfornament[scale=\ornscalev]{87}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\textcolor{red}{\pgfornament[scale=\ornscale]{87}}\pgfornament[scale=\ornscalev]{87}}}

%\pgfornament[width=2cm]{3}

\newcommand*{\upit}[2]{\raisebox{#1}{#2}}\newcommand*{\rotpi}[1]{\rotatebox{180}{#1}}\newcommand*{\rotrt}[1]{\rotatebox{90}{#1}}\newcommand*{\rotlft}[1]{\rotatebox{-90}{#1}}

%%% draws a (page) frame
\newcommand*{\goddfoot}{\begin{picture}(0,0)
%\wb{10pt}{10pt}
\put(-70,-50){% change these to move the frame
\begin{picture}(0,0)
\multiput(52,0)(0,0){1}{\leavesthree}   % bottom
\multiput(5,669)(0,0){1}{\leavesfive}   % left
\multiput(530,669)(0,0){1}{\leavesfive}  % right
\multiput(52,718)(0,0){1}{\leavesthree} % top
\put(0,700){\textcolor{blue}{\pgfornament[width=1.75cm]{61}}}%TL
\put(485,700){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=v]{61}}}%TR
\put(0,20){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=h]{61}}}%BL
\put(485,20){\textcolor{blue}{\pgfornament[width=1.75cm,symmetry=c]{61}}}%BR
\end{picture}}
\end{picture}}
\let\gevenfoot\goddfoot

\fancyfoot[L]{\goddfoot}

\begin{document}
\lipsum[1-40]
\end{document}

Original answer
You need to supply a Minimum Working Example so people can test their answers against without having to guess anything; and also use the remember picture,overlay options (as the manual says).
I am not sure what you intend the anchors for.
This MWE:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfornament}

\begin{document}
\begin{tikzpicture}[remember picture,overlay,every node/.style={inner sep=0pt}]
\node [shift={(1cm,-1cm)},blue,scale=2] (CNW)
at (current page.north west) {\pgfornament[height=1cm,width=1cm]{61}};
\node [shift={(-1cm,-1cm)},blue,scale=2] (CNE)
at (current page.north east) {\pgfornament[height=1cm,width=1cm,symmetry=v]{61}};
\node [shift={(1cm,1cm)},blue,scale=2] (CSW)
at (current page.south west) {\pgfornament[height=1cm,width=1cm,symmetry=h]{61}};
\node [shift={(-1cm,1cm)},blue,scale=2] (CSE)
at (current page.south east) {\pgfornament[height=1cm,width=1cm,symmetry=c]{61}};
\pgfornamentline[color=brown]{CNW}{CNE}{2}{87}
\pgfornamentline{CSW}{CSE}{2}{87}
\pgfornamentline{CNW}{CSW}{3}{87}
\pgfornamentline{CNE}{CSE}{3}{87}
\end{tikzpicture}%

produces this:

Addition
In TikZ, there are multiple ways to achieve the same effect.
If I understand the statement in the comments correctly, if the goal is to draw ornamental lines between the corners of a page, from corner to corner, and such that the centre of the line is on the page edge, then one way is -- to draw ornamental lines between the corners of the page:
\pgfornamentline[color=brown]{current page.north west}{current page.north east}{2}{87}
\pgfornamentline{current page.south west}{current page.south east}{2}{87}
\pgfornamentline{current page.north west}{current page.south west}{3}{87}
\pgfornamentline{current page.north east}{current page.south east}{3}{87}

To avoid being overwritten, (one method is) the corner ornaments can be pushed out of the way with the anchor= options.

MWE2
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfornament}

\begin{document}
\begin{tikzpicture}[remember picture,overlay,every node/.style={inner sep=0pt}]
\node [shift={(1cm,-1cm)},blue,scale=2,anchor=north west] (CNW)
at (current page.north west) {\pgfornament[height=1cm,width=1cm]{61}};
\node [shift={(-1cm,-1cm)},blue,scale=2,anchor=north east] (CNE)
at (current page.north east) {\pgfornament[height=1cm,width=1cm,symmetry=v]{61}};
\node [shift={(1cm,1cm)},blue,scale=2,anchor=south west] (CSW)
at (current page.south west) {\pgfornament[height=1cm,width=1cm,symmetry=h]{61}};
\node [shift={(-1cm,1cm)},blue,scale=2,anchor=south east] (CSE)
at (current page.south east) {\pgfornament[height=1cm,width=1cm,symmetry=c]{61}};
%\pgfornamentline[color=brown]{CNW}{CNE}{2}{87}
%\pgfornamentline{CSW}{CSE}{2}{87}
%\pgfornamentline{CNW}{CSW}{3}{87}
%\pgfornamentline{CNE}{CSE}{3}{87}
\pgfornamentline[color=brown]{current page.north west}{current page.north east}{2}{87}
\pgfornamentline{current page.south west}{current page.south east}{2}{87}
\pgfornamentline{current page.north west}{current page.south west}{3}{87}
\pgfornamentline{current page.north east}{current page.south east}{3}{87}
\end{tikzpicture}%

%\begin{tikzpicture}[bullet/.style={%
%circle,draw,fill=black!30,inner sep=2pt}]
%\draw [help lines,color=black!60] (0,0) grid (5,2);
%\node[bullet] (A) at (0,0) {}; \node[bullet] (B) at (6,4) {};
%\pgfornamentline[color=red]{A}{B}{4}{88}
%\end{tikzpicture}
\end{document}


text:
Q: PUT request not passing HTML form data as object I'm having trouble passing an object through to my PUT route via an HTML form. When I try to console.log the 'product' object the terminal reads undefined. I've got Method Override installed and everything works fine if I don't try to pass the data as an object. e.g. name="title" and name="price".
app.js
router.put('/events/:id', function(req, res){
   console.log(req.body.product);
   res.redirect('/events/');
});

HTML
<form action="/events/<%= product._id %>?_method=PUT" method="POST">

    <input class="form-control" type="text" name="product[title]" value="<%= product.title%>">

    <input class="form-control" type="text" name="product[price]" value="<%= product.price%>">

    <button>Submit</button>

</form>

A: Your problem is not correctly configuring body-parser since you can reach your middleware and print out something from there to your console. Just to make sure you have configured something like this:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: 'application/json' }));

Then your app should correctly populate the input value to req.body.


text:
Q: How do you pass values to javascript in view template in MVC5? How do you pass values from a model to a javascript paging script in MVC? I have a paging model and need to pass values to the following javascript in the view template:
  <script type='text/javascript'>
    var options = {
        currentPage: 2,
        totalPages: 4,
        numberOfPages: 5,
        onPageChanged: function(e,oldPage,newPage){

        },
        pageUrl: function(type, page, current) {

I need to pass values in my model to replace the hard coded values in the above javascript.

A: In case someone finds useful:
 <script type='text/javascript'>
    var options = {
        currentPage:@Html.DisplayFor(modelItem => modelItem.Sessionstateadminroot.CourseCurrentPage),
        totalPages:@Html.DisplayFor(modelItem => modelItem.Sessionstateadminroot.CourseTotalPages),
        numberOfPages:4,
        onPageChanged: function(e,oldPage,newPage){

        },
        pageUrl: function(type, page, current) {


text:
Q: How can i do pagination and searching in YII? Here is my controller code for displaying..
  $this->layout = 'admin-home';
             $studios = AccountsStudios::model()->with('generalUserStudiosesCount')->findAll();

             #print_r($studios);
             $this->render('listStudios', array('studios' => $studios));

Am entirely new to YII... i want to include filter option,search and pagination .
Any good references?

A: CGridView displays a list of data items in terms of a table.
Each row of the table represents the data of a single data item, and a column usually represents an attribute of the item (some columns may correspond to complex expression of attributes or static text).
CGridView supports both sorting and pagination of the data items. The sorting and pagination can be done in AJAX mode or normal page request. A benefit of using CGridView is that when the user browser disables JavaScript, the sorting and pagination automatically degenerate to normal page requests and are still functioning as expected.
CLick Here to get more deatls


text:
Q: Access Violation After Windows Resume from Sleep I have had a few users report a AV for my application after they close their laptop lid and reopen it. I assume Windows went into Sleep Mode and the problem occurs on resume. It's a standard Windows 32 bit application written in Delphi Seattle 10.
What happens to an application after it wakes up from "sleep"? Anyone have any ideas? How can this be corrected?
Below I've posted the Call Stack which give the error - I cannot see anything particularly wrong,
Steve
Access violation at address 00000000 in module 'AlignMix.exe'. Read of address 00000000.

[011A1B43] dxBarExtItems.TPlaceForm.WMEraseBkgnd (Line 1021, ''dxBarExtItems.pas'')
[0064787D] Vcl.Controls.TControl.WndProc
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[0074B344] Vcl.Forms.TCustomForm.WndProc
[0064B9DC] Vcl.Controls.TWinControl.MainWndProc
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C9681B] user32 (possible DispatchMessageW+1323)
[76C9D167] user32 (possible PeekMessageW+1367)
[77088E54] ntdll.KiUserCallbackDispatcher
[76CB92CA] user32.DestroyWindow
[0064B38C] Vcl.Controls.TWinControl.DestroyWindowHandle
[00BEA26E] cxControls.TcxControl.DestroyWindowHandle (Line 5856, ''cxControls.pas'')
[0064B33D] Vcl.Controls.TWinControl.DestroyWnd
[00C19D6C] cxContainer.TcxContainer.DestroyWnd (Line 3881, ''cxContainer.pas'')
[0064B5C5] Vcl.Controls.TWinControl.DestroyHandle
[0074D5AD] Vcl.Forms.TCustomForm.DestroyHandle
[0064B976] Vcl.Controls.TWinControl.SetParentWindow
[011AD042] dxBarExtItems.TdxBarControlContainerControl.PlaceControl (Line 5230, ''dxBarExtItems.pas'')
[011ACF6A] dxBarExtItems.TdxBarControlContainerControl.InternalPaint (Line 5209, ''dxBarExtItems.pas'')
[011AD542] dxBarExtItems.TdxBarControlContainerControl.DoPaint (Line 5333, ''dxBarExtItems.pas'')
[00C83188] dxBar.TdxBarItem.GetStyleValue (Line 20608, ''dxBar.pas'')
[00CB618D] dxBar.TdxBarItemControl.Paint (Line 41821, ''dxBar.pas'')
[00FC28BA] dxRibbon.TdxRibbonCustomToolbarBarControl.DoPaintItem (Line 8918, ''dxRibbon.pas'')
[00FEB7C0] dxRibbonStatusBar.TdxRibbonStatusBarBarControl.DoPaintItem (Line 522, ''dxRibbonStatusBar.pas'')
[00CBEF57] dxBar.TCustomdxBarControl.PaintItem (Line 45942, ''dxBar.pas'')
[00CBD76E] dxBar.TCustomdxBarControl.DrawItems (Line 45205, ''dxBar.pas'')
[00CC7C50] dxBar.TdxBarControl.DoPaint (Line 49698, ''dxBar.pas'')
[00CC3082] dxBar.TdxBarControl.Paint (Line 47747, ''dxBar.pas'')
[00652503] Vcl.Controls.TCustomControl.PaintWindow
[0064C589] Vcl.Controls.TWinControl.PaintHandler
[0064CD74] Vcl.Controls.TWinControl.WMPaint
[0065249D] Vcl.Controls.TCustomControl.WMPaint
[00CBB22A] dxBar.TCustomdxBarControl.WMPaint (Line 44163, ''dxBar.pas'')
[00FC2B98] dxRibbon.TdxRibbonCustomToolbarBarControl.WMPaint (Line 9007, ''dxRibbon.pas'')
[0064787D] Vcl.Controls.TControl.WndProc
[0064787D] Vcl.Controls.TControl.WndProc
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[00CBBDFF] dxBar.TCustomdxBarControl.WndProc (Line 44477, ''dxBar.pas'')
[00CC521D] dxBar.TdxBarControl.WndProc (Line 48701, ''dxBar.pas'')
[006474B8] Vcl.Controls.TControl.Perform
[00BE1F82] cxControls.dxBufferedPaintControl (Line 2087, ''cxControls.pas'')
[00FC2BE9] dxRibbon.TdxRibbonCustomToolbarBarControl.WMPaint (Line 9016, ''dxRibbon.pas'')
[0064787D] Vcl.Controls.TControl.WndProc
[0064787D] Vcl.Controls.TControl.WndProc
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[00CBBDFF] dxBar.TCustomdxBarControl.WndProc (Line 44477, ''dxBar.pas'')
[00CC521D] dxBar.TdxBarControl.WndProc (Line 48701, ''dxBar.pas'')
[0064B9DC] Vcl.Controls.TWinControl.MainWndProc
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C9681B] user32 (possible DispatchMessageW+1323)
[76C9D167] user32 (possible PeekMessageW+1367)
[77088E54] ntdll.KiUserCallbackDispatcher
[0064F0C5] Vcl.Controls.TWinControl.Update
[0064F0DD] Vcl.Controls.TWinControl.Repaint
[00CAE3E7] dxBar.TdxDockControl.PaintBarControls (Line 38531, ''dxBar.pas'')
[00CAE69A] dxBar.TdxDockControl.UpdateDock (Line 38596, ''dxBar.pas'')
[00CC4B8A] dxBar.TdxBarControl.DoRepaintBar (Line 48491, ''dxBar.pas'')
[00CBE853] dxBar.TCustomdxBarControl.RepaintBarEx (Line 45726, ''dxBar.pas'')
[00CC00AC] dxBar.TCustomdxBarControl.RepaintBar (Line 46422, ''dxBar.pas'')
[00CC8523] dxBar.TdxBarControl.RebuildBar (Line 49912, ''dxBar.pas'')
[00CC781D] dxBar.TdxBarControl.BarManagerStyleChanged (Line 49618, ''dxBar.pas'')
[00C7B545] dxBar.TdxBarManager.InternalStyleChanged (Line 17475, ''dxBar.pas'')
[00C7B5AA] dxBar.TdxBarManager.LFChanged (Line 17492, ''dxBar.pas'')
[00BCA0D8] cxLookAndFeels.TcxLookAndFeel.Changed (Line 589, ''cxLookAndFeels.pas'')
[00BCA670] cxLookAndFeels.TcxLookAndFeel.SystemPaletteChanged (Line 749, ''cxLookAndFeels.pas'')
[00BCB178] cxLookAndFeels.TcxSystemPaletteChangedNotifier.DoChanged (Line 1122, ''cxLookAndFeels.pas'')
[00BC9B95] cxLookAndFeels.TcxSystemPaletteChangedListener.DoChange (Line 431, ''cxLookAndFeels.pas'')
[00BC9BC9] cxLookAndFeels.TcxSystemPaletteChangedListener.WndProc (Line 439, ''cxLookAndFeels.pas'')
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C9681B] user32 (possible DispatchMessageW+1323)
[76C9D167] user32 (possible PeekMessageW+1367)
[77088E54] ntdll.KiUserCallbackDispatcher
[76C95EDE] user32.SendMessageW
[73EB9085] shell32.SHAppBarMessage
[00F985D2] dxRibbonForm.TdxCustomRibbonForm.IsNeedCorrectForAutoHideTaskBar (Line 1271, ''dxRibbonForm.pas'')
[00F98332] dxRibbonForm.TdxCustomRibbonForm.CalculateZoomedOffsets (Line 1197, ''dxRibbonForm.pas'')
[00F99925] dxRibbonForm.TdxCustomRibbonForm.WMNCCalcSize (Line 1917, ''dxRibbonForm.pas'')
[0064787D] Vcl.Controls.TControl.WndProc
[770685E2] -= a recursive area removed =- (Line 2)
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[0074B344] Vcl.Forms.TCustomForm.WndProc
[00F9A41F] dxRibbonForm.TdxCustomRibbonForm.WndProc (Line 2284, ''dxRibbonForm.pas'')
[00BF08E9] cxControls.TcxWindowProcLinkedObject.DefaultProc (Line 8898, ''cxControls.pas'')
[00C364D9] dxShadowWindow.TdxShadowWindow.OwnerWindowWndProc (Line 375, ''dxShadowWindow.pas'')
[00BF0CBD] cxControls.TcxWindowProcLinkedObjectList.WndProc (Line 9010, ''cxControls.pas'')
[0064B9DC] Vcl.Controls.TWinControl.MainWndProc
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C969D2] user32.CallWindowProcW
[0125F5B9] FormSize.TFormSize.HookWndProc (Line 432, ''FormSize.pas'')
[77055E63] ntdll (possible RtlActivateActivationContextUnsafeFast+211)
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C9681B] user32 (possible DispatchMessageW+1323)
[76C9EC9D] user32 (possible RemovePropW+221)
[77088E54] ntdll.KiUserCallbackDispatcher
[0064787D] Vcl.Controls.TControl.WndProc
[0064C3BD] Vcl.Controls.TWinControl.WndProc
[0074B344] Vcl.Forms.TCustomForm.WndProc
[00F9A41F] dxRibbonForm.TdxCustomRibbonForm.WndProc (Line 2284, ''dxRibbonForm.pas'')
[00BF08E9] cxControls.TcxWindowProcLinkedObject.DefaultProc (Line 8898, ''cxControls.pas'')
[00C364D9] dxShadowWindow.TdxShadowWindow.OwnerWindowWndProc (Line 375, ''dxShadowWindow.pas'')
[00BF0CBD] cxControls.TcxWindowProcLinkedObjectList.WndProc (Line 9010, ''cxControls.pas'')
[0064B9DC] Vcl.Controls.TWinControl.MainWndProc
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C969D2] user32.CallWindowProcW
[0125F5B9] FormSize.TFormSize.HookWndProc (Line 432, ''FormSize.pas'')
[77055E63] ntdll (possible RtlActivateActivationContextUnsafeFast+211)
[00502E50] System.Classes.StdWndProc
[76CB84F1] user32 (possible SetManipulationInputTarget+81)
[76C96C3B] user32 (possible CallWindowProcW+763)
[76C9681B] user32 (possible DispatchMessageW+1323)
[76C9F76E] user32 (possible InitDManipHook+1246)
[77088E54] ntdll.KiUserCallbackDispatcher
[76C9CD7A] user32 (possible PeekMessageW+362)
[007548C0] Vcl.Forms.TApplication.ProcessMessage
[007549E2] Vcl.Forms.TApplication.HandleMessage
[00754D15] Vcl.Forms.TApplication.Run
[0173E485] AlignMix.Initialization (Line 203, ''AlignMix.dpr'')
[75A438F2] KERNEL32.BaseThreadInitThunk


text:
Q: Best way to display only URL domain using jinja2 I have URLs stored in a Django model that I would like to display on a template, but I would only like to display the domain like this:
original_url:
https://wikipedia.org/wiki/List_of_chemical_process_simulators

display:
wikipedia.org/...

Would it be better to handle this on entirely on the back-end, font-end, or a custom function on with jinja2?

A: If it is something you would later reuse in the templates throughout the project and, taking into account that there is a pretty simple logic involved, defining a custom template filter would be perfectly okay here.
Use urlparse.urlparse() to get the domain name:
>>> from urlparse import urlparse
>>> from jinja2 import Environment, Template
>>>
>>> def get_domain(url):
...     return "%s/..." % urlparse(url).netloc
...
>>>
>>> env = Environment()
>>> env.filters['domain'] = get_domain
>>>
>>> template = env.from_string('{{ url|domain }}')
>>> template.render(url='https://wikipedia.org/wiki/List_of_chemical_process_simulators')
u'wikipedia.org/...'

This is a simple example, you should additionally provide an error-handling mechanism in case urlparse() would fail parsing the url passed in.

A: The best way would probably be a custom template filter as answered by @alecxe, but in case you can't, here is a non-fool-proof way for future reference.
{{ original_url.rpartition("//")[-1] }}

*

*https://wikipedia.org/wiki/List_of_chemical_process_simulators → wikipedia.org/wiki/List_of_chemical_process_simulators

*//example.net/path/to/file → example.net/path/to/file

*ftp://example.net/pub → example.net/pub
Get just the domain name (hostname):
{{ original_url.rpartition("//")[-1].partition("/")[0] }}

*

*https://wikipedia.org/wiki/List_of_chemical_process_simulators → wikipedia.org

*//example.net/path/to/file → example.net

*ftp://example.net/pub → example.net


text:
Q: MongoDB: how to rename result fields in raw commands Given the following mongo command...
db.runCommand({
  "aggregate":"orders","pipeline":[
    {"$match":{"state.value":"open"}},
    {"$group":{"_id":"$currency","total":{"$sum":"$amount"}}}
  ]
})

... I get this result:
{
  "result" : [
    { "_id" : "USD", "total" : 55 },
    { "_id" : "EUR", "total" : 30 }
  ],
  "ok" : 1
}

In the result, is it possible to have currency instead of _id?
EDIT
... or event better, would it be possible to use the value of _id as the name for total like this?
{
  "result" : [
    { "USD" : 55 },
    { "EUR" : 30 }
  ],
  "ok" : 1
}

I've tried this...
db.runCommand({
  "aggregate":"orders",
  "pipeline":[
    {"$match":{"state.value":"open"}},
    {"$group":{"_id":"$currency","total":{"$sum":"$amount"}}},
    {"$project":{"_id":0,"$_id":"$total"}}
 ]

})
... but it doesn't work.

A: You should add a $project operator stage after the $group pipeline stage and your final aggregation command should be like:
db.runCommand({
    "aggregate":"orders",
    "pipeline":[
        {"$match":{"state.value":"open"}},
        {"$group":{"_id":"$currency","total":{"$sum":"$amount"}}},
        {
            "$project":{
                "_id":0,
                "currency":"$_id",
                "total": 1
            }
        }
     ]
  })

This suppresses the _id field and replaces it with the desired currency field to give the output:
{
  "result" : [
    { "currency" : "USD", "total" : 55 },
    { "currency" : "EUR", "total" : 30 }
  ],
  "ok" : 1
}

-- UPDATE --
To address your other query, MongoDB's aggregation framework does not have $project operations that can convert field values into keys. As a workaround, you could try convert the aggregation result using the forEach() cursor method to iterate over the projected fields and use JavaScript's bracket-notation on the result object to then create desired final object:
var pipeline = [
        {"$match":{"state.value":"open"}},
        {"$group":{"_id":"$currency","total":{"$sum":"$amount"}}}
     ],
    agg = db.orders.aggregate(pipeline),
    obj = {},
    result = [];

agg.forEach(function (doc){
    obj[doc._id] = doc.total;
    result.push(obj);
});

Output of custom result array:
[
    { "USD" : 55 },
    { "EUR" : 30 }
]


text:
Q: EntLib logging to category I'm using EntLib 4.1. I want to associate log entries with different categories. My categories will reflect various interesting bits of information such as the kind of context (say, "Batch" or "Online") and the functional area (say, "Invoice" or "Order").
I've done the logging code, but I think I'm doing something wrong in configuration. What I'm trying to achieve is to have all entries logged to category "Batch" end up in the event log called "Batch", and everything else in the Application log. (I have manually created a custom event log by this name.)
However, log entries with category Batch instead get logged to the Application log, and each entry contains the following preamble:

Message: Tracing to LogSource 'Batch' failed. Processing for other sources will continue. See summary information below for more information. Should this problem persist, stop the service and check the configuration file(s) for possible error(s) in the configuration of the categories and sinks.

EntLib config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </configSections>
    <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
      defaultCategory="APPLICATION" logWarningsWhenNoCategoriesMatch="true">
        <listeners>
            <add source="Project II Logger" formatter="Text Formatter" log="Batch"
              machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="BatchListener" />
            <add source="Project II Logger" formatter="Text Formatter" log="Application"
              machineName="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              traceOutputOptions="Callstack" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="DefaultListener" />
            <add fileName="c:\temp\trace.log" header="----------------------------------------"
              footer="----------------------------------------" formatter="ExceptionFormatter"
              listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              traceOutputOptions="Callstack" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="Exception TraceListener" />
        </listeners>
        <formatters>
            <add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
ErrorMessages: {errorMessages}"
              type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="ExceptionFormatter" />
            <add template="Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
ErrorMessages: {errorMessages}"
              type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
              name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="APPLICATION">
                <listeners>
                    <add name="DefaultListener" />
                </listeners>
            </add>
            <add switchValue="All" name="Batch">
                <listeners>
                    <add name="BatchListener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category" />
            <errors switchValue="All" name="Logging Errors & Warnings">
                <listeners>
                    <add name="DefaultListener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
</configuration>

A: My guess is that you have not created the appropriate event log and/or event sources within that log.
The problem doesn't appear to be in the configuration file.
If you choose to set up the new log and such from a bat file or console app, make sure to run it under admin.
creating log and source win 7


text:
Q: How to compress an image until a fixed byte size is reached I have an application that needs to communicate with a server exchanging images via their Base64 representation. Due to server capacity, I can only compress and send images that are < 100KB of size. I can easily retrieve the size of the image using:
File file= new File(path);
long size = file.length() / 1024;  // KB

and that displays the exact size. Then I decode it into a Bitmap and compress it using:
int quality= 100;

Bitmap bitmap = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] byteArr = baos.toByteArray();

And here things get dirty. I can't properly retrieve the exact size value as I did before, because if the size is > 100KB then I need to re-compress it adjusting the quality.
EDIT: forgot to mention that I have tried byte.length method but the resulting size isn't the same as it was before.
In this example, I have tried with an 80KB image, as shown in the AndroidStudio Console:

A: You may want to use this library which accepts Max-Size (in kb) for compression.
Example (From readme.md):
   Luban.compress(context, file)
            .setMaxSize(100)                // limit the final image size(unit:Kb)
            .setMaxHeight(1920)             // limit image height
            .setMaxWidth(1080)              // limit image width
            .putGear(Luban.CUSTOM_GEAR)     // use CUSTOM GEAR compression mode
            .asObservable()

However i strongly suggest you to not send binary data (such as images) as Base64 since it'll reduce performance and increase size!
It's better to upload it in binary.
If none of above solutions suits you, then at least try to implement your method using binary search.

A: You'll need to loop over your compression section, reducing the value of quality each loop until the desired size is reached. You can check the size by evaluating byteArr.length


text:
Q: Will Cassandra reach eventual consistency without manual repair if there is no read for that data during gc.grace.seconds? Assume the following

*

*Replication factor is 3

*A delete was issued with consistency 2

*One of the replica was busy (not down) so it drops the request

*The other two replicas add the tombstone and send the response. So currently the record is marked for deletion in only two replicas.

*There is no read repair happened as there was no read for that data gc.grace.seconds
Q1.
Will this data be resurrected when a read happens for that record after gc.grace.seconds if there was no manual repair?
(I am not talking about replica being down for more than gc.grace.seconds)

A:
One of the replica was busy (not down) so it drops the request

In this case, the coordinator node realizes that the replica could not be written and stores it as a hint.  Once the overwhelmed node starts taking requests again, the hint is "replayed" to get the replica consistent.
However, hints are only kept (by default) for 3 hours.  After that time, they are dropped.  So, if the busy node does not recover within that 3 hour window, then it will not be made consistent.  And yes, in that case a query at consistency-ONE could allow that data to "ghost" its way back.


text:
Q: Output rows that contains different value from 2 dataframes Code references by Compare two DataFrames and output their differences side-by-side
df1
----
#     id   score isEnrolled               Comment
# 0  111   2.17       True  He was late to class
# 1  112   1.11      False             Graduated
# 2  113   4.12       True                   NaN

df2
----
# 0  111   2.17       True  He was late to class
# 1  112   1.21      False             Graduated
# 2  113   4.12      False           On vacation

df.set_index('id', inplace=True)
def report_diff(x):
    return x[0] if x[0] == x[1] else '{} | {}'.format(*x)

changes = df.groupby(level=0, axis=1).apply(lambda x: x.apply(report_diff, axis=1))
print(changes)

My expected output are rows that have different values (not including id 111)
      score       isEnrolled            Comment
id
112  1.11 | 1.21     False             Graduated
113     4.12        True | False     nan | On vacation

A: Combine each data frame and group the combined ones by 'id' to list the duplicates. Next, we run a duplicate check function (that you created) for each column. Finally, we simply remove 'id=111'.
df3 = pd.concat([df,df2],axis=0)
df3 = df3.groupby('id').agg(list).reset_index()
def report_diff(x):
    return x[0] if x[0] == x[1] else '{} | {}'.format(*x)
df3['score'] = df3['score'].apply(lambda x: report_diff(x))
df3['isEnrolled'] = df3['isEnrolled'].apply(lambda x: report_diff(x))
df3['Comment'] = df3['Comment'].apply(lambda x: report_diff(x))
df3 = df3[df3.index != 111]
df3
    score   isEnrolled  Comment
id
112 1.11 | 1.21 False           Graduated
113 4.12        True | False    nan | On vacation


text:
Q: Different kind of Java EE projects What is the different between different kind of Java EE projects in Eclipse WTP?
There are:

*

*Application Client Project

*Connector Project

*Enterprise Application Project

*Utility Project

A: Quoting the Chapter 5. Projects of the RAD v7, Programming Guide (applies to Eclipse too):

*

*Application Client Project (J2EE) — Guides the user through
  creating an empty Application Client
  project. Includes prompts for the
  associated EAR project and a list of
  facets applicable for J2EE Application
  Client projects.

*Connector Project (J2EE) — Guides the user through creating a
  J2EE connector project, which includes
  specifying the associated enterprise
  application project and a set of
  facets applicable to it.

*Enterprise Application Project (J2EE) — Creates a new EAR project.
  This includes options for creating
  associated Web, EJB, and Application
  Client projects.

*Utility Project (J2EE) — Assists in the construction of a Java utility
  library project which is associated
  with an Enterprise Application
  project. The product of such a project
  is a JAR file that is available to the
  resources within the Enterprise
  project and is automatically wrapped
  into the EAR file when it is exported.

This is detailed a few pages later:

Enterprise Application project
Enterprise Application projects contain the resources needed for enterprise
  applications and can contain references to a combination of Web modules, EJB
  modules, application client modules, resource adapter modules, utility Java
  projects, and JAR files.
These relationships can be specified when creating a new Enterprise Application
  project through the wizard or through the project properties.
For more information on developing J2EE enterprise applications, see
  Chapter 16, "Develop Web applications using EJBs" on page 719.
J2EE Application Client project
J2EE Application Client projects contain the resources needed for J2EE
  application client modules. An application client module is used to contain a
  fully-functioning client Java application (non-Web-based) that connects to and
  uses the J2EE resources in a J2EE enterprise application and an application
  server. By holding a reference to the associated enterprise application, it shares
  information such as the Java Naming and Directory Interface (JNDI) reference to
  EJBs and data sources.
Connector project
A connector project contains the resources required for a J2EE resource adapter.
  The wizard allows a set of facets (including the J2EE Connector Architecture
  (JCA) version) and containing EAR file to be specified.

Short version: they are all wizards to create an Enterprise Application or its parts.


text:
Q: Windows 7 starter will not shutdown or logoff Im having some problems with a friends netbook (a dell mini 10). It will not shutdown or logoff via the usual route. Whenever the shutdown/logoff button is clicked, it will briefly freeze (maybe for only a second) and then do nothing. Ive tried shutting down manually via the command line using shutdown /p but all to no avail, it just defaults back to flashing cursor in the command prompt. There doesnt seem to be any mention of a similar problem on google so i was wondering if anyone else had any ideas.
Thanks
oh and its runnning windows 7 starter.

A: Most likely there is some process responding badly to the shutdown process (canceling the shutdown when notified about it).
The best you can do is to kill process manually from the Process Explorer one by one and trying logoff after each kill. Once the logoff will succeed, you know the last process you have killed before was the one causing the problem.

A: Does running the command Work?
shutdown -s -f

If so, it's a process stopping it from shutting down rather than a driver. The "F" switch forces Windows to drop everything and shutdown, usually.


text:
Q: What are the usages of a generic method in C# without using type argument() as input parameters or return value? What are the usages of a generic method in C# without using type argument as input parameters or return value?
private void method1<T>()

I have just explored in ASP.NET Core code and saw they have used this kind of generic method in a lot of places.
For example in UseMiddleware in UseMiddlewareExtensions.
public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app,
    params object[] args)
{
    return app.UseMiddleware(typeof(TMiddleware), args);
}

Is it a common pattern or I am wrong?

A: It's just a way of passing in a Type, instead of adding an extra Type parameter.  It's exactly the same as:
public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app,
    params object[] args,
    Type middlewhereType)
{
    return app.UseMiddleware(middlewhereType, args);
}

It's just a matter of stylistic choice, which one to use.


text:
Q: Get png with transparency from iPhone using File API Im using a input (type="file") with fileAPI (fileReader / dataURL) to get png (with transparency) images and then show up into a website. This work great in desktops. I just click the button, browse an select my image an then it will show up on the site.
In iOS iPhone (not tested on other ios devices) when you click the button, the browser show up options for take a photo or choose a image from camera roll. I choose my image on cam roll an it show up with a white background; but this is a png 24 with transparency, and that background should not be there (like in the desktop).
I found that its probably a problem with camera roll removing the transparency of the image. So Im wondering if someone has ever got a png with transparency from the iphone using the html 5 file api, and if so, how to do it?
Note: I tried using dropbox (an others apps that alow to copy images to cam roll) hoping that the png images dont loose their transparency but somehow all the images ended with the annoying background when are imported in the site.
This is the code im currently using for get the images via File API:
function init() {
    var bHaveFileAPI = (window.File && window.FileReader);
    document.getElementById("inputid").addEventListener("change", onFileChanged);
}
function onFileChanged(theEvt) {
    var thefile = theEvt.target.files[0];
    var reader = new FileReader();

    reader.onload = function (evt) {
        var resultdata = evt.target.result;
        $('<img>')
            .attr('title', thefile.name)
            .attr('src', evt.target.result)
            .prependTo('#imgin');
    }
    reader.readAsDataURL(thefile);
}
window.addEventListener("load", init);


text:
Q: Using Pagination with a DataTable object in MVC 3 I am receiving a DataTable object from the controller and using that to display a table in the view with the following code:
@model System.Data.DataTable

    USERNAME
    ROLE
    ACTIVE

@foreach(DataRow row in Model.Rows)
{

        @foreach (DataColumn column in Model.Columns)
        {
            @row[column]
        }

        @Html.ActionLink("Edit", "Edit", new { id = row[0] })
        @Html.ActionLink("Delete", "Delete",new{id=row[0]})

}

I'd like to add pagination so that the user doesn't have to scroll down for a long period when the table becomes populated with a lot of data. This is for a basic learning exercise that I'm doing where I've hard-coded all of the database SQL calls in the relevant controller action methods. I'm not using an ORM like NHibernate so ideally I'm looking for a solution that just uses the DataTable object on the server side.
Here's the code from the controller (with the DB specifics removed):
public ActionResult Index()
    {
        string oradb = "Data Source = XXXXXXXXXXXXXXXXXXX";

        OracleConnection conn = new OracleConnection(oradb);

        conn.Open();

        string sql = " SELECT USER_ROLE_ID, USERNAME, ROLE, ACTIVE_IND FROM LD_USER_ROLE";

        OracleDataAdapter adapter = new OracleDataAdapter(sql, conn);
        DataTable dt = new DataTable();
        adapter.Fill(dt);

        conn.Close();

        return View(dt);
    }

A: As already pointed out, paging is usually done server side, that way you get the benefit of limiting what comes over the wire as well as limiting what the user has to take in.  However, if you only care about the user experience and not so much about the page bandwidth, then you can do client-side paging using a JavaScript library such as knockout.  Look at this knockout paging link for information on how to accomplish client-side paging.

A: In order to solve this I had to rewrite the controller method so that it converted the DataTable into a List of User objects and then I passed this list through to the view. By doing this I was then able to use the WebGrid object which enables easy pagination. The controller code also uses a dataAccess object to encapsulate some of the database info and calls.
Controller code:
public ActionResult Index()
    {
        UserRoleDAL udl = new UserRoleDAL();
        DataSet ds = udl.GetData(" SELECT USER_ROLE_ID, USERNAME, ROLE, ACTIVE_IND FROM LD_USER_ROLE");

        var ZUsers = new List<ZUserRoleModel>();

        if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                var dr = ds.Tables[0].Rows[i];

                var ZUser = new ZUserRoleModel()
                {
                    UserRoleId = Convert.ToInt64(dr["USER_ROLE_ID"]),
                    UserName = dr["USERNAME"].ToString(),
                    Role = dr["ROLE"].ToString(),
                    ActiveInd = ActiveBool
                };
                ZUsers.Add(ZUser);
            }
        }

        return View(ZUsers);
    }

View Code:
@model IEnumerable<CIMsWebApp.Models.ZUserRoleModel>

@{  var grid = new WebGrid(Model, canSort: false, canPage: true, rowsPerPage:25); }

@grid.GetHtml(
                tableStyle: "dataGrid",
                headerStyle: "header",
                alternatingRowStyle: "evenRow",
                columns: grid.Columns
  (
          grid.Column(header: "UserName", columnName: "UserName"),
          grid.Column(header: "Role ", columnName: "Role"),
          grid.Column(header: "Active", columnName: "ActiveInd"),
          grid.Column(header: "Edit", format: @<text>@Html.ActionLink("Edit", "Edit",  new { id = @item.UserRoleId })</text>),
          grid.Column(header: "Delete", format: @<text>@Html.ActionLink("Delete", "Delete", new { id = @item.UserRoleId })</text>)
  ))


text:
Q: Android "Zombie" BLE Advertising Task In my App, i have a Service including a Thread that ciclycally starts and stops BLE Advertising:
public class BeaconSearchService extends Service {

     private void startAdvertisingThread() {
         (advertisingThread = new Thread("Advertising Thread") {
             @Override
             public void run() {
                //Ensure that advertising is off
                try {
                   BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
                } catch (Exception e) {
                }
                while(!isInterrputed()) {
                   AdvertiseSettings advertiseSettings = new AdvertiseSettings.Builder()
                      .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
                      .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
                      .setConnectable(true)
                      .build();
                   BeaconSearchService.this.advertiseData.getServiceUuids().clear();
                   BeaconSearchService.this.advertiseData.getServiceUuids().add(BeaconSearchService.this.getUuid());
                   long uptime = 5000;
                   long downTime = 7000;
                   //START ADVERTISING
                   try {
                       BeaconSearchService.this.bluetoothLeAdvertiser.startAdvertising(advertiseSettings, BeaconSearchService.this.advertiseData, BeaconSearchService.this.advertiseCallback);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, e.getMessage(), e);
                    }
                    //SLEEP FOR 5 SEC
                    try {
                        sleep(upTime);
                    } catch (InterruptedException e) {
                        interrupt();
                        break;
                    }
                    //AFTER WAKE FROM SLEEP, STOP ADVERTISING
                    try {
                       BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
                    } catch (Exception e) {
                        Log.e(LOG_TAG, e.getMessage(), e);
                    }
                    //SLEEP FOR 7 SEC
                    try {
                        sleep(downTime);
                    } catch (InterruptedException e) {
                        interrupt();
                        break;
                    }
                    //RESTART THE CIRCLE IF NOT INTERRUPTED
             }
             //Ensure stop advertising while exiting
             try {
               BeaconSearchService.this.bluetoothLeAdvertiser.stopAdvertising(BeaconSearchService.this.advertiseCallback);
            } catch (Exception e) {
            }
         }).start();
     }

     @Override
     public void onDestroy() {
         try {
            advertisingThread.interrupt();
         } catch(Exception e) {
         }
     }
}

The problem is that when the Advertising is ON and Service and Thread are closed WITHOUT calling the onDestroy() method (e.g. App Crash, App process killed by the Local Android ROM Custom Behavior or while developing with Android Studio, App restart after new version download from Playstore etc), the Android system keeps the BLE Advertising ON. So when I reopen the App and sniff the BLE Packets I see TWO or More Advertising "sessions" of my App. The problem is solved when I reboot the phone and "orphan" Advertisig sessions disappear.
Is there any way to kill all the "zombie" Advertising sessions without forcing the user to reboot his phone?


text:
Q: Why some folders have the .DS_Store but some doesn't?  Local storage
In some of my folder, I found something quite interesting:
Some folders have the `.DS_Store` but some does not

Network storage
.DS_Store files are not on the network store. Any reason?
Thanks.

A: Locally stored .DS_Store files
In brief
A common reason for presence of .DS_Store:

*

*in Finder, a view is preferred.

Technical details
An answer to Why are dot underscore ._ files created, and how can I avoid them?:

*

*Purposes of .DS_Store and ._ files


text:
Q: push_back whole array wchar_t[n] to vector efficiently Why I use vector<wchar_t> instead of vector<array<wchar_t, n> >, if you are interested:

I want to store a lot of wchar_t arrays with different sizes together
  so that I can write it all to a file later after some encrypt/compress process.
I don't know how many arrays are there before I start, so I chose to use vector.
But these arrays are not the same size and I want them to be stored next to each
  other, so I can't use something like vector<array<wchar_t, n> >.

The only way I can think of doing this is push_back every wchar_t in every array one by one, and I think it is not efficient, because copy a string by yourself is always slower than strcpy, and every time I push_back it will check about capacity which is unnecessary in this case.
Is there any better solution?
I was hoping something like push_back(array_address, n).

A: Considering a container src, and your vector of wchar_tuse the insert method :
std::vector<wchar_t> dst;
dst.insert( end(dst), begin(src), end(src));

But there is no strong guarantee that it will optimize to a plain memcpy in case of a POD type or even a native type.

A: As I understand you need a vector of vectors of wchar_ts, but with the condition that vectors of wchar_ts are stored contiguously in base vector. Something like:
vector<vector<wchar_t>> v = {"string""value""list"};

The question is you need this for performance (means that that you can access each string separately, but they are in same space) or just need a contiguous array of strings to process it later?
If is the first then you need to make your own container that have these properties, if is the second then just append sequences to the vector, but if you want to use the memxxx functions then you may try this:
v.resize(v.size() + arr_sz);
std::copy_n(std::begin(sz), arr_sz, v.end() - arr_sz);

that is because (at least in VC++ 2013) copy_n uses memxxx on scalar types values:
template<class _InIt,
    class _Diff,
    class _OutIt> inline
    _OutIt _Copy_n(_InIt _First, _Diff _Count,
        _OutIt _Dest, _Scalar_ptr_iterator_tag)
    {   // copy [_First, _First + _Count) to [_Dest, ...), pointers to scalars
    _CSTD memmove(&*_Dest, &*_First,
        _Count * sizeof (*_First));
    return (_Dest + _Count);
    }


text:
Q: Unwanted xmlns="" in _di_IXMLNode I'm creating a xml-file for display in Excel using _di_IXMLDocument. But for some tags I get an unwanted extra (empty) xmlns attribute witch makes the file unreadable for Excel...
This is what i do:
...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("ss:Name",Now().DateString());
...

and this is what comes out:
<Worksheet xmlns="" ss:Name="2008-12-11">

Where does xmlns come from? How do I get rid of it?
EDIT:
Some more info: If I try to add a xmlns attribute to Worksheet myself, like this:
...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("xlmns","Foo");
worksheet->SetAttribute("ss:Name",Now().DateString());
...

Then the child nodes of "Worksheet" all get the empty xmlns attributes instead!
<Worksheet xmlns="Foo" ss:Name="2008-12-11">
  <Table xmlns="">

A: xmlns stands for xml name space, if an attribute does not receive an explicit name space, it possesses none.
http://www.w3.org/TR/REC-xml-names/

A: Ok I had a look at this question. The trick was to create the child nodes and telling the what namespace they belong to, and then not to output it...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet","workbooks-namespace",false);
worksheet->SetAttribute("ss:Name",Now().DateString());

this produces the desired output:
<Worksheet ss:Name="2008-12-11">


text:
Q: Icon arrow positions in collapsing tables - Twitter Bootstrap I have an issue with the font-icons and collapsing tabs in Twitter Bootstrap.
My goal is to visualize the icon arrow down as default and not up and i dont want to see the first collapsing tab open as default.
Then when i click over the icon arrow down the icon has to toggle swtitch.
I think i am really close to it, look the example.
http://jsfiddle.net/2D3V5/1/

A: So getting the accordion to load with all the tabs closed can be achieved by:
$('.collapse').collapse("hide");

Then you just need to change the class of the icons:
<i class="icon-arrow-down"></i>

Then you should have the arrows point down as default and up when the tab is opened.
There seems to be something weird going on in the JS fiddle with the collapse, sometimes when you open and close tabs the text is not hiding properly, I tried this on a normal page and it seems to work okay.


text:
Q: SQL Join to the latest record I want to join tables in such a way that it fetches only latest record from one of the tables:
The following are my data
Table_One:
+----+------+
| ID | Name |
+----+------+
|  1 | John |
|  2 | Tom  |
|  3 | Anna |
+----+------+

Table_two:
+----+----------+-----------+
| ID | Visit ID |   Date    |
+----+----------+-----------+
|  1 |     2513 | 5/5/2001  |
|  1 |    84654 | 10/5/2012 |
|  1 |      454 | 4/20/2018 |
|  2 |      754 | 4/5/1999  |
|  2 |      654 | 8/8/2010  |
|  2 |      624 | 4/9/1982  |
|  3 |     7546 | 7/3/1997  |
|  3 |   246574 | 6/4/2015  |
|  3 |    15487 | 3/4/2017  |
+----+----------+-----------+

Results needed after Join:
+----+------+----------+-----------+
| ID | Name | Visit ID |   Date    |
+----+------+----------+-----------+
|  1 | John |      454 | 4/20/2018 |
|  2 | Tom  |      654 | 8/8/2010  |
|  3 | Anna |   246574 | 6/4/2015  |
+----+------+----------+-----------+

A: Different database engines have varying ways to get the top row from table 2 per group (you can google for "SQL windowing functions" and your product).  Since you don't state what engine you're using it's impossible to give the most appropriate or most performant solution.
The following method should work in most or all SQL engines but will not be especially performant over a large data set (it will benefit from a composite index Table2(ID, Date)).  The details of how you specify the aliases for the tables may differ a bit among engines but you can use this as a guide.  A windowing function solution will probably be more efficient.
 SELECT ID, Name, VisitID, Date FROM Table1 T1 INNER JOIN Table2 T2 +
   ON T1.ID = T2.ID
   WHERE NOT EXISTS (SELECT * FROM Table2 T2B WHERE T2B.ID = T1.ID AND T2B.Date > T2.Date)

A: I suspect you have SQL Server if so, then you can use APPLY:
select o.*, tt.*
from Table_One o
cross apply ( select top 1 t.VisitDate, t.Date
              from table_two t
              where t.id = o.id
              order by t.date desc
            ) tt;

A: You can filter out "latest visit" using
SELECT ID,MAX(DATE) FROM TABLE_TWO GROUP BY ID;
You then join that to TABLE_ONE (... ON .ID = .ID) to pick up the Name column and then join that again to TABLE_TWO (... ON ID=ID AND DATE=DATE) if you need to pick up the VISIT_ID as well.
Specific DBMS's might have proprietary/idiosyncratic extensions typically serving the purpose of allowing the optimizer do a better job (e.g. allowing the optimizer to understand that the "joining back to TABLE_TWO can be eliminated).  Thinking here of SELECT TOP 1 ... and the like.

A: SELECT ID,Name,Visit_ID,Date
FROM
    (SELECT *, ROW_NUMBER() OVER(PARTITION BY ID Date DESC) as seq
    FROM Table2 LEFT OUTER JOIN
         Table1 ON Table2.ID = Table1.ID) as mainTable
WHERE seq = 1

A: I'm not a 100% sure if this is correct since the Visit ID might just throw every record right back at you. However you can find some great documentation here: https://www.w3resource.com/sql/aggregate-functions/max-date.php
select t1.ID,t1.Name,t2.visit_ID, Max(t2.Date) from Table_Two t2
inner join Table_One t1
on(t2.ID=t1.ID)
group by t1.ID,t1.Name,t2.visit_ID

something like this should work though, i think that this is also the same as @Erwin Smout proposes
select a.ID, t1.Name, a.date,t2.Visit_ID (
select ID, max(date)'date' from Table_Two
group by ID) a
inner join Table_One t1
    on( a.ID=t1.ID)
inner join Table_Two t2
    on(a.ID=t2.ID and a.Date=t2.Date)

A: This is the answer to your question
SELECT t1.ID, t1.Name, t2.visit_id, t2.Date FROM table1 t1 INNER JOIN table2 t2 ON t1.ID = t2.ID WHERE NOT EXISTS (SELECT * FROM table2 t2b WHERE t2b.ID = t1.ID AND t2b.Date > t2.Date)


text:
Q: query base object based on a non related entity list using entity framework I have the following model:
A workflowconfiguration has a Brand and also has a type.
A Workflowconfiguration has a collection of Approvers.
The Approvers entity has property Status and username.
In another part of the application, we have an entity called RequestBase
This entity has a string property called CurrentStatus.
I need to make a query with linq or EF Lambda expressions that returns me ALL requests which status matches the username on the approvers entity.
I know its a little bit complicated, or really much complicated, lol.
These are my entities(simplified)
public class RequestBase
    {
        public int RequestBaseId { get; set; }
        public string CurrentStatus { get; set; }
      }

 public class WorkflowConfiguration
    {
        public int WorkflowConfigurationId { get; set; }
        public WorkflowType WorkflowType { get; set; }
        public Brand Brand { get; set; }
        public virtual ICollection<Approver> Approvers { get; set; }

    }

public class Approver
    {
        public Approver()
        {

        }

        public Approver(string approverUserName)
        {
            Name = approverUserName;
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string StepName { get; set; }  -----||||>>>>>> Must match status?
        public int Order { get; set; }
    }

and my query?
obviously it does not even compile
return _context.RequestBases.
                        .Where(a => a.CurrentStatus.Any(workflowconfiguration.Select(b=>b.Approvers.Select(c => c.StepName))));

A: _context.RequestBases
.Where(rb => _context.Workflowconfiguration
    .Any(wc => wc.Approvers
        .Any(a => a.StepName == rb.CurrentStatus)));


text:
Q: while executing asking for two input values #include <stdio.h>

int main()
{
   int minutes=0;
   double days=0.0;
   double  years=0.0;
   printf("enter minutes ");
   scanf("%d ",&minutes);
   days= (minutes/60)/24;
   years=days/365;
   printf("no of minutes %d equals no of days are %f , no of years are %f \n",minutes,days,years);

   return 0;
}

During output we have to enter a value two times for program to work, while I used scanf only one time.
Also the value of days is being truncated to integer even though I defined it as double.

A: Space in a scanf format string matches zero or more white-space characters. But to know where the white-spaces ends the function must be able to read something that is not a white-space character, hence the second input.
Simple solution: Don't use trailing spaces in your scanf format strings:
scanf("%d",&minutes);
//       ^
// Note no space here

A:
Also value of days is being truncated to integer

Here
  days = (minutes / 60) / 24;

the right side of the assignment is calculated using integer arithmetic, as only integers are involved. Integer arithmetic does not take care of any fractions but just drops them.
For example 1/2 results in 0, or 4/3 results as 1.
So to fix your issue specify the number-literals as floating points like so:
  days = (minutes / 60.) / 24.;

or (more common but in fact the same):
  days = (minutes / 60.0) / 24.0;

or just cast:
  days = ((double) minutes / (double) 60) / (double) 24;

The latter can be simplified to be:
  days = ((double) minutes / 60) / 24;

The latter works, as calculation is done from inner to outer and the arithmetic applied always follows the "Usual Arithmetic Conversions", which in your case is division of double by integer results in a double.


text:
Q: How to improve monitor saturation? Recently I have installed Ubuntu on my laptop and noticed that colors are very dull and washed out and the color calibration option is grayed out.
-GPU: Intel UHD 620
-Ubuntu 22.04 LTS
-monitor: built in laptop display

A: Use VibrantLinux - great simple software to boost color saturation
https://flathub.org/apps/details/io.github.libvibrant.vibrantLinux


text:
Q: NaN countdown timer javascript I have created a javascript countdown for a wordpress custom plugin. I've read this article and this is the first time I try to make something similar. After I've ended writing the code I was testing it and initially it was working fine. Now if I try to log the values of the hours minutes days and seconds in console I get a NaN message. I don't know what's wrong, can anyone help me?
<?php if( get_option('show-countdown') ): ?>

                <?php endif; ?>

A: The issue was that you were passing two arguments to initClock, but the method signature only accepted one (endTime). By removing the first argument, which appeared to be an unused CSS selector string, the problem is resolved:

(function($) {
  $(document).ready(function() {

    var date = '2030-01-01';
    console.log(date);

    function remainingTime(date) {
      var countdown = Date.parse(date) - Date.parse(new Date());
      var seconds = Math.floor((countdown / 1000) % 60);
      var minutes = Math.floor((countdown / 1000 / 60) % 60);
      var hours = Math.floor((countdown / (1000 * 60 * 60)) % 24);
      var days = Math.floor(countdown / (1000 * 60 * 60 * 24));
      return {
        'total': countdown,
        'd': days,
        'h': hours,
        'm': minutes,
        's': seconds
      };
    }

    console.log(remainingTime(date));

    function initClock(endtime) {
      var timeinterval = setInterval(function() {
        var t = remainingTime(endtime);

        $('.days').html(t.d);
        $('.hours').html(t.h);
        $('.minutes').html(t.m);
        $('.seconds').html(t.s);
      }, 1000);
    }

    initClock(date);
  });
}(jQuery));

Note: since this was primarily about the JavaScript, I removed the PHP conditional and hardcoded a date value in place of the get_option call.


text:
Q: why doesn't opengl show my fire particles Here is main.cpp:
class Vector3
{
private:
   float x,y,z;
public:
    Vector3(float thex=0,float they=0,float thez=0)
        :x(thex),y(they),z(thez)
    {
    }
    float X()const
    {
        return x;
    }
    float Y()const
    {
        return y;
    }
    float Z()const
    {
        return z;
    }
    Vector3 operator -(const Vector3 &other)const
    {
        return Vector3(x-other.x,y-other.y,z-other.z);
    }
    static Vector3 crossproduct(const Vector3 &v,const Vector3 &u)
    {
        Vector3 resVector;
        resVector.x = u.y*v.z - u.z*v.y;
        resVector.y = u.z*v.x - u.x*v.z;
        resVector.z = u.x*v.y - u.y*v.x;

        return resVector;
    }
    Vector3 operator *(const float &scale)const
    {
        return Vector3(x*scale,y*scale,z*scale);
    }
    Vector3 operator /(const float &scale)const
    {
        return Vector3(x/scale,y/scale,z/scale);
    }
    Vector3 &operator +=(const Vector3& other)
    {
        x+=other.x;
        y+=other.y;
        z+=other.z;
        return *this;
    }
    const float *toArray()const
    {
        float *a=new float[3];
        a[0]=x;
        a[1]=y;
        a[2]=z;
        return a;
    }
};
struct Force
{
private :
    float strength;
    Vector3 orentation;
public :
    Force(const Vector3 &v,const float &s)
        :strength(s),orentation(v)
    {
    }
    Force(const Force &f)
        :strength(f.strength),orentation(f.orentation)
    {

    }
    float getStrength() const
    {
        return strength;
    }
    Vector3 getOrentation() const
    {
        return orentation;
    }
};
class Camera
{
private:
    Vector3 Position;
    Vector3 View;
    Vector3 Up;
    Vector3 lineofsight;
public:
    Camera(const Vector3 &pos, const float &lookatx, const float &lookaty):
       Position(pos), View(Vector3(lookatx,lookaty,pos.Z()-1))
       ,Up(Vector3::crossproduct(lineofsight,Vector3(1,0,0))),lineofsight(View-pos)
    {

    }
    void LookAt()
    {
        gluLookAt(Position.X(),Position.Y(),Position.Z(),View.X(),View.Y(),View.Z(),Up.X(),Up.Y(),Up.Z());
    }
};
class Particle
{
  public :
    Vector3 velocity,position,color;
    const float mass;
    float *deltatime;
    Particle(const Vector3 &pos,const Vector3 &col,const float &m,float *dt)
        :velocity(Vector3()),position(pos),color(col),mass(m),deltatime(dt)
    {

    }

    void applyforce(const Force &f)
    {
        Vector3 force=f.getOrentation()*f.getStrength();
        Vector3 accleration=force/mass;
        velocity+=accleration*(*deltatime);
        proceedintime();
    }
    void proceedintime()
    {
        position+=velocity*(*deltatime);
    }
    virtual void draw()const=0;
    virtual ~Particle()
    {

    }
};

class Emmiter;

class ParticleSystem
{
    friend class Emmiter;
private :
    deque<Particle*> particles;
    float elapsedtime;
    float *deltatime;
    float LifeOfParticles;
    unsigned short particlesperframe;
    void deleteparticles()
    {
        float div=fmod(elapsedtime,LifeOfParticles);
        if(div==0)
        {
            deque<Particle*>::const_iterator begin=particles.begin();
            deque<Particle*>::const_iterator end=particles.end();
            for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
                delete (*it);
            particles.clear();
        }
    }

public :
    ParticleSystem(const float &life,float *dt)
        :elapsedtime(0),deltatime(dt),LifeOfParticles(life)
    {

    }
    void drawparticl1es()
    {
        deque<Particle*>::const_iterator begin=particles.begin();
        deque<Particle*>::const_iterator end=particles.end();

        for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
        {
            (*it)->proceedintime();
            (*it)->draw();
        }
        elapsedtime+=(*deltatime);
        deleteparticles();
    }
};

class Emmiter
{
public :
    unsigned short ParticlesPerSecond;
    Vector3 position;
    ParticleSystem *ps;
    unsigned char count;
    float deltatime;
    Particle *(*emitfunc)(const Emmiter &em);
    Emmiter(const unsigned short &parpersec,const Vector3 &pos,ParticleSystem *p,const unsigned char &c)
         :ParticlesPerSecond(parpersec),position(pos),ps(p),count(c)
    {

    }
    unsigned short particlesperframe()const
    {
        return ParticlesPerSecond*deltatime;
    }
    void emitparticles()const
    {
        unsigned short numpars=deltatime*ParticlesPerSecond;
        for(unsigned char i=0;i<count;i++)
        {
            for(unsigned short j=0;j<numpars;j++)
                ps[i].particles.push_back(emitfunc(*this));
        }
    }
};
class BallParticle:public Particle
{
public :
    float radius;
    BallParticle(const Vector3 &pos,const Vector3 &col,const float &rad,const float &m,float *dt)
        :Particle(pos,col,m,dt),radius(rad)
    {

    }
    void draw() const
    {
        glPushMatrix();
        glColor3fv(color.toArray());
        glTranslatef(position.X(), position.Y(), position.Z());
        glutSolidSphere(radius, radius * 20, radius * 20);
        glPopMatrix();
    }
};
using namespace std;

float deltatime;
float oldtime;
float newtime;

ParticleSystem pars(2,&deltatime);
Emmiter emmiter(200,Vector3(0,0,8),&pars,1);

Camera camera(Vector3(0,0,3),0,0);
float myrand(const float &min,const float &max)
{
    return min+(max-min)*(float(rand())/float(RAND_MAX));
}

Particle *emitfunction(const Emmiter &em)
{
    float x=em.position.X(),y=em.position.Y(),z=em.position.Z();
    BallParticle *b=new BallParticle(Vector3(myrand(x-5,x+5),y,myrand(z-5,z+5)),Vector3(myrand(0,1),myrand(0,1),myrand(0,1)),4,0.02,&deltatime);
    b->velocity=Vector3(0,4,0);
    return b;
}
void resize(int width, int height)
{
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,(4/3),2,100);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    camera.LookAt();
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    newtime=glutGet(GLUT_ELAPSED_TIME)/1000;
    deltatime=newtime-oldtime;
    oldtime=newtime;
    emmiter.deltatime=deltatime;
    emmiter.emitparticles();
    pars.drawparticl1es();
    glutSwapBuffers();
}
void idle()
{
    glutPostRedisplay();
}
void init()
{
    glClearColor(1, 1, 1, 1);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
}
int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(300,200);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Fire");
    glutReshapeFunc(resize);
    glutDisplayFunc(display);
    glutIdleFunc(idle);
    init();
    oldtime=glutGet(GLUT_ELAPSED_TIME)/1000;
    emmiter.emitfunc=&emitfunction;
    glutMainLoop();
    return EXIT_SUCCESS;
}

I'm trying to build a simple fire particle system in opengl with freeglut, I have Nvidia 9400GT and working on linux mint 17.1 64bit.
I tried apitrace but it didn't show anything, I debugged my program, it seems the emmiter works because the particle system get filled, but yet it doesn't show anything.
Most of the time it's camera but I don't anything wrong with it. So what's the problem?

A: Your camera was off in $DEITY-knows-where and your glutSolidSphere()s were wayyyy too big.  And overly-subdivided.
Don't re-invent a vec3 class, use GLM, Eigen, or something similar.
You have several places where you're dividing an integer by an integer and hoping for a float.  Coerce the divisor to float via a f suffix.
All together:
#include <GL/glut.h>

// http://glm.g-truc.net/
#include <glm/glm.hpp>

#include <deque>
using namespace std;

typedef glm::vec3 Vector3;

struct Force
{
private :
    float strength;
    Vector3 orentation;
public :
    Force(const Vector3 &v,const float &s)
        :strength(s),orentation(v)
    {
    }
    Force(const Force &f)
        :strength(f.strength),orentation(f.orentation)
    {

    }
    float getStrength() const
    {
        return strength;
    }
    Vector3 getOrentation() const
    {
        return orentation;
    }
};

class Particle
{
public :
    Vector3 velocity,position,color;
    const float mass;
    float *deltatime;
    Particle(const Vector3 &pos,const Vector3 &col,const float &m,float *dt)
        :velocity(Vector3()),position(pos),color(col),mass(m),deltatime(dt)
    {

    }

    void applyforce(const Force &f)
    {
        Vector3 force=f.getOrentation()*f.getStrength();
        Vector3 accleration=force/mass;
        velocity+=accleration*(*deltatime);
        proceedintime();
    }
    void proceedintime()
    {
        position+=velocity*(*deltatime);
    }
    virtual void draw()const=0;
    virtual ~Particle()
    {

    }
};

class Emmiter;

class ParticleSystem
{
    friend class Emmiter;
private :
    deque<Particle*> particles;
    float elapsedtime;
    float *deltatime;
    float LifeOfParticles;
    unsigned short particlesperframe;
    void deleteparticles()
    {
        float div=fmod(elapsedtime,LifeOfParticles);
        if(div==0)
        {
            deque<Particle*>::const_iterator begin=particles.begin();
            deque<Particle*>::const_iterator end=particles.end();
            for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
                delete (*it);
            particles.clear();
        }
    }

public :
    ParticleSystem(const float &life,float *dt)
        :elapsedtime(0),deltatime(dt),LifeOfParticles(life)
    {

    }
    void drawparticl1es()
    {
        deque<Particle*>::const_iterator begin=particles.begin();
        deque<Particle*>::const_iterator end=particles.end();

        for(deque<Particle*>::const_iterator it=begin;it!=end;it++)
        {
            (*it)->proceedintime();
            (*it)->draw();
        }
        elapsedtime+=(*deltatime);
        deleteparticles();
    }
};

class Emmiter
{
public :
    unsigned short ParticlesPerSecond;
    Vector3 position;
    ParticleSystem *ps;
    unsigned char count;
    float deltatime;
    Particle *(*emitfunc)(const Emmiter &em);
    Emmiter(const unsigned short &parpersec,const Vector3 &pos,ParticleSystem *p,const unsigned char &c)
        :ParticlesPerSecond(parpersec),position(pos),ps(p),count(c)
    {

    }
    unsigned short particlesperframe()const
    {
        return ParticlesPerSecond*deltatime;
    }
    void emitparticles()const
    {
        unsigned short numpars=deltatime*ParticlesPerSecond;
        for(unsigned char i=0;i<count;i++)
        {
            for(unsigned short j=0;j<numpars;j++)
                ps[i].particles.push_back(emitfunc(*this));
        }
    }
};

class BallParticle:public Particle
{
public :
    float radius;
    BallParticle(const Vector3 &pos,const Vector3 &col,const float &rad,const float &m,float *dt)
        :Particle(pos,col,m,dt),radius(rad)
    {
    }

    void draw() const
    {
        glPushMatrix();
        glColor3fv( (GLfloat*)&color );
        glTranslatef(position.x, position.y, position.z);
        glutSolidSphere(radius, 10, 10);
        glPopMatrix();
    }
};

float deltatime;
float oldtime;
float newtime;

ParticleSystem pars(2,&deltatime);
Emmiter emmiter(200,Vector3(0,0,8),&pars,1);

float myrand(const float &min,const float &max)
{
    return min+(max-min)*(float(rand())/float(RAND_MAX));
}

Particle *emitfunction(const Emmiter &em)
{
    float x=em.position.x,y=em.position.y,z=em.position.z;
    BallParticle *b=new BallParticle
        (
        Vector3(myrand(x-5,x+5),y,myrand(z-5,z+5)),
        Vector3(myrand(0,1),myrand(0,1),myrand(0,1)),
        0.2,
        0.02,
        &deltatime
        );
    b->velocity=Vector3(0,4,0);
    return b;
}

void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,(4/3.0f),2,100);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt( 20, 20, 20, 0, 0, 0, 0, 0, 1 );

    newtime=glutGet(GLUT_ELAPSED_TIME)/1000.0f;
    deltatime=newtime-oldtime;
    oldtime=newtime;
    emmiter.deltatime=deltatime;
    emmiter.emitparticles();
    pars.drawparticl1es();

    glutSwapBuffers();
}

void timer( int value )
{
    glutTimerFunc( 16, timer, 0 );
    glutPostRedisplay();
}

void init()
{
    glClearColor(1, 1, 1, 1);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
}

int main(int argc, char *argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(300,200);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
    glutCreateWindow("Fire");
    glutDisplayFunc(display);
    glutTimerFunc(0, timer, 0);
    init();
    oldtime=glutGet(GLUT_ELAPSED_TIME)/1000.0f;
    emmiter.emitfunc=&emitfunction;
    glutMainLoop();
    return EXIT_SUCCESS;
}


text:
Q: is there any way to detect bots (like google) with JS? i want to create additional page visit analytics (for a/b test) with js. but i need to exclude google bots.
is there any way to exlude bots like google bot in js without any captcha or form validation ?

A: How about the noindex-meta-tag?
In javascript you can check the navigator.userAgent if it matches with any of those.
Edit: I realize this might not be the answer you were looking for. Is that google analytics? How about goint to Admin > View > View Settings > Bot Filtering
"Exclude all hits from known bots and spiders".


text:
Q: I need a button NOT to disapear I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears.  I'm new to javascript so can I please get some help?

<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>

A: When you write document.write() the screen refreshes, so I guess you could do something like this:

<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>

A: Slightly optimized version of otrebla's code, see it in action:

function slots() {
  var slot1 = Math.floor(Math.random() * 5);
  var value = document.getElementById('value');
  switch (slot1) {
    case 0:
      value.innerHTML = "\u2663";
      break;
    case 1:
      value.innerHTML = "\u2665";
      break;
    case 2:
      value.innerHTML = "\u2666";
      break;
    case 3:
      value.innerHTML = "\u2660";
      break;
    case 4:
      value.innerHTML = "7";
      break;
  }
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>


text:
Q: How to work with time interval in postgreSQL I have a postgreSQL query that returns 'Late' when the given condition is met, currently, When i run below query I'm getting an error
SELECT
CASE WHEN CAST(so.scheduled_delivery_time AS date) < CURRENT_DATE OR CAST(so.scheduled_delivery_time AS date) = CURRENT_DATE AND DATETIME(so.scheduled_delivery_time) < DATETIME_SUB(datetime(current_datetime()),  INTERVAL '3' HOUR) THEN 'Late'
END AS status
FROM
table1

Error

ERROR: function datetime(timestamp without time zone) does not exist Hint: No function matches the given name and argument types.

What I'm I missing?

A: Hey there — the simplest answer is that there is no function named DATETIME. Also it looks like your values are already timestamps, so you can probably just do this:
so.scheduled_delivery_time < current_datetime() - INTERVAL '3' HOUR

A: A good starting point to find the available functions, is the fine manual. CURRENT_TIMESTAMP will give you the current timestamp and you can use it like this:
SELECT CURRENT_TIMESTAMP;


text:
Q: Excel Office.js add-in no longer loads correctly on Windows 10 I'm currently working on getting an Office.js add-in for Excel submitted to Microsoft. The add-in used to work well and still does on Mac OSX and office.com. However, it no longer works on Windows 10 (64 bit) with my desktop Excel 2016. My Excel project includes both customfunctions and task panes.
I have been using the yeoman generator to create my project and develop in Visual Studio Code. Up to last month I had no problem loading my add-in using either node.js to debug or through a manifest pointing to the location where the code is hosted. At some point (after the Nov Windows update?) it was no longer possible to run the yeoman generated projects on Windows 10. Not only does my project no longer load correctly but a cleanly generated yeoman project has the same issue. The client js in the taskpanes still runs but the customfunctions do not. I wonder if this is related somehow to system browser changes.
The only clue I have is that when debugging through node.js I see the following in the debug log
[14:42:07.011 UTC] Getting browser and debug protocol version via http://127.0.0.1:9229/json/version
[14:42:07.012 UTC] Discovering targets via http://127.0.0.1:9229/json/list
[14:42:09.014 UTC] HTTP GET failed: Error: connect ECONNREFUSED 127.0.0.1:9229
[14:42:09.014 UTC] There was an error connecting to http://127.0.0.1:9229/json/version : connect ECONNREFUSED 127.0.0.1:9229

I can't be sure if this is an indication of the problem or just a symptom that node.js is showing.
I would appreciate any advice on the problem. If others are still able to work with yeoman generated add-ins on recently updated Windows 10 that would be a good datapoint to know as well.
Thanks!

A: The Edge WebView requires a configuration change to allow access to localhost.
Open a command prompt as Administrator and run the following command:
CheckNetIsolation LoopbackExempt -a -n="microsoft.win32webviewhost_cw5n1h2txyewy"
Alternatively, you can run this command:
npx office-addin-dev-settings appcontainer edgewebview --loopback

A: Clear cache may help:

*

*Keep the node.js which serves your add-in running,

*Clear everything under %LOCALAPPDATA%\Microsoft\Office\16.0\Wef\,

*Pick your add-in from the dropdown list Excel->Insert->My Add-ins.

A: I don't know if this is the real solution but in addition to the WEF folder on the file system I found some registry keys under HKCU\Software\Microsoft\Office\16.0\WEF\Providers and I deleted any provider that I couldn't justify keeping. That combined with the Monthly Office update seems to have fixed the problem. Thanks everyone for your help but seems to be some kind of registry corruption problem.


text:
Q: path visibility from source to destination in googlemaps Path visibility from Source to Destination in Google Maps. The Source and Destination places must be retrieved from the backend and it should shown in the google map. the detailed description for my requirement is given in image. i have searched in youtube but it is showing that the source is constant and the destination varies by the movement of marker.

A: This code is use to redirect to the google map and give you a path between source and destination :
button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("http://maps.google.com/maps?saddr=" + doubleLatStart + "," + doubleLonStart + "&daddr=" + doubleLatEnd + "," + doubleLonEnd + "&mode=driving"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

here, doubleLatStart is latitude of your source location and doubleLonStart is longitude of your source location.
doubleLatEnd is latitude of destination location and doubleLonEnd is longitude of destination location.
Let me know if you have any further query.


text:
Q: BigQuery convert String to Date In my dataset, one column called timestamp was created with datatype as String.
It contains values like:
2018-05-30T12:56:27:487+0200
I want to construct a query where I can fetch all column from the dataset table based on the date in 'YYYY-MM-DD' format.
I want to use it in where clause with DATE Range between.
Can you guide?
Thank you.

A:
convert String to Date

Below example for BigQuery Standard SQL
#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2018-05-30T12:56:27.487+0200' ts UNION ALL
  SELECT '2018-05-30T01:56:27.487+0200'
)
SELECT ts AS ts_as_string,
  PARSE_TIMESTAMP('%FT%H:%M:%E3S%z', ts) ts_as_timestamp,
  DATE(PARSE_TIMESTAMP('%FT%H:%M:%E3S%z', ts)) ts_as_date
FROM `project.dataset.table`

with result
ts_as_string                    ts_as_timestamp                 ts_as_date
2018-05-30T12:56:27.487+0200    2018-05-30 10:56:27.487 UTC     2018-05-30
2018-05-30T01:56:27.487+0200    2018-05-29 23:56:27.487 UTC     2018-05-29

As you can see - first i am parsing timestamp out of the string - this is important part - this is where you can take timezone into account (see difference in dates in the result 2018-05-29 vs. 2018-05-29). Then you can get Date out of TIMESTAMP

I want to use it in where clause with DATE Range between.

So, now you can use below in your WHERE clause
WHERE DATE(PARSE_TIMESTAMP('%FT%H:%M:%E3S%z', ts)) BETWEEN date1 AND date2

Update

You can use below to avoid dealing with "wrong" format
PARSE_DATE('%F',  SUBSTR(ts, 1, 10))

In case if you need to account for timezone  - you can use below (which fix : to . before applying PARSE_TIMESTAMP)
DATE(PARSE_TIMESTAMP('%FT%H:%M:%E3S%z', FORMAT('%s.%s', SUBSTR(ts, 1, 19), SUBSTR(ts, 21, 8))))

A: If you want the date in the same timezone represented, then the simplest method is to use string operations and convert to a date:
select PARSE_DATE('%Y-%m-%d', SUBSTR('2018-05-30T12:56:27:487+0200', 1, 10))