text:
Q: Devise omniauth stopped working for some unknown reason I have Ruby on Rails application that uses devise and user model has omniauthable attribute, i.e. users can sign in via social network accounts (application allows google and linkedin).
Sign in via social networks worked until I try to setup email confirmation of registration.
Now any social registration attempt causes Invalid credentials error, altough config.omniauth rows and environment variables with credentials have not been change.
In production mode social registration still works, and I download old code from server (Development and production environments uses same credentials). But it not helped, and I still can't use socian networks for sign in my application in development mode. I thought browser cache is the reason of this bug, but in others browsers I saw same error message.
My devise.rb code:
Devise.setup do |config|

    config.omniauth :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
    config.omniauth :linkedin, ENV['LINKEDIN_KEY'], ENV['LINKEDIN_SECRET']

user.rb:
class User < ActiveRecord::Base
    devise :database_authenticatable,
        :registerable,
        :recoverable,
        :rememberable,
        :trackable,
        :validatable,
        :omniauthable,
        :omniauth_providers => [
            :google_oauth2,
            :linkedin
        ]

Does I understand correctly that credentials are social network application id and secret?
Where is my error?

A: Add the file config/api_keys.yml
defaults: &defaults
  linkedin:
    api_key: "KEY"
    api_secret: "SECRET"

  development:
    <<: *defaults

  production:
    linkedin:
      api_key: "KEY2"
      api_secret: "SECRET2"

Then in my devise.rb file I do:
API_KEYS = YAML::load_file("#{Rails.root}/config/api_keys.yml")[Rails.env]
config.omniauth :linkedin , API_KEYS['linkedin']['api_key'], API_KEYS['linkedin']['api_secret']

A: Probably you have removed your devise secret key in development.
Use rake secret to generate one.

A: Problem was in omniauth-oauth2 gem and most likely appeared after bundle install or bundle update command.
When I compared gems at development computer and production server, I found that omniauth-oauth2 gem has different versions. Then I rollback this gem version and application began working.
Thank for help!
Update: issue is already created at github


text:
Q: How to use std::less in a vector that contains classes How to use std::less in a vector that contains classes, all google results are with plain int examples.
When it comes to classes, for example:
class A{
   public:
      A( int value = 0 ):m_value(value){};
      int m_value;
};

How to do something like:
std::count_if( m_cells.begin(), m_cells.end(), std::less< int >() );
Less will receive an A, not an int. std::less< A >
Seems like less needs a functor operator()(), how to avoid this? I need to implement operator<( int a ) ? Make a bind? What else?
Code:
  1 #include <iostream>
  2 #include <vector>
  3 #include <algorithm>
  4
  5 using namespace std;
  6
  7 class A
  8 {
  9    public:
 10       A(int a = 0 ):m_value(a) {}
 11       bool operator!=( int a )
 12       {
 13          return m_value != a;
 14       }
 15
 16       bool operator<( A &a )
 17       {
 18          return m_value < a.m_value;
 19       }
 20
 21       int m_value;
 22 };
 23
 24
 25 int main(){
 26    std::vector< A > m_cells( 5 );
 27
 28    m_cells[2].m_value = 3;
 29    m_cells[3].m_value = 4;
 30    m_cells[4].m_value = 4;
 31    std::count_if( m_cells.begin(), m_cells.end(), std::less< A >() );
 32    return 0;
 33 }
 34

This results in:
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_algo.h:4437: error: no match for call to '(std::less<A>) (A&)'
/usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_function.h:229: note: candidates are: bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = A]

A: Implement an operator< for A, and then pass in std::less<A>, other options (for example you could implement a conversion operator to int - YUCKYUCKYUCKYUCK)
EDIT: To continue...
Like James says, std::less<> requires two arguments, if you are stuck on c++03 (and don't have boost), you can do something like the following:
std::count_if( m_cells.begin(), m_cells.end() ,std::bind1st(std::less<A>(), 3) )

Basically one of the arguments is bound to 3 - this the first argument (consider the left hand side), you can also bind to the second argument (right hand side - using std::bind2nd), depending on how you want the predicate to work.
This approach requires that you properly implement operator<, i.e.
bool operator<(A const& a) const
{
}

EDIT2: for c++11, you can try any of the following:
 std::cout << std::count_if( m_cells.begin(), m_cells.end() , [](A const& a) { return 3 < a.m_value; } ) << std::endl; // lambda
 std::cout << std::count_if( m_cells.begin(), m_cells.end() , std::bind(std::less<A>(), _1, 4) ) << std::endl; // bind second argument (rhs)
 std::cout << std::count_if( m_cells.begin(), m_cells.end() , std::bind(std::less<A>(), 3, _1) ) << std::endl; // bind first argument (lhs)

A: You need more than just std::less, even if it were a vector of int.
std::count_if calls the predicate with a single argument; std::less
requires two.
There are a number of other functional objects, along the lines of
std::bind2nd which can be combined.  Figuring out the correct
combination isn't trivial, however, and the results are both unreadable
and fragile, so it's not a solution I'd recommend.  If you're using
C++11, there's lamba, which is clearly the way to go.  Otherwise,
boost::bind is quite usable; if you can't use Boost, about the only
reasonable solution is to write a predicate object of your own,
something like:
class ALessThan
{
    int myUpperLimit;
public:
    ALessThan( int upperLimit ) : myUpperLimit( upperLimit ) {}
    bool operator()( A const& object ) const
    {
        return object.m_value < myUpperLimit;
    }
};

(Note that no matter how you do it, you're going to have to provide an
argument to the predicate.  Less than what?)

A: The problem is with your definition of operator< that std::less<> uses under the hood.
With your current operator<, you are effectively telling the compiler that the operator might change either of its operands (as neither the operator nor its argument are declared const).
As std::less<> doesn't want the operands of operator< to change, your implementation is not acceptable.
To fix it, change the definition of operator< to:
16       bool operator<( const A &a ) const
17       {
18          return m_value < a.m_value;
19       }

(Note the addition of const on line 16). This tells the compiler that your operator< won't change either of its operands, making it acceptable for use by std::less<>.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make each textarea unique to its own button I'm trying to create an online commenting system where each user can comment on a post and I want a popup text area to be unique to its own button.
Each element is meant to open a text field where a user is to input text to be posted (say in reply to a preceding post or comment).
There are three buttons (representing each user) which when clicked is intended to display a text field specific to the button (or user).
The problem:
After clicking a button, a modal will popup, try typing some text into the field and close the field, without clearing the text in the field, then open another field by clicking on another button. You'll notice that the text typed into one textarea will also be visible in another instance when you click on another button.
What I'm trying to achieve is to make a textarea unique to its direct button instead of a text constantly showing for all buttons clicked.
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />
    <title>multi textarea</title>

    <button>Open a textarea</button>
    <button>Open a textarea</button>
    <button>Open a textarea</button>

        <textarea name="" id="" cols="80" rows="20"></textarea>

CSS:
.textarea_modal_backdrop{
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #444c;
    display: grid;
    place-items: center;
    visibility: hidden;
    opacity: 0;
}

.textarea_modal_backdrop.textarea_modal_backdrop_active{
    visibility: visible;
    opacity: 1;
}

JS:
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');

for (var i = 0; i < allButtonElms.length; i+=1) {
    allButtonElms[i].onclick = () => {
        modalBackdrop.classList.add('textarea_modal_backdrop_active')
    }
}

document.addEventListener('click', (event) => {
    if (event.target.matches('.textarea_modal_backdrop')) {
        modalBackdrop.classList.remove('textarea_modal_backdrop_active')
    }
})

I'll be grateful if everyone can join in sharing their ideas on how this issue can be solved.
Thank you all!

A: one way can be to

*

*stored textarea values in an array of value

*add a dataset on button to identify value link to textarea

*when textarea is closed save data in values array

const values = [];
var currentButton = 0;
const allButtonElms = document.getElementsByTagName('button');
const modalBackdrop = document.querySelector('.textarea_modal_backdrop');
const textarea = document.querySelector('textarea');

for (var i = 0; i < allButtonElms.length; i+=1) {
    allButtonElms[i].onclick = (e) => {
        var target = e.target || e.srcElement;
        currentButton = target.dataset.number;
        if (!values[currentButton]) {
          values[currentButton] = "";
        }
        textarea.value = values[currentButton];
        modalBackdrop.classList.add('textarea_modal_backdrop_active')
    }
}

document.addEventListener('click', (event) => {
    if (event.target.matches('.textarea_modal_backdrop')) {
       values[currentButton] = textarea.value;
        modalBackdrop.classList.remove('textarea_modal_backdrop_active')
    }
})
.textarea_modal_backdrop{
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #444c;
    display: grid;
    place-items: center;
    visibility: hidden;
    opacity: 0;
}

.textarea_modal_backdrop.textarea_modal_backdrop_active{
    visibility: visible;
    opacity: 1;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />
    <title>multi textarea</title>

    <button data-number="0">Open a textarea</button>
    <button data-number="1">Open a textarea</button>
    <button data-number="2">Open a textarea</button>

        <textarea name="" id="" cols="80" rows="20"></textarea>


text:
Q: Defragmenting a large amount of files (35GB) over night I'm trying to defrag my HP G60-116ea laptop using Piriform Defraggler.
Even their quick scan has been on 0 percent for about 30 minutes.
There are 34GB of fragmented files. I'm presuming this is a bad thing? What will defragging this do for my laptop? It's very slow.
Also, is there a way I can make my screen stay black, but have the laptop running, until I want to start it up as otherwise I have to sleep next to this thing!
During defragmentation, which processes can I safely cancel (such as explorer.exe) to speed things up?

A: Generally speaking, having fragmented files makes read operations on those files slower, as the hard drive must "jump around" to get all the pieces.
There is nothing you can do to make it faster, other than perhaps increase the free space on the drive (only effective if you have less than 15% or so free) or use a different program..
To answer the second part of your question, go toControl Panel\Hardware and Sound\Power Options\Edit Plan Settings and pick how long you want  wait until the screen shuts off.

A: I am not familiar with "piriform defraggler" therefore I cannot compare speeds, but I have had good results with the highly configurable UltimateDefrag Freeware.  It has a number of different modes, and one of them will hopefully serve your needs.

A: Try using the Windows Defragmenter first to see if the issue is with the app or the hardware. It should at least get the process started, and Defraggler can be used afterwards to make sure things are truly the way you want them.
I echo others though in saying that with today's systems, 34GB really isn't that much.
Also, laptop harddrives tend to be much slower than desktop drives in order to make them use less power. This will affect the speed of the defragmentation significantly.


text:
Q: system of differential equations for spread of infection query I have been given a set of equations describing the spread of infection in a population:
$${\frac{dS}{dt}}=-aIS+bI+c-cS$$
$${\frac{dI}{dt}}=aIS-bI-cI$$
where S and I are susceptible and infected populations, respectively, and a,b,c are positive constants.
I want to derive a differential equation for $Q(t)=S(t)+I(t)$
I started by assuming ${\frac{dQ}{dt}}={\frac{d}{dt}}(S+I)={\frac{dS}{dt}}+{\frac{dI}{dt}}=c-cS-cI$
hence, Q(t) would equal the integral of (c-cS-cI) with respect to t, but I'm not sure how to do this and even if it's right. Am I on the right track or is this completely wrong? I need to solve the equation I get for Q(t) to prove that Q(t) tends to 1 as t tends to infinity. Any help would be much appreciated.

A: Your differential equation is OK, and in terms of $Q$ it looks like
$dQ / dt = c - cQ, \tag{1}$
and it's legitimate to write
$Q(t) - Q(t_0) = \int_{t_0}^t (c -cQ(s))ds, \tag{2}$
but trying to find $Q$ from (2) is not the easiest way to go, in my perhaps not-so-humble opinion.  Easier to write
$dQ / dt + cQ = c, \tag{3}$
and solve (3) for the simple, linear, first order differential equation it is.  One easy way to do this is to multiply (3) through by $e^{ct}$:
$e^{ct}dQ / dt + ce^{ct}Q = ce^{ct}, \tag{4}$
then observe that (4) may be written
$d / dt (e^{ct}Q(t)) = d / dt (e^{ct}), \tag{5}$
so if we integrate both sides we obtain
$\int_{t_0}^t (d / ds (e^{cs}Q(s))ds = \int_{t_0}^t (d / ds (e^{cs}))ds, \tag{6}$
or
$e^{ct}Q(t) - e^{ct_0}Q(t_0) = e^{ct} - e^{ct_0} \tag{7}$
which we readily solve for $Q(t)$:
$Q(t) = e^{-c(t - t_0)}(Q(t_0) - 1) + 1; \tag{8}$
it is easily seen that such $Q(t)$ takes the value $Q(t_0)$ at $t = t_0$ and, for $c > 0$, we have
$Q(t) \to 1 \; \text{as} \; t \to \infty, \tag{9}$
both of which are required properties of the solution.  The desired integral form (2) is also satisfied by such $Q(t)$.
Hope this helps!  Cheers,
and as always,
Fiat Lux!!!


text:
Q: read asp.net control in client side I'm using the javascript below to read the value of an asp.net control in the client-side. However, it always returns the null value. I'm using similar code at other pages in my website, but now i can't read this specific control. Please suggest anyways I can fix this problem.
<asp:Label ID="srch_data" runat="server" ClientIDMode="Static" ></asp:Label>

var srch_data = document.getElementById("<%= srch_data.ClientID %>");
alert(srch_data);

A: Try using single quotes:
var srch_data = document.getElementById('<%= srch_data.ClientID %>').value;

A: Try this
var srch_data =document.getElementById('srch_data').innerHTML;

ASP.Net Label becomes span after rendering so instead of finding a label which can not be recognized by JS better find

A: Add the defer attribute to your script element. I tested and it worked.
Try something like below -
<%--defer indicates the script to be run after the document is completely parsed.--%>
<script type="text/javascript" language="javascript" defer="true">
        var label = document.getElementById("<%= srch_data.ClientID %>");
        alert("label : " + label);
</script>
<asp:Label ID="srch_data" runat="server" ClientIDMode="Static"></asp:Label>

This should fix your issue.


text:
Q: Evaluate $\int_0^1\frac{x\ln x}{(1+x^2)^2}\ dx$ $$\int_0^1\frac{x\ln x}{(1+x^2)^2}\ dx
$$
Help me please. I don't know any ways of solution. Thank you.

A: Rewrite:
$$
\int\frac{x\ln x}{(1+x^2)^2}\ dx=\frac14\int\frac{2x}{1+x^2}\cdot\ln x\cdot\frac{2\ dx}{1+x^2}.
$$
Now, consider Weierstrass substitution: $x=\tan\dfrac t2$, $\sin t=\dfrac{2x}{1+x^2}$, $\cos t=\dfrac{1-x^2}{1+x^2}$, and $dt=\dfrac{2\ dx}{1+x^2}$. The integral turns out to be
$$
\frac14\int\sin t\cdot \ln \tan\frac t2\ dt.
$$
Use IBP by taking $u=\ln \tan\dfrac t2\;\Rightarrow\;du=\dfrac12\dfrac{\sec^2\frac t2}{\tan\frac t2}\ dt=\dfrac{dt}{\sin t}$ and $dv=\sin t\ dt\;\Rightarrow\;v=-\cos t$. We obtain
\begin{align}
\frac14\int\sin t\cdot \ln \tan\frac t2\ dt&=\frac14\left[-\cos t\cdot\ln \tan\dfrac t2+\int\dfrac{\cos t}{\sin t}\ dt\right]\\
&=\frac14\left[-\cos t\cdot\ln \tan\dfrac t2+\int\dfrac{1}{\sin t}\ d(\sin t)\right]\\
&=\frac14\left[-\cos t\cdot\ln \tan\dfrac t2+\ln\sin t\right]+C\\
&=\frac14\left[-\dfrac{1-x^2}{1+x^2}\cdot\ln x+\ln\dfrac{2x}{1+x^2}\right]+C\\
&=\frac14\left[\dfrac{x^2\ln x-\ln x}{1+x^2}+\ln2+\ln x-\ln\left(1+x^2\right)\right]+C\\
&=\frac14\left[\dfrac{x^2\ln x-\ln x+\left(1+x^2\right)\ln x}{1+x^2}+\ln2-\ln\left(1+x^2\right)\right]+C\\
&=\frac14\left[\dfrac{2x^2\ln x}{1+x^2}-\ln\left(1+x^2\right)\right]+\frac{\ln2}{4}+C\\
\int\frac{x\ln x}{(1+x^2)^2}\ dx&=\frac14\left[\dfrac{2x^2\ln x}{1+x^2}-\ln\left(1+x^2\right)\right]+K.
\end{align}
Thus
$$
\int_0^1\frac{x\ln x}{(1+x^2)^2}\ dx=\frac14\left[\dfrac{2x^2\ln x}{1+x^2}-\ln\left(1+x^2\right)\right]_{x=0}^1=\large\color{blue}{-\frac{\ln2}{4}}.
$$

A: Integrating by Parts,
$$I=\int \ln x\cdot\frac x{(1+x^2)^2}dx$$
$$=\ln x\int\frac x{(1+x^2)^2}dx-\int\left(\frac{d(\ln x)}{dx}\cdot \frac x{(1+x^2)^2}dx\right)dx $$
For $\displaystyle J=\int\frac x{(1+x^2)^2}dx$ set $1+x^2=u\implies2x\ dx=du$
$\displaystyle J=\int\frac{du}{2u^2}=-\frac1{2u}=-\frac1{2(1+x^2)}$
$\displaystyle\implies I=\ln x\left(-\frac1{2(1+x^2)}\right)+\int\frac1{2x(1+x^2)}\ dx$
Setting $x^2=v,$
$\displaystyle K=\int\frac1{2x(1+x^2)}\ dx=\int\frac{2x}{4x^2(1+x^2)}\ dx$
$\displaystyle4K=\int\frac{dv}{v(1+v)}=\int\frac{v+1-v}{v(1+v)}dv=\int\frac{dv}v -\int\frac{dv}{v+1}=\cdots$

A: Another approach:
expand $\frac{1}{(1+x^2)^2} = \sum_{k=0}^{\infty}(-1)^kkx^{2k}$, then each integral becomes of the form
$$
I_k = (-1)^kk\int_{0}^{1}x^{2k+1} \log x dx
$$
and integrate by parts $du = x^{2 k +1}, v = \log x$. Lots of things will cancel out because of upper and lower bounds on the integral.

A: For $x\ge0$
$$I=\int\frac{x\ln x}{(1+x^2)^2}\ dx=\frac12\int\frac{x\ln(x^2)}{(1+x^2)^2}\ dx$$
Setting $\displaystyle x^2=u,4I=\int\frac{\ln y}{(1+y)^2}dy$
Integrating by Parts, $\displaystyle4I=\ln y\int\frac{dy}{(1+y)^2}-\int\left(\frac{d(\ln y)}{dy}\cdot\int\frac{dy}{(1+y)^2}\right)dy$
$\displaystyle4I=-\frac{\ln y}{1+y}+\int\frac{dy}{y(1+y)}$ which can be solved easily by using my other answer

A: If I may pose yet another method to go about this one.
Make the sub $x=e^{-t}$
$$-\int_{0}^{\infty}\frac{te^{-2t}}{(e^{-2t}+1)^{2}}dt=-1/4\int_{0}^{\infty}\frac{t}{\cosh^{2}(t)}dt$$
Integrate by parts:  $\displaystyle u=t, \;\ dv=\frac{1}{\cosh^{2}(t)}dt$
resulting in:
$$-1/4\lim_{t\to \infty}\left[t\cdot \tanh(t)-\log(\cosh(t))\right]$$
Rewrite as $$\lim_{t\to \infty}\frac{t\cdot \sinh(t)+\log(sech(t))\cosh(t)}{\cosh(t)}$$
and apply L'Hopitals rule:
This gives:
$$\lim_{t\to \infty}-log(1+e^{2t})-\frac{2t}{e^{2t}+1}+\frac{4}{e^{2t}+1}-\frac{4}{(e^{2t}+1)^{2}}+2t+\log(2)$$
Note that as $t\to \infty$, the $2t$ and the $-log(1+e^{2t})$ cancel one another. All other terms go to 0 except for $\log(2)$
This results in our final answer of $$-1/4 \log(2)$$
This may be a fun one to try using contours.

A: First consider
$$
I(s) = \int_0^1\frac{x^{s}}{(1+ x^2)^2} \ \mathrm{d}x,
$$
Then
\begin{align}
I(s) & = \int_0^1 x^s \displaystyle \sum_{n=1}^{\infty} n(-1)^{n+1}x^{2n-2} \ \mathrm{d}x, \\
 & = \displaystyle \sum_{n=1}^{\infty} \frac{n(-1)^{n+1}}{2n+s-1},
\end{align}
And our original integral is
$$
\frac{\partial I }{\partial s}\bigg|_{s=1} = -\displaystyle \sum_{n=1}^{\infty} \frac{n(-1)^{n+1}}{(2n)^2} = -\frac{1}{4}\displaystyle \sum_{n=1}^{\infty} \frac{(-1)^{n+1}}{n} = -\frac{\ln 2}{4}.
$$
Edit - This is simply Alex's approach. I took an unnecessary detour.

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{\int_{0}^{1}{x\ln\pars{x} \over \pars{1 + x^{2}}^{2}}\,\dd x:\ {\large ?}}$

With $\ds{\large 0 < \epsilon < 1}$:
  \begin{align}
&\color{#c00000}{\int_{\epsilon}^{1}{x\ln\pars{x} \over \pars{1 + x^{2}}^{2}}\,\dd x}
=-\,\half\int_{x = \epsilon}^{x = 1}\ln\pars{x}\dd\pars{1 \over 1 + x^{2}}
=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}
+\half\int_{\epsilon}^{1}{1 \over x^{2} + 1}\,{1 \over x}\,\dd x
\\[3mm]&=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}
+\half\Im\int_{\epsilon}^{1}{1 \over x - \ic}\,{1 \over x}\,\dd x
=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}
-\half\Re\int_{\epsilon}^{1}\pars{{1 \over x - \ic} - {1 \over x}}\,\dd x
\\[3mm]&=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}
-\half\Re\ln\pars{\bracks{1 - \ic}/1 \over \bracks{\epsilon - \ic}/\epsilon}
=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}
-\half\Re
\ln\pars{\epsilon\,{1 + \epsilon + \bracks{1 - \epsilon}\ic \over \epsilon^{2} + 1}}
\\[3mm]&=\half\,{\ln\pars{\epsilon} \over 1 + \epsilon^{2}}-\half
\ln\pars{\epsilon\,{\root{2 + 2\epsilon^{2}} \over \epsilon^{2} + 1}}
\\[3mm]&=\underbrace{\half\,\ln\pars{\epsilon}\pars{{1 \over 1 + \epsilon^{2}} - 1}}
_{\to\ 0\quad\mbox{when}\quad \epsilon \to 0^{+}}\
-\
{1 \over 4}\,\ln\pars{2}\ +\
\underbrace{{1 \over 4}\ln\pars{1 + \epsilon^{2}}}_{\to\ 0\quad\mbox{when}\quad \epsilon \to 0^{+}}
\end{align}

$$\color{#00f}{\large%
\int_{0}^{1}{x\ln\pars{x} \over \pars{1 + x^{2}}^{2}}\,\dd x
=-\,{1 \over 4}\,\ln\pars{2}}
$$

A: Integration by parts with $u=\ln x$, $dv=xdx/(1+x^2)^2$, followed by partial fractions gives the indefinite integral
$$\begin{align}
\int{x\ln x\over(1+x^2)^2}dx&={-\ln x\over2(1+x^2)}+{1\over2}\int{1\over x(1+x^2)}dx\\
&={-\ln x\over2(1+x^2)}+{1\over2}\int\left({1\over x}-{x\over(1+x^2)}\right)dx\\
&={-\ln x\over2(1+x^2)}+{1\over2}\left(\ln x-{1\over2}\ln(1+x^2) \right)\\
&={x^2\ln x\over2(1+x^2)}-{1\over4}\ln(1+x^2)
\end{align}$$
When you turn this into a definite integral from $0$ to $1$, the term with $x^2\ln x$ in the numerator is $0$ at both limits, so you're left with
$$\int_0^1{x\ln x\over(1+x^2)^2}dx=-{1\over4}\ln2$$
Note, you can't just write
$$\int_0^1{x\ln x\over(1+x^2)^2}dx={-\ln x\over2(1+x^2)}\Big|_0^1+{1\over2}\int_0^1{1\over x(1+x^2)}dx$$
because the two terms on the right hand side there diverge at $x=0$.  For this problem, you really have to find the complete antiderivative before you plug in limits.


text:
Q: How to use proper typescript types in mongodb find filter combined with a predefined schema? I am using native mongodb (npmjs.com/mongodb) driver for node.js.
I've a collection with following interface:
interface Users {
  name: string;
  age: number;
  favoriteFood: string;
}

I've to query this collection like:
const filter = { name: "lily" };
DB.collection("Users").find(filter);

Now, how will I define type of that filter variable?
I could use something like Record<string, any>. But that is vary broad.
const filter: Record<string, any>
  = { nmae: "lily" }
// see the miss typed name. Gives no errors.
// but I'd like to see a little type checking there.

So I tried
const filter: Partial<Record<keyof Users, any>>
 = { name: "lily" } // this force me to use the same keys as in schema.

Now is there any way I can avoid the any type in the above code? So that it support all kinds of filters and operators like $gt, $lt etc.

A: Basically, you need to import Filter type from mongodb and then simply use it.
const filter: Filter<User> = {}

For example lets say you want to create a function that receives a filter object.
function find(filter: Filter<User> = {}) {
   return Db.collection<User>("users").find(filter).toArray();
}

Now you can call this function and have the auto complete suggestion. you can also use different operators such as $in.


text:
Q: C# lambda-> All rows Select Add Row_Number I have a table:
DataTable store_temp = new DataTable();
store_temp.Columns.Add("patn");
store_temp.Columns.Add("rf");
store_temp.Columns.Add("name");
store_temp.Columns.Add("conv");
store_temp.Columns.Add("conv_type");
store_temp.Columns.Add("recorddate");
store_temp.Columns.Add("executiondate");

My C# code :
int i = 0;
var rowsgroups = (from row in store_temp.AsEnumerable().GroupBy(row =>
row.Field<string>("patn"))
.OrderBy((g => g.OrderByDescending(y => y.Field<string("executiondate")).ThenByDescending(y =>
y.Field<string>("rf"))))
select new
{
    patn = row.ElementAt(i),
    rf_num = ++i,
}).ToArray();

I want the lambda experession, which is equivalent to:

select patn, rf,

>     row_number() over( partition by  patn order by  executiondate,rf )
    as rf_num,

     name, conv,conv_type, recorddate, executiondate
      from store_temp2

But, lambda syntax  ... var rowsgroups has just a one row..
I want to show  all rows in store_temp.
What should I do to fix the query?

A:
row_number() over(partition by patn order by executiondate, rf)

means in LINQ you need to group by patn, then order each group by executiondate, rf, then use the indexed Select overload to get row numbering inside the group, and finally flatten the result with SelectMany.
With that being said, the equivalent LINQ query could be something like this:
var result = store_temp.AsEnumerable()
    .GroupBy(e => e.Field<string>("patn"), (key, elements) => elements
        .OrderBy(e => e.Field<string>("executiondate"))
        .ThenBy(e => e.Field<string>("rf"))
        .Select((e, i) => new
        {
            patn = key,
            rf = e.Field<string>("rf"),
            rf_num = i + 1,
            name = e.Field<string>("name"),
            conv = e.Field<string>("conv"),
            conv_type = e.Field<string>("conv_type"),
            recorddate = e.Field<string>("recorddate"),
            executiondate = e.Field<string>("executiondate")
        }))
    .SelectMany(elements => elements)
    .ToArray();

A: Try something like this
select new
{
    rowNum = store_temp.Rows.IndexOf(row),
    patn = row.ElementAt(i),
    rf_num = ++i,
}).ToArray();

A: I don't think you required any groupby as per your required sql
        var i=0;
        var rowsgroups = (from row in store_temp.AsEnumerable()
                          orderby row.Field<string>("executiondate") descending,
                          row.Field<string>("rf") descending
                          select new
                            {
                                patn = row.Field<string>("patn"),
                                rf_num = ++i,
                                name = row.Field<string>("name"),
                                conv = row.Field<string>("conv"),
                                conv_type = row.Field<string>("conv_type"),
                                recorddate = row.Field<string>("recorddate"),
                                executiondate = row.Field<string>("executiondate")
                            }).ToArray();


text:
Q: NodeJS Asynchronous FIFO Queue Implementation I'm currently working on a system that allows users to submit a request to my server, and the server assigns them a random number out of a given set of numbers until those numbers are exhausted. There can be N sets of numbers at any given time, meaning users may be requesting from a single set, or have the ability to request from many sets (each through their own request).
Each set of numbers is stored in a MongoDB, and the requests for a number can come in anywhere from milliseconds apart to hours apart.
My current implementation attempts to use locks on the database entry, where when a request comes in for a number, before attempting to assign a number, it sets a flag on the entry indicating it's locked and saves it. Other requests then have a while loop that fetches the entry every second until the lock flag is false.
When requests come in more than a second or so apart from each other, the current system works perfectly fine. However, when I get requests within milliseconds of each other, the system enters a deadlock because there isn't enough time for one request to lock the entry before the other request also attempts to lock it.
What I would like to do is implement a FIFO queue to solve this, but I keep coming back to the potential for processes to occur in the milliseconds when certain actions are being performed (i.e. fetching data from the db, saving data to the db, etc).
My stack is as follows:

*

*NodeJS w/ Typescript

*ExpressJS Server

*Remote MongoDB Database

It may also be worth noting that all interactions from users come in through event handlers, so no single request knows about any other request. There is also no common place in which I can store a data structure in code due to the requirement that many different sets of numbers can exist at any given time, and users can submit requests to any one of them.
Can anyone offer some guidance in how I could potentially solve this issue?


text:
Q: Including a Spark Package JAR file in a SBT generated fat JAR The spark-daria project is uploaded to Spark Packages and I'm accessing spark-daria code in another SBT project with the sbt-spark-package plugin.
I can include spark-daria in the fat JAR file generated by sbt assembly with the following code in the build.sbt file.
spDependencies += "mrpowers/spark-daria:0.3.0"

val requiredJars = List("spark-daria-0.3.0.jar")
assemblyExcludedJars in assembly := {
  val cp = (fullClasspath in assembly).value
  cp filter { f =>
    !requiredJars.contains(f.data.getName)
  }
}

This code feels like a hack.  Is there a better way to include spark-daria in the fat JAR file?
N.B. I want to build a semi-fat JAR file here.  I want spark-daria to be included in the JAR file, but I don't want all of Spark in the JAR file!

A: The README for version 0.2.6 states the following:

In any case where you really can't specify Spark dependencies using sparkComponents (e.g. you have exclusion rules) and configure them as provided (e.g. standalone jar for a demo), you may use spIgnoreProvided := true to properly use the assembly plugin.

You should then use this flag on your build definition and set your Spark dependencies as provided as I do with spark-sql:2.2.0 in the following example:
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.2.0" % "provided"

Please note that by setting this your IDE may no longer have the necessary dependencies references to compile and run your code locally, which would mean that you would have to add the necessary JARs to the classpath by hand. I do this often on IntelliJ, what I do is having a Spark distribution on my machine and adding its jars directory to the IntelliJ project definition (this question may help you with that, should you need it).


text:
Q: Format /dev/sda as unallocated I want to format my hard disk (/dev/sda) to be unallocated (free space).
The reason I want this is because I'm installing cPanel CentOS disk and it shows me that there's not free space on my system.
This is the format command that I know, but the hard drive isn't becoming "free" when I format it that way:
mkfs.ext4 /dev/sda

A: A hard disk usually has a partion table. If you use mkfs.ext4 /dev/sda you'll create a filesystem over the whole disk. Better create a partition table with fdisk or parted or similar. /dev/sda may not be mounted for that. If you created the filesystem the partition programs might complain about it. To clear the data from the mkfs you can use dd if=/dev/zero of=/dev/sda bs=512 count=1.
I'm not quite sure if cPanel wants free unformatted space or if it needs unused space inside a mounted filesystem. If it wants free unformatted space just create an empty partition table and you're done. It might need a reboot if /dev/sda was somehow in use.
If cPanel wants unused space inside a mounted filesystem, create a partition spanning the  whole disk. This partition is then /dev/sda1. Use mkfs.ext4 /dev/sda1 to format it and mount /dev/sda1 /mountpoint to mount it (You'll have to create an entry in /etc/fstab to mount it at boot time). After that you'll have to tell cPanel to use /mountpoint.


text:
Q: Доступ к DOM popup.html расширения Chrome Уважаемые коллеги, вопрос следующего характера:
Я пишу расширение для хрома. Как нужно подключить js-файл и как в нем получить доступ к DOM popup.html?
Имеется такая разметка popup.html:
<!doctype html>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>xdParser v1.1</title>
<link href="css/main.css" rel="stylesheet"/>

  <input id="starter" type="button" value="Запустить парсер" onclick="console.log('sd');" />
  Запустить парсер

Но никакой реакции от js на клики на этой странице я не получаю.

A: В расширениях Google Chrome есть запрет на исполнение inline JavaScript.

Поэтому обработка событий вида onclick="javascript:..." не работает.
Вам необходимо подключать JS код в виде отдельного внешнего файла


text:
Q: Xamarin forms LibVlc not able to to change aspect ratio on ios I have a video using LibVLC and want to force the video to fit a specific size on the screen.(This will stretch the video slightly).
I was looking at the question why i can't change my video size in xamarin forms ios libvlcsharp as it seems to be a similar/same issue. I don't have enough reputation to leave a comment, and didn't want to provide a question as an answer. Doing what was suggested there (adding the scale = 0 on the media player) doesn't seem to fix the issue.
I have a grid with 2 rows of *.
I then add a videoview in the top row.
I then load the videoView and media player in the code behind. On android this works as expected.
On iOS the videoview initially loads with black bars around it. Rotating the screen landscape/ portrait fixes the issue. It's like iOS is rendering the video first and then applying the aspect ratio, but not redrawing until the device orientation forces it to be.
I have tried changing the visibility of the element and adding/removing it from the grid in the code behind to try and "trick" iOS into rendering it correctly.
I have also tried doing inside of a Device.BeginInvokeOnMainThread as I thought that might be the issue. Running it on the ui thread but that didn't seem to make a difference either.
I am doing this inside a xamarin shell project in case that makes any difference with how items are rendered.
Any help would be appreciated.
Below is some sample code:
<Grid BackgroundColor="LightGray" x:Name="MainGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="*"/>
              <shared:VideoView x:Name="VideoView"
                              Grid.Row="0"
                              Grid.Column="0"
                              BackgroundColor="Black">

            </shared:VideoView>
        </Grid.RowDefinitions>

Code behind
 protected async override void OnAppearing()
    {
        base.OnAppearing();

        VideoView.MediaPlayerChanged += VideoView_MediaPlayerChanged;

        Core.Initialize();

        _libVLC = new LibVLC();

        CreateVideoPlayer();

    }

  async void CreateVideoPlayer()
    {
     using (var media = new Media(_libVLC, new Uri(url)))
                {

                    _mediaPlayer = new MediaPlayer(_libVLC)
                    {
                        Media = media,
                        EnableHardwareDecoding = true,

                    };
                }

                VideoView.MediaPlayer = _mediaPlayer;
                //fix aspect ratio so if the stream is a weird resolution it will fill the space with the grid.
                VideoView.MediaPlayer.AspectRatio = $"{Height}:{Width}";//"1920:1080";//Aspect.Fill.ToString();
                VideoView.MediaPlayer.Scale = 0

                VideoView.MediaPlayer.EncounteredError += MediaPlayer_EncounteredError;
                VideoView.MediaPlayer.Stopped += MediaPlayer_Stopped;
                VideoView.MediaPlayer.Buffering += MediaPlayer_Buffering;
                VideoView.MediaPlayer.Opening += MediaPlayer_Opening;
                VideoView.MediaPlayer.PositionChanged += MediaPlayer_PositionChanged;
                VideoView.MediaPlayer.Playing += MediaPlayer_Playing;
    }

I have made a very simple sample based on the MediaElement sample in the libvlc-sharp-sample example.
I am using the MediaPlayerElement with the IsAspectRatioButtonVisible="true".
This works as expected on android. But has the same issue on ios. Clicking the button initally displays text to say "4:3" etc but the screen itself doesn't change. Rotating the ios device then causes the button to behave as expected.
This seems to be an issue with both a "blank" xamarin project and within the shell.
I am using a real iphone se (not a simulator) on software version 15.6.
This also happens with an ios emulator running iphone 13 pro 15.5.
I have created a simple github app here:
https://github.com/developerfiveneosoftware/VideoAspectRatioTest


text:
Q: Simulink - Find computed index of multidimensional signal at specific time I am trying to find which element(index) of a multidimensional signal is computed at a specific time in a Simulink model. Assume that there is a multidimensional input signal given to an add block together with a constant so Simulink calculates the sum with the constant for each element of the signal and gives the output as multidimensional signal. I want to know which index of the signal is computed at a time so I can do additional computation. How can I do that?

A: Do you want to do additional computation during simulation or after? In the latter case, you can save the multidimensional signal to the MATLAB Workspace as a "structure with time" variable. Then do your additional computations by finding the index of the time point of interest and the associated multidimensional data point. In the former case, you can probably a MATLAB function block with two inputs: the output of a clock block and the multidimensional signal. Then do your processing in there using MATLAB code.


text:
Q: Testing ajax from therubyracer (or execjs)? I want to test javascript code from a ruby context. Specifically, I want to setup my database with ruby, query it with my javascript model, and confirm my javascript state from ruby. I want to do this without mocking.
I've tried simply loading my client libraries into a v8 context, but that causes therubyracer to choke in all sorts of ways (window not defined, userAgent not defined, etc).
Further I'm using headless browsers to test my javascript code, but they don't provide me the ruby context I need to leverage for these cases.
I think I need to load a browser (or a dom simulator) into a v8 context, but i don't what libraries are out there to do this. Maybe you have another idea?
How can I do this?

A: I've used capybara-webkit for this kind of task. You don't actually need to use the RSpec helpers, you can also simply create an in-memory browser instance which you can direct to your HTML/Javascript. The advantage is that it provides a evaluate_script method that can be used to interact with the browser's Javascript context (to push/receive data).
Whether or not this is applicable in your case is what kind of "ruby context" you need to be able to access from the Javascript side.
There are also some other projects you might be interested in:

*

*http://www.envjs.com/: browser emulation in JS

*http://zombie.labnotes.org/: browser emulation in Node.js

*https://github.com/LearnBoost/tobi: A similar approach to zombie


text:
Q: Imprimir linha negativa DPP-450 Datecs EscPos Estou começando um projeto nessa impressora (DPP-450), e me deparei com um problema que não estou conseguindo resolver:
Preciso imprimir uma linha negativa, fundo preto e escrita em branco.
No manual esta "GS B" como o código para isso, porem só consigo executar os códigos "ESC".
Não sei se existe alguma forma de alternar entre GS/ESC, não pude encontrar nada que me ajudasse.

A: Olá.
ESC na verdade corresponde ao char 27. Atualmente uso Delphi então os comandos que usam ESC, são passados assim:
/* Exemplo de negrito */
_prNegritoAtivar : string = #27'E1';
_prNegritoDesativar : string = #27'E0';
Desta forma, para passar o GS, que corresponde ao char 29, faço assim:
/* definindo a largura do código de barras */
_prBarCodeLargura : string = #29'w' + '2'; //entre 2 e 4
no seu caso o GS B, seria: #29'B'
Sacou ?


text:
Q: How to draw a custom background I have to design a triangle and display some text inside it with an angle of 45,  below that I have to put a text view outside the boundaries of the triangle to display some other text. It is like a banner. However when I use a relative layout and put a triangular background, it still acts as a rectangle, obscuring my Text view. Below is the code I use:
<RelativeLayout
        android:id="@+id/relative"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/image_sticker" >

        <com.example.AngledTextView
            android:id="@+id/textViewx"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:rotation="52"
            android:textColor="#FFFFFF" />
    </RelativeLayout>

My AngledTextView Class:
public class AngledTextView extends TextView  {

    private int mWidth;
    private int mHeight;

    public AngledTextView(Context context, AttributeSet attrs)  {
        super(context, attrs);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        /*Paint textPaint = new Paint();
        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;

            canvas.rotate(45, xPos,yPos);   */

        super.onDraw(canvas);
        canvas.restore();
    }
}

Problem:

Any hints or links to suggested tutorials will be highly appreciated :)

A: i've done similar stuff recently. Here are some tips i've used:

*

*Create customView class.

*Init at least one Paint (semitransparent, fill) and one Path on your init method. It should be called from constructors.

*On your onDraw method customize path. For example:
mPath = new Path();
mPath.moveTo(.0f, this.getHeight());
mPath.lineTo(this.getWidth(), this.getHeight());
mPath.lineTo(this.getWidth(),0.25f*this.getHeight());
mPath.lineTo(.0f, .0f);
mPath.lineTo(.0f, this.getHeight());

*This  will make a Path similar to a trapezoid. Just customize your points to make a triangle. Then call
canvas.clipPath(mPath);
canvas.drawPath(mPath,mPaint);

*With these points, you will draw your triangle. You could pass a String to your init method and call drawText before drawing the path:
canvas.drawText(str, xTit, yTit, mPaintTit);

I hope this will help =)

A: In your regular textview use rotate animation like.
 <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:rotation="45"
    android:text="@string/hello_world" />

A: Your implementation could inherit from Drawable and implement getTransparentRegion()
Next, use this drawable as background on a view that is drawn on top of your TextView (probably by having both as childs inside a FrameView)

A: i have some link for crate triangle background as below
link1
link2
link3
i hope it helpful for you

A: Before you do any drawing, you must initialize and load the shapes you plan to draw. Unless the structure (the original coordinates) of the shapes you use in your program change during the course of execution, you should initialize them in the onSurfaceCreated() method of your renderer for memory and processing efficiency.
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
    ...

    // initialize a triangle
    mTriangle = new Triangle();
    // initialize a square
    mSquare = new Square();
}

Example
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

public class Slice extends LinearLayout {

    final static String TAG = "Slice";
    Paint mPaint;
    Path mPath;

    public enum Direction {
        NORTH, SOUTH, EAST, WEST;
    }

    public Slice(Context context) {
        super(context);
        Create(context);
    }

    public Slice(Context context, AttributeSet attrs) {
        super(context, attrs);
        Create(context);
    }

    private void Create(Context context) {
        Log.i(TAG, "Creating ...");

        mPaint = new Paint();
        mPaint.setStyle(Style.FILL);
        mPaint.setColor(Color.RED);

        Point point = new Point();
        point.x = 80;
        point.y = 80;

        mPath = Calculate(point, 70, Direction.SOUTH);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Log.i(TAG, "Drawing ...");

        canvas.drawPath(mPath, mPaint);
    }

    private Path Calculate(Point p1, int width, Direction direction) {
        Log.i(TAG, "Calculating ...");

        Point p2 = null, p3 = null;

        if (direction == Direction.NORTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y - width);
        } else if (direction == Direction.SOUTH) {
            p2 = new Point(p1.x + width, p1.y);
            p3 = new Point(p1.x + (width / 2), p1.y + width);
        } else if (direction == Direction.EAST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x - width, p1.y + (width / 2));
        } else if (direction == Direction.WEST) {
            p2 = new Point(p1.x, p1.y + width);
            p3 = new Point(p1.x + width, p1.y + (width / 2));
        }

        Path path = new Path();
        path.moveTo(p1.x, p1.y);
        path.lineTo(p2.x, p2.y);
        path.lineTo(p3.x, p3.y);

        return path;
    }
}


text:
Q: How can i write "setTimeOut" function in react hooks? I am working on displaying a "message" on the component based on the server response, and i wanted that message to disappear after 5 second. I tried my best with setTimeout but  no luck, can you help me?
Here is my code:
import React, { useState } from "react";
import { Form, Button, Container, Row, Col} from 'react-bootstrap'
import axios from 'axios'

export default function Users() {

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("")

  function handleSubmit(e){
    e.preventDefault()
    const credential = { email, name };
      axios
        .post('/', credential)
        .then(response => {
          if(response.status === 201) {
            resetInputs()
            setMessage(response.data.message)
          }
        })
        .catch(error => {
          if (error.response.status === 409) {
            setMessage(error.response.data.message)
          }
        })
  }

  function resetInputs(){
    setEmail("")
    setName("")
  }

  return (

Welcome to mywebsite

Enter your name and your email to join our waiting list!

                 {message}

  )
}

A: You call setTimeout after setting the message, telling it to fire after five seconds, and then clear the message:
function handleSubmit(e){
  e.preventDefault()
  const credential = { email, name };
    axios
      .post('/', credential)
      .then(response => {
        if(response.status === 201) {
          resetInputs()
          setMessage(response.data.message)
        }
      })
      .catch(error => {
        if (error.response.status === 409) {
          setMessage(error.response.data.message)
        }
      })
      .finally(() => {       // ***
        setTimeout(() => {   // ***
            setMessage("");  // *** If you want to clear the error message as well
        }, 5000);            // *** as the normal message
      });                    // ***
}

or
function handleSubmit(e){
  e.preventDefault()
  const credential = { email, name };
    axios
      .post('/', credential)
      .then(response => {
        if(response.status === 201) {
          resetInputs()
          setMessage(response.data.message)
          setTimeout(() => {   // *** If you only want to automatically clear
              setMessage("");  // *** this message and not an error message
          }, 5000);            // ***
        }
      })
      .catch(error => {
        if (error.response.status === 409) {
          setMessage(error.response.data.message)
        }
      });
}

A: You can add setTimout to your axios call, or you can reset it independently like this:
import { useEffect } from "react";

...

useEffect(() => {
  let isUnmounted = false;

  if (message !== "") {
    setTimeout(() => {
      if (!isUnmounted ) {
        setMessage("");
      }
    }, 5000);
  }

  return () => { isUnmounted = true; };
}, [message])

isUnmounted prevents using setMessage() in an unmounted component, it is possible for a user to close the component before time is reached.

A: Something like this may work (untested):
const useTimedState = (initialState, duration) => {
    const [state, setState] = setState(initialState);
    useEffect(() => {
        if (typeof state === 'undefined') {
            return;
        }
        const timer = setTimeout(() => {
            setState();
        }, duration);
        return () => clearTimeout(timer);
    }, [state]);
    return [state, setState];
}

export default function Users() {

  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useTimedState(undefined, 5000);

  function handleSubmit(e){
    e.preventDefault()
    const credential = { email, name };
      axios
        .post('/', credential)
        .then(response => {
          if(response.status === 201) {
            resetInputs()
            setMessage(response.data.message)
          }
        })
        .catch(error => {
          if (error.response.status === 409) {
            setMessage(error.response.data.message)
          }
        })
  }
}


text:
Q: How to execute program on Google Compute Engine locally As the title, I have some programs already uploaded to the compute engine instance running Linux, and plan to execute them locally.
However, I can't find any doc in Google Compute Engine API that how to execute the program from my local.
For example, I am looking for a function like
instance.run_Command("$ sudo python program.py args")

Any idea? Using google-cloud-api is not necessary, any methods are welcome.

A: You can do this with Fabric in Python.  Behind the scenes Fabric just uses SSH.

A: You can use gcloud compute ssh --zone ZONE INSTANCE --command 'python program.py args'.


text:
Q: SSIS send email on error sending multiple errors I have simple SSIS package in which On Error event handler I have created Send email task to send error details. But I get multiple emails for one error. I found the ways to club all emails but they are in vb script and my SQL server is 64 bit which in turn requires hotfix installation for binary compilation.
So I need any alternative option for that. It's fine with me even though I can send first error email and ignore other.
Any suggestion will be appreciated.

A: I found the solution which meet my requirement of sending first error and ignoring rest.
Used for loop container, declared variable Count with value = 0 and in for loop container set the condition Count < 1; Count = count + 1.

A: The reason you are getting multiple errors has to do with event bubbling.  If you have an event handler at the parent package level, and it has, for instance a data flow task, and in the data flow, there is a OLEDB Command component that fails, then that object will throw and error that bubbles up to the event handler. Then because the component failed, the Data Flow task reports an error and it bubbles up to the event handler.  Then because the Data Flow Task failed, the package fails and that is sent to the event handler.  I had some code where I dealt with this in the past, but I cannot get to that machine right now.  I will update this question with the full answer later today, but it had to do with checking the System::SourceID variable against the System::PackageGUID variable and only running the mail portion of the error handler when they were equal.  System::SourceID is the variable detailing which object is throwing the error, so this would limit the reporting of errors to those that bubble up to the package level (i.e. those that will fail the entire task.)
@Rajiv Varma
In my event handler (which is in the package level) I have a script task (which has no code behind it (basically a no-op)) and a send mail task.  Between the script task and the send mail I us the constraint as a conditional (I set the evaluation operation: to Expression and the expression to the value
@[System::SourceID]== @[System::PackageID]

which tests to see if the source of the error is the main package object then I use the send mail task to send my error message.
Why this works:  If I have a hierarchy of objects
Main package - Loop Task - Data Flow Task
If the Data Flow Task fails, an event is thrown.  After the event throws, it bubbles up to the next level and the Loop Task throws the same error.  After this event throw it bubbles up to the main package layer and throws the same error again.  This is why @Pramodtech had the problem in the first place, each level was triggering the same error message again.  What I am effectively doing here is ignoring any error that is not at the main package level.  So I don't send any message until the message bubbles up to the top level.  Hope this helps.

A: One method to send a single mail containing a summary of all the error messages is:

*

*Create a String variable to store the error description summary.

*In the OnError Event handler, use an Expression task to store the error description as below:

@[User::ErrorDescSummary] = @[User::ErrorDescSummary] + @[System::ErrorDescription]

*Towards the end of your package, add a Send Email task, use the Precedence Constraint editor to set Evaluation Operation to "Expression" and check for

@[User::ErrorDescSummary]!=""
We are sending Error Email with a complete error summary if the variable is not empty.

A: Thanks Ajay Kumar Meda, a small change in your solution works fine:
One method to send a single mail containing a summary of all the error messages is:

*

*Create a String variable to store the error description summary.

*In the OnError Event handler, use an Expression task to store the error description as below:
@[User::ErrorDescSummary] = @[User::ErrorDescSummary] + @[System::ErrorDescription]

*Go to Task Failed in the event handler and add the Mail Task using the
variable @[User::ErrorDescSummary]

A: I found the solution which meet my requirement of sending first error and ignoring rest.
Used for loop container, declared variable Count with value = 0 and in for loop container set the condition Count < 1; Count = count + 1.
This is not working I'm getting multiple mails of error there one script task which send the  status mail like job id  status starttime and end time total time.This mail of this  task getting as many of error occur in package


text:
Q: Generating thumbnails from videos created using AVAssetWriter I'm recording video+audio using AVAssetWriter and the captureOutput callback. The problem is that in about 5% of the cases I cannot generate a thumbnail from second zero(If I try to go further in the video, then there is no problem). The error I'm getting is:

Error Domain=AVFoundationErrorDomain Code=-11832 "Cannot Open"
  UserInfo=0x4b31b0 {NSLocalizedFailureReason=This media cannot be
  used., NSUnderlyingError=0x4effb0 "The operation couldn't be
  completed. (OSStatus error -12431.)", NSLocalizedDescription=Cannot
  Open}

Here is the code I'm using:
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
generator.appliesPreferredTrackTransform=TRUE;
[asset release];
CMTime thumbTime = CMTimeMakeWithSeconds(0,30);

AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
{
    if (result != AVAssetImageGeneratorSucceeded)
    {
        [self NSLogPrint:[NSString stringWithFormat:@"couldn't generate thumbnail, error:%@", error]];
    }

    UIImage *thumbImg=[[UIImage imageWithCGImage:im] retain];

    [image setImage:thumbImg];
    [thumbImg release];

    [generator release];
};

CGSize maxSize = CGSizeMake(177, 100);
generator.maximumSize = maxSize;
[generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];

Here is how I'm setting up my video AVAssetWriterInput:
- (BOOL) setupAssetWriterVideoInput:(CMFormatDescriptionRef)currentFormatDescription
{
    float bitsPerPixel;
    CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(currentFormatDescription);
    int numPixels = dimensions.width * dimensions.height;
    int bitsPerSecond;

    // Assume that lower-than-SD resolutions are intended for streaming, and use a lower bitrate
    if ( numPixels < (640 * 480) )
        bitsPerPixel = 4.05; // This bitrate matches the quality produced by AVCaptureSessionPresetMedium or Low.
    else
        bitsPerPixel = 11.04; // This bitrate matches the quality produced by AVCaptureSessionPresetHigh.

    bitsPerSecond = numPixels * bitsPerPixel;

    NSDictionary *videoCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              AVVideoCodecH264, AVVideoCodecKey,
                                              [NSNumber numberWithInteger:dimensions.width], AVVideoWidthKey,
                                              [NSNumber numberWithInteger:dimensions.height], AVVideoHeightKey,
                                              [NSDictionary dictionaryWithObjectsAndKeys:
                                               [NSNumber numberWithInteger:bitsPerSecond], AVVideoAverageBitRateKey,
                                               [NSNumber numberWithInteger:30], AVVideoMaxKeyFrameIntervalKey,
                                               nil], AVVideoCompressionPropertiesKey,
                                              nil];
    if ([_videoWriter canApplyOutputSettings:videoCompressionSettings forMediaType:AVMediaTypeVideo])
    {
        self._videoWriterInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeVideo outputSettings:videoCompressionSettings];
        self._videoWriterInput.expectsMediaDataInRealTime = YES;
        self._videoWriterInput.transform = [self returnOrientation];
        if ([_videoWriter canAddInput:self._videoWriterInput])
            [_videoWriter addInput:self._videoWriterInput];
        else
        {
            NSLog(@"Couldn't add asset writer video input.");
            return NO;
        }
    }
    else
    {
        NSLog(@"Couldn't apply video output settings.");
        return NO;
    }

    return YES;
}

I know that the error means there is no image at that time, but why is this happening?
I've also tested recording using AVCaptureMovieFileOutput and the thumbnails are always generated.
Also if I export the video that to camera roll, the preview also isn't available in Photos.
P.S: I've also read somewhere that this may have something to do with the key frame interval, but I'm not sure how.

A: I sort of fixed my problem. I was running on iOS 4.2.1,and decided to upgrade to iOS 5.1.1 and the issue dissappeared.


text:
Q: Redirecting dynamic URLS with NGINX and flask This is my first time using NGINx, and uwsgi. I have read up on several tutorials, mainly this one (https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04), however, it's not particularly helpful when I have dynamic urls and multiple application routes defined in my flask application. For the sake of simplicity, here are my app.py (flask), and my ngingx configurations below:
app.py (simplified version for StackExchange)
from flask import Flask
application = Flask(__name__)

#works!
@application.route("/")
def hello():
    return "
Hello There!
"

#DOESN'T WORK
@application.route("/<userId>")
def hello_user():
    return "
Hello some user!
"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

nginx configuration:
server {
listen 9090;
server_name myapp.new;

location / {
    include uwsgi_params;
    uwsgi_pass unix:/home/user1/NGINxApp/app.sock;
    }

}

How can I allow dynamic urls (using variable rules) here?

A: I was able to find the solution here:
http://flask.pocoo.org/docs/0.10/deploying/uwsgi/
I changed the nginx configurations slightly, and now it works:
location / { try_files $uri @yourapplication; }
location @yourapplication {
    include uwsgi_params;
    uwsgi_pass unix:/home/user1/NGINxApp/app.sock;
}


text:
Q: Conditional HTML in Codebehind vs Inline I am having trouble finding documentation on this subject, perhaps because I don't know the proper way to explain it. Please take a look at the following simplified code:
<html>
    <script type="text/javascript">

        $(function () {

            <% if (Page.IsPostBack == true) { %>
            alert("PAGE IS POSTBACK");
            <% } else { %>
            alert("PAGE IS NOT A POSTBACK");
            <%} %>

        });
    </script>
</html>

This works perfectly, but I would like to put this code on my codebehind page so I make database calls and change the jquery based on what my methods return. Is there a codebehind alternative to the inline code as I have shown above?

A: If you want to call get a value of code behind from aspx page, you can create a public property and access it using <%= xxxx %> -
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" />
<script type="text/javascript"
  src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        if ("<%= PageIsPostBack  %>" == "True") {
            alert("PAGE IS POSTBACK");
        } else {
            alert("PAGE IS NOT A POSTBACK");
        }
    });
</script>

public partial class _Default : System.Web.UI.Page
{
    public bool PageIsPostBack
    {
        get { return Page.IsPostBack; }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

    }
}

Note: for Page.IsPostBack, you can even access from aspx like this without public property -
<script type="text/javascript">
    $(function () {
        if (<%= Page.IsPostBack.ToString().ToLower() %>") {
            alert("PAGE IS POSTBACK");
        } else {
            alert("PAGE IS NOT A POSTBACK");
        }
    });
</script>


text:
Q: MILP solver for black box function I need to solve a problem that has both integer and continuous values. However, I the function to be optimized is solved remotely.
I need a MILP solver that can optimize the parameters to F(x) without me modeling out all of F(x)
All of the Python MILP solvers I've seen AFAIK require you to model the problem, give the constraints, and then it solves it. I need one that can optimize the parameters just by sending parameters and getting results from the remote server.
I'd like to not have to build my own gradient descent solver.


text:
Q: Is it possible to run IHostedService instances inside a WindowsService? I am trying to convert a Console app into a Windows Service. The Console app is created using IWebHostBuilder. In the Startup, I register multiple IHostedService singletons. When running as a console, the app starts just fine.
However, if I follow the steps described in here: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-2.2 and I try to start the app as a Windows Service, it just freezes until you get the typical error: service timed out.
Commenting out the lines in the Startup that register the IHostedService instances does the trick, and I can get the service running.
Are there any technical limitations that prevent us from using IWebHostBuilder + IHostedService + Windows Service?


text:
Q: Ancho tabla word java Tengo :
XWPFTable header = document.createTable(1 , 2);
header.getRow(0).getCell(0).setColor("dbdbdb")
header.getRow(0).getCell(0).setText("titulo")
header.getRow(0).getCell(1).setText("valor1")

Cuando genera el word el ancho de la tabla se adapta al texto, pero me gustaria darle un 30% al titulo y un 70% al valor, es posible?


text:
Q: htaccess rule giving 403 error for homepage I need the following URLs to be allowed

*

*https://www.example.com

*https://www.example.com/index.php

*https://www.example.com/login

*https://www.example.com/logout

*https://www.example.com/callback
The rule that I have added in .htaccess is:
Order deny,allow
Deny from all
<FilesMatch "login|logout|callback|index\.php">
  Allow from all
</FilesMatch>
### End

DirectoryIndex index.php

# enable apache rewrite engine
RewriteEngine on

# set your rewrite base
# Edit this in your init method too if you script lives in a subfolder
#RewriteBase /

# Deliver the folder or file directly if it exists on the server
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Push every request to index.php
RewriteRule ^(.*)$ index.php [QSA]

Then I am using Steampixel\Route package to process the request:
Route::add('/', function() {
    //code to process homepage request
});

Route::add('/login', function() {
    //code to process login request
});

Route::add('/logout', function() {
    //code to process logout request
});

Route::add('/callback', function() {
    //code to process callback request
});

Route::run('/');

URLs /login, /logout, /callback work, however, I get 403 "You don't have permission to access this resource." error when I access my homepage, either with or without / (forward slash )

A:
<FilesMatch "login|logout|callback|index\.php">

You need to allow nothing (a request for the root). However, your existing regex is also far too broad as it matches the request if these strings are contained anywhere in the first path-segment. For instance, it will also permit /foologinbar and /login/bar etc.
It would need to be like this to allow nothing and be more restrictive.
<FilesMatch "^(login|logout|callback|index\.php)?$">

You are also using the deprecated Order, Deny and Allow directives. If you are on Apache 2.4 (as I expect you are) then you should be using the equivalent Require directives instead. (But you must avoid mixing old and new directives as you can get unexpected conflicts.) So, this should be written (on Apache 2.4) like this:
Require all denied
<FilesMatch "^(login|logout|callback|index\.php)?$">
  Require all granted
</FilesMatch>

However, strictly speaking the <FilesMatch> (and <Files>) containers are for matching against physical files, not URL-paths. Consider using mod_rewrite instead to specifically match the URL-path. For example, the following should go immediately after the RewriteEngine directive:
# Block all other requests
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule !^(login|logout|callback|index\.php)?$ - [F]

Aside:

when I access my homepage, either with or without / (forward slash)

The trailing slash after the hostname is (effectively) always present on the HTTP request, regardless of whether you explicitly include this in the browser's address bar or not. What you see in the browser's address bar often masks the true request.


text:
Q: What are the parameters in this LESS sprite shorthand specification? I'm fairly new to LESS, and I have some code--which seems to work--for a sprite given to me that looks like this.  First a variable is defined as follows:
@my_img: 0px 105px 0px -105px 22px 22px 44px 150px 'sprites/sprite-img.png';

This variable gets used like this:
.someClass {
      .sprite(@my_img);
}

CSS output of this looks like this:
.someClass{
    background-image: url("sprites/sprite-img.png");
    background-position: 0 -105px;
    height: 22px;
    width: 22px;
}

What do the parameters in that variable definition indicate?  The last one (url) is obvious, and I believe from looking at the sprite that the 3rd and 4th ones seem to be the background position offsets (X and Y).  But what are the others?  What do each of the 9 elements in this variable specify?

*

*?

*?

*horizontal position

*vertical position

*width

*height

*?

*?

*background-image url

A: The comments on other answers helped make it clear that the .sprite usage is actually not part of LESS, but is a mixin definition, as follows.  So the extra stuff in the variable definition is not used in the sprite at all, but exists for other uses.
  .sprite-width(@sprite) {
    width: ~`"@{sprite}".split(', ')[4]`;
  }

  .sprite-height(@sprite) {
    height: ~`"@{sprite}".split(', ')[5]`;
  }

  .sprite-position(@sprite) {
    @sprite-offset-x: ~`"@{sprite}".split(', ')[2]`;
    @sprite-offset-y: ~`"@{sprite}".split(', ')[3]`;
    background-position: @sprite-offset-x  @sprite-offset-y;
  }

  .sprite-image(@sprite) {
    @sprite-image: ~`"@{sprite}".split(', ')[8].slice(1, -2)`;
    background-image: url(@sprite-image);
  }

  .sprite(@sprite) {
    .sprite-image(@sprite);
    .sprite-position(@sprite);
    .sprite-width(@sprite);
    .sprite-height(@sprite);
  }


text:
Q: trying to get cpu temperature systeminformation npm library im trying to get CPU temperature using systeminformation in node.js, but getting null values in the output.
i also installed sensors before getting cpu information
this application is running on AWS EC2 instance
import si from 'systeminformation'
import { execSync } from 'child_process'

let output=execSync('sudo apt-get install lm-sensors')
const temperature = await si.cpuTemperature()
console.log(temperature)

output:
{ main: null, cores: [], max: null, socket: [], chipset: null }

A: AWS EC2 won't disclose its CPU temperature. But this should work in any local machine.


text:
Q: Extjs Make some cells uneditable while modifing I am using Extjs3.2 and Row editor Plugin for Grid.I have Add,Modify and Delete Button.I have Four Cell in grid Say(id,firstname,lastname,roll no).In case of Add  all field should be editable so that he can add all four fields.But suppose if clicks one existing record and click on modify i want id field non editable.How to acheive this
Below is my code
var grid= new Ext.grid.GridPanel({
                            store : store_surv,
                            id : "grid_surv",
                            columns : [

                    {
                        header : "Id",
                        width : 120,
                        sortable : true,
                        dataIndex : 'id',
                        renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                             return  getToolTip(value, metaData, record, rowIndex, colIndex, store);
                            } ,
                        editor : {
                            xtype : 'textfield',
                            allowBlank : true
                        }
                    }
                    {
                        header : "First Name",
                        width : 120,
                        sortable : true,
                        dataIndex : 'fname',
                        renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                             return  getToolTip(value, metaData, record, rowIndex, colIndex, store);
                            } ,
                        editor : {
                            xtype : 'textfield',
                            allowBlank : true
                        }
                    }

                    {
                        header : "Last Name",
                        width : 120,
                        sortable : true,
                        dataIndex : 'lname',
                        renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                             return  getToolTip(value, metaData, record, rowIndex, colIndex, store);
                            } ,
                        editor : {
                            xtype : 'textfield',
                            allowBlank : true
                        }
                    },

                   {
                        header : "Roll No",
                        width : 120,
                        sortable : true,
                        dataIndex : 'roll',
                        renderer: function (value, metaData, record, rowIndex, colIndex, store) {

                             return  getToolTip(value, metaData, record, rowIndex, colIndex, store);
                            } ,
                        editor : {
                            xtype : 'textfield',
                            allowBlank : true
                        }
                    }                   ],

                            title : 'Student List',
                            height : 350,
                            width : 750,
                            frame : false
                        })

;

A: Add an afteredit listener to your editor object and in that listener call the setDisabled(true) method on the id textfield like this:
var idTextField = Ext.create({
    xtype : 'textfield',
    allowBlank : true
});

var editor = new Ext.ux.grid.RowEditor({
    saveText: 'Update',
    listeners: {
        afteredit: function(){
            idTextField.setDisabled(true);
        }
    }
});

And modify your existing code by replacing the old textfield with the above mentioned:
...
{
  header : "Id",
  width : 120,
  sortable : true,
  dataIndex : 'id',
  renderer: function (value, metaData, record, rowIndex, colIndex, store) {
                return  getToolTip(value, metaData, record, rowIndex, colIndex, store);
  },
  editor : idTextField
}
...

So we just changed the editor property.


text:
Q: RxBleConnection Observable is not emitting in my android repository layer I am holding a reference to the Android RxBleConnection. I also have a read write function that return an observable, my problem is that this function is being called but not it is not responding because the connection observable has stopped emitting, you can check the code bellow, any suggestions ?
class LampRepository(private val lampBleDevice: Observable<RxBleDevice>,
                 private val bluetoothExecutor: Executor) : IRepository {

companion object {
   private val TAG = "LampRepository"
}

 val  lampConnectionState:Observable<RxBleConnection.RxBleConnectionState>
 val  lampBleConnection:Observable<RxBleConnection>

init {

      lampBleConnection = lampBleDevice.subscribeOn(Schedulers.from(bluetoothExecutor))
                                      .observeOn(AndroidSchedulers.mainThread())
                                      .flatMap {
                                            Log.d(TAG,"Connecting to the lamp GATT server")
                                           it.establishConnection(true) }
                                      .compose(ReplayingShare.instance())

    lampConnectionState =  lampBleDevice.subscribeOn(Schedulers.from(bluetoothExecutor))
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .flatMap {
                                                    Log.d(TAG,"Observing the Lamp GATT server connection state")
                                                    it.observeConnectionStateChanges()}
                                        .share()
}

fun getLampLuminosityLevel()
    = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            Log.d(TAG,"Reading the lamp luminosity characteristic")
            it.readCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID))
                    ?.toObservable()}
        .flatMap {
            Observable.just(it[0].toInt()) }
        .flatMap { Observable.just(0) }
        .flatMap {
            when (it) {
                0 -> Observable.just(LampProfile.Luminosity.NON)
                1 -> Observable.just(LampProfile.Luminosity.LOW)
                2 -> Observable.just(LampProfile.Luminosity.MEDIUM)
                3 -> Observable.just(LampProfile.Luminosity.HIGH)
                4 -> Observable.just(LampProfile.Luminosity.MAX)
                else -> Observable.error(Throwable("unknown value ${it}"))
            }}

fun getLampPowerState()
    = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            Log.d(TAG,"Reading the lamp power state characteristic")
            it.readCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID))
                    .toObservable()}
        .flatMap {
            Observable.just(it[0].toInt()) }
        .flatMap {
            when (it) {
                0 -> Observable.just(LampProfile.State.OFF)
                1 ->  Observable.just(LampProfile.State.ON)
                else ->  Observable.error(Throwable("unknown value ${it}"))
            }}

fun setLampPowerState(state: LampProfile.State)
        = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
                        .observeOn(AndroidSchedulers.mainThread())
                         .flatMap {
                                    Log.d(TAG,"writing to the Characteristic")
                                 it.writeCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID), byteArrayOf(state.value.toByte()))
                                   .toObservable()}
                        .flatMap {
                            Observable.just(it[0].toInt()) }
                         .flatMap {  Observable.just(1) }
                        .flatMap {
                            Log.d(TAG,"Finish writing")
                            when (it) {
                                0 -> Observable.just(LampProfile.State.OFF)
                                1 ->  Observable.just(LampProfile.State.ON)
                                else -> Observable.error(Throwable("unknown value")) }}

fun setLampLuminosityLevel(level: LampProfile.Luminosity)
      =lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
            .flatMap {
                Log.d(TAG,"Writing the lamp luminosity characteristic")
                it.writeCharacteristic(UUID.fromString(LampProfile.LUMINOSITY_CHARACTERISTIC_UUID), byteArrayOf(level.value.toByte()))
                        .toObservable()
            }
            .flatMap {
                Observable.just(it[0].toInt())
            }
            .flatMap { Observable.just(0) }
            .flatMap {
                    when (it) {
                        0 -> Observable.just(LampProfile.Luminosity.NON)
                        1 -> Observable.just(LampProfile.Luminosity.LOW)
                        2 -> Observable.just(LampProfile.Luminosity.MEDIUM)
                        3 -> Observable.just(LampProfile.Luminosity.HIGH)
                        4 -> Observable.just(LampProfile.Luminosity.MAX)
                        else -> Observable.error(Throwable("unknown value"))
                    }
            }

}

class LampViewModel(private val lampRepository:LampRepository):ViewModel(){

companion object {
    val TAG = "LampViewModel"
}
private val  mLampPowerState:MutableLiveData<LampProfile.State> = MutableLiveData()
private val  mLampLuminosityLevel:MutableLiveData<LampProfile.Luminosity>  = MutableLiveData()
private val  mLampBleConnectionState:MutableLiveData<RxBleConnection.RxBleConnectionState>  = MutableLiveData()
private val  compositeDisposable = CompositeDisposable()

init {

    compositeDisposable.add(lampRepository.lampConnectionState.subscribe(
          mLampBleConnectionState::postValue,{
          Log.d(TAG,"error is ${it.message}")
  }))

    compositeDisposable.add(lampRepository.lampBleConnection.subscribe({
    },{

    }))

}

fun getLampLuminosityLevel():LiveData<LampProfile.Luminosity> = mLampLuminosityLevel
fun getLampPowerState():LiveData<LampProfile.State> = mLampPowerState
fun getLampConnectionState():LiveData<RxBleConnection.RxBleConnectionState> = mLampBleConnectionState

fun setLampPowerState(state: LampProfile.State) {
    Log.d(TAG,"Into the function")
  compositeDisposable.add(lampRepository.setLampPowerState(state)
        .subscribe({
            Log.d(TAG,"writing with success $it")
        },{
            Log.d(TAG,"error while writing ${it.message}")
        }))

}
fun setLampLuminosityLevel(level: LampProfile.Luminosity) {
    compositeDisposable.add(lampRepository.setLampLuminosityLevel(level)
            .subscribe({

            },{
                Log.d(TAG,"writing error")
            }))

}

class DefaultServiceLocator (private val activity: FragmentActivity): ServiceLocator {

companion object {
  private  val TAG = "DefaultServiceLocator"
}

private var blueToothClient = RxBleClient.create(activity)
private var rxPermissions = RxPermissions(activity)

private val BLUETOOTH_IO = Executors.newFixedThreadPool(2)
private val NETWORK_IO = Executors.newFixedThreadPool(1)
private val bluetoothScan:Observable<ScanResult>
private val bluetoothClientState:Observable<RxBleClient.State>
private val lampBleDevice: Observable<RxBleDevice>
private val broadLinkBleDevice: Observable<RxBleDevice>
private val broadLinkRepository:BroadLinkRepository
private val mConfig = AIConfiguration(
        "e87e26ceb2ae4519ace2f3c71abd076e",
                         ai.api.AIConfiguration.SupportedLanguages.English,
                         AIConfiguration.RecognitionEngine.System
)
private val AIDataService = AIDataService(mConfig)

init {

    bluetoothClientState =  blueToothClient.observeStateChanges()
                                           .observeOn(Schedulers.from(getBlueToothExecutor()))
                                           .subscribeOn(AndroidSchedulers.mainThread())
                                           .startWith(Observable.just(blueToothClient.state))
                                           .share()

     bluetoothScan =  bluetoothClientState.filter{it == RxBleClient.State.READY}
             .delay(1000,TimeUnit.MILLISECONDS)
             .flatMap {
                blueToothClient.scanBleDevices(
                        ScanSettings.Builder()
                                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                                .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
                                .build(),
                        ScanFilter.Builder().build())}
            .share()

    broadLinkBleDevice = bluetoothScan.filter { it.bleDevice.macAddress ==  BroadLinkProfile.DEVICE_MAC_ADDRESS}
                                      .flatMap { result ->
                                                       Log.d(TAG, "the device named ${result.bleDevice.name} is found")
                                              Observable.just(result.bleDevice) }
                                      .retry()
                                      .share()

    lampBleDevice =   bluetoothScan.filter { it.bleDevice.macAddress == LampProfile.DEVICE_MAC_ADDRESS }
                                   .flatMap { result ->
                                                  Log.d(TAG, "the device named ${result.bleDevice.name} is found")
                                          Observable.just(result.bleDevice) }
                                   .retry()
                                   .share()

    broadLinkRepository = BroadLinkRepository(broadLinkBleDevice,getBlueToothExecutor())

}

override fun getBlueToothExecutor() = BLUETOOTH_IO

override fun getNetworkExecutor() = NETWORK_IO

override fun getBleDevice(key: BleDevices): Observable<RxBleDevice> {

    return when (key) {
        BleDevices.LAMP -> lampBleDevice
        BleDevices.BROAD_LINK -> broadLinkBleDevice
    }
}

override fun getRepository(key: Repositories): IRepository {
    return when (key) {
        Repositories.LAMP_REPOSITORY -> LampRepository(
                lampBleDevice = getBleDevice(BleDevices.LAMP),
                bluetoothExecutor = getBlueToothExecutor()
        )

        Repositories.TV_REPOSITORY -> TvRepository(
                broadLinkRepository = broadLinkRepository,
                bluetoothExecutor = getBlueToothExecutor()

        )
        Repositories.AIR_CONDITIONER_REPOSITORY -> AirConditionerRepository(
                broadLinkRepository = broadLinkRepository,
                bluetoothExecutor = getBlueToothExecutor()
        )
        Repositories.DIALOG_REPOSITORY -> DialogRepository(
                AIService = AIDataService,
                networkExecutor = getNetworkExecutor()

        )
    }
}

}

A: The lampBleConnection will emit only once per connection since you are using both ReplayingShare and .share().
The ReplayingShare shares the upstream Observable subscription and emit's the last event to new subscribers. Using .share() does partially the same thing as it also shares the upstream Observable subscription rendering the ReplayingShare useless as it will be subscribed only once.
Bottom line — remove .share() from the lampBleConnection and from setLampPowerState()
The (original) below code with removed .share() should do the trick:
class LampRepository(private val lampBleDevice: Observable<RxBleDevice>,
    private val bluetoothExecutor: Executor) : IRepository {

    companion object {
        private val TAG = "LampRepository"
    }

    val  lampConnectionState:Observable<RxBleConnection.RxBleConnectionState>
    val  lampBleConnection:Observable<RxBleConnection>

    init {

        lampBleConnection = lampBleDevice.subscribeOn(Schedulers.from(bluetoothExecutor))
                              .observeOn(AndroidSchedulers.mainThread())
                              .flatMap {
                                            Log.d(TAG,"Connecting to the lamp GATT server")
                                  it.establishConnection(true) }
                              .compose(ReplayingShare.instance())

        lampConnectionState =  lampBleDevice.subscribeOn(Schedulers.from(bluetoothExecutor))
                                .observeOn(AndroidSchedulers.mainThread())
                                .flatMap {
                                            Log.d(TAG,"Observing the Lamp GATT server connection state")
                                            it.observeConnectionStateChanges()}
                                .share()

    }

    fun getLampLuminosityLevel() = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            Log.d(TAG,"Reading the lamp luminosity characteristic")
            it.readCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID))
                ?.toObservable()
        }
        .flatMap { Observable.just(it[0].toInt()) }
        .flatMap { Observable.just(0) }
        .flatMap {
            when (it) {
                0 -> Observable.just(LampProfile.Luminosity.NON)
                1 -> Observable.just(LampProfile.Luminosity.LOW)
                2 -> Observable.just(LampProfile.Luminosity.MEDIUM)
                3 -> Observable.just(LampProfile.Luminosity.HIGH)
                4 -> Observable.just(LampProfile.Luminosity.MAX)
                else -> Observable.error(Throwable("unknown value ${it}"))
            }
        }

    fun getLampPowerState() = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            Log.d(TAG,"Reading the lamp power state characteristic")
            it.readCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID))
                .toObservable()
          }
        .flatMap { Observable.just(it[0].toInt()) }
        .flatMap { Observable.just(0) }
        .flatMap {
            when (it) {
                0 -> Observable.just(LampProfile.State.OFF)
                1 ->  Observable.just(LampProfile.State.ON)
                else ->  Observable.error(Throwable("unknown value ${it}"))
            }
        }

    fun setLampPowerState(state: LampProfile.State) = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            Log.d(TAG,"writing to the Characteristic")
            it.writeCharacteristic(UUID.fromString(LampProfile.STATE_CHARACTERISTIC_UUID), byteArrayOf(state.value.toByte()))
                ?.toObservable()
        }
        .flatMap { Observable.just(it[0].toInt()) }
        .flatMap {
            Log.d(TAG,"Finish writing")
            when (it) {
                0 -> Observable.just(LampProfile.State.OFF)
                1 ->  Observable.just(LampProfile.State.ON)
                else -> Observable.error(Throwable("unknown value"))
            }
        }

    fun setLampLuminosityLevel(level: LampProfile.Luminosity) = lampBleConnection.subscribeOn(Schedulers.from(bluetoothExecutor))
        .flatMap {
            Log.d(TAG,"Writing the lamp luminosity characteristic")
            it.writeCharacteristic(UUID.fromString(LampProfile.LUMINOSITY_CHARACTERISTIC_UUID), byteArrayOf(level.value.toByte()))
                    .toObservable()
        }
        .flatMap { Observable.just(it[0].toInt()) }
        .flatMap { Observable.just(0) }
        .flatMap {
            when (it) {
                0 -> Observable.just(LampProfile.Luminosity.NON)
                1 -> Observable.just(LampProfile.Luminosity.LOW)
                2 -> Observable.just(LampProfile.Luminosity.MEDIUM)
                3 -> Observable.just(LampProfile.Luminosity.HIGH)
                4 -> Observable.just(LampProfile.Luminosity.MAX)
                else -> Observable.error(Throwable("unknown value"))
            }
        }
}


text:
Q: Solution with over 100 projects takes over five minutes to build I have a solution with over 100 projects. It takes a long time to build, and sometimes Visual Studio crashes during the build.  How can I deal with this issue and minimize the pain?  Have we gone horribly, horribly wrong somewhere?
Some background on the problem:
We are using CAB with WPF, and each module has a ui assembly and a "server" assembly, which is really just a layer for the database.  There is only one team, with about 5 developers.
I don't know how many classes or how many lines of code.

A: Your question is a bit short on specifics, but I imagine the crashing is just a workstation resource issue more than anything.  100 projects isn't a problem in itself as long as there are good reasons for having that many, but by the time you get to over 10 projects, I would hope that you have some sort of management structure in place for them.
Do you really need to be building all 100 projects, all the time?  You can switch off individual projects for building using the configuration manager, and you can create solution files with a subset of the total number of projects.
For example, we have 36 projects for one of the enterprise apps I work with.  Along with that, we have multiple solution files and configurations designed to allow our devs to load only the projects and configuration that they need in order to work with given subcomponents of the application.  In other words, they're only ever loading some subset of the 36 projects.  Our build server takes care of putting everything together.
I suggest doing some analysis on your application and finding out what you can consolidate, and what you can partition into other solution files.

A: Your question seems to have more to do with the design of your solution and less about the ability of VS to handle 100 projects.  You really want to know if the fact that your solution takes a long time is a code smell for "holy crap we have designed this wrong".
If you have a 1:1 relationship between "UI" assemblies and "Server" assemblies, they are logically the same and could be combined.
It's ok for CAB/CAG module assemblies to have all of their dependencies in one assembly in my opinion.  If you intend on sharing data access code across several modules, then it would make sense to break it out into a separate assembly.
If you decide this approach isn't appropriate, what we usually do is have several smaller solutions that allow us to test a few related modules together locally during development, but have one large solution that our build servers build out.  This way, long build times are experienced by a dedicated build machine, rather than our local dev boxes (this is a good approach for even the smallest of projects, as well).

A: Do they all need to build at the same time?  If not, you can go into the Configuration Manager and only select the ones you need built at the present time.
Although it seems to me that 100 projects in a solution is quite a bit.  Is this really necessary?  Can you break it up into smaller related solutions, or are there really this many projects that are inter-dependent on each other?

A: You can right click on an individual project in the Solution Explorer and select the option to build just that project. If there are any necessary projects in the build order, it will build those too, but this allows you to only build the necessary items.

A: The default solution configurations Debug and Release always checks all projects, and builds the ones that are not up to date. You can create your own solution configuration where you disable the build option for projects that you know doesn't need checking.