text:
Q: iPod Shuffle (3G) - new unit is producing "usb over current notice" Bought a new unit today. Seemed to be fine, synced, used it for a while.
Now whenever I plug it into a system, I either get a "usb over current notice" error, or the keyboard/mouse stops working.
MacBook (white) - all ports -> error
iMac G5 - any built-in ports -> mouse stops working
iMac G5 - keyboard ports -> error.
Any ideas? I think the problem began when the iPod finally was fully charged?

A: Seriously sounds like their is a problem with either your USB ports on the Mac or the Shuffle itself. I would suggest taking both to your nearest iStore and have them check it out.


text:
Q: How to slide down in javascript if the data posted I build a code here.. that when he\she posts a comment the JavaScript will slide down a new comment block...
But i need to refresh after click the post button - then - there will be a new comment block under a post.
This is my code:

A: assuming your script works fine, except that u need to refresh page every time...
why cant you automatically refresh that particular div without loading overall page like this...
$('#Comment"+blab_id).load('yourpage.php');

A: What is "#Comment"+blab_id ? If that is just an input field, what is blab_id?
I think what you want is something like http://jqueryui.com/demos/dialog/#modal-form , but instead of a table a bunch of divs. I would have one div id=comments that contains all the comments, then you should be able to add more comments to the bottom of this. So instead of
$("#new_comment"+blab_id).html(data);
$("#new_comment"+blab_id).slideDown(300);

you would have $("comments").append(data).fadeIn(); (According to this) (Or prepend if you want the comment to appear at the top) (I haven't checked if this works though...)
where I assume data is

    '.$comment_user.'

'.$comment_txt.'
 ·'.$whenComment.'·

which is returned from scripts/send_comment.php

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generalization of a result on finite Galois extensions to infinite case. It is well known that if $L/K$ is a finite abelian extension, $\frak p$  a prime of $K$ and $\frak P$ a prime of $L$ above  $\frak p,$ then $L^I /K$ is the maximal subextension of $L/K$ in which $\frak p$ is unramified, where $I=I(\frak P/p)$ is the inirtia group of $\frak p.$

Is it always the case for infinite abelian extensions ?

Some hints please I am sur that is true but I don't have an idea to starting,
Thanks very much for any help.


text:
Q: Update PHP cURL request from SSLv3 to TLS..? Because of the recent vulnerability discovered in SSLv3, many web service providers (ie. PayPal, Facebook, Google) are disabling that and wanting us to use TLS instead.  I'm having a little bit of trouble figuring out how to do this.
I'm currently using the following function to handle my cURL requests.
function CURLRequest($Request = "", $APIName = "", $APIOperation = "", $PrintHeaders = false)
{
    $curl = curl_init();
            curl_setopt($curl, CURLOPT_VERBOSE, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_TIMEOUT, 30);
            curl_setopt($curl, CURLOPT_URL, $this->EndPointURL);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $Request);

    if($this->APIMode == 'Certificate')
    {
        curl_setopt($curl, CURLOPT_SSLCERT, $this->PathToCertKeyPEM);
    }

    $Response = curl_exec($curl);

    /*
     * If a cURL error occurs, output it for review.
     */
    if($this->Sandbox)
    {
        if(curl_error($curl))
        {
            echo curl_error($curl).'

';
        }
    }

    curl_close($curl);
    return $Response;
}

When I try hitting PayPal's sandbox, though, where they've already disabled this, I end up with a cURL error:  error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
The info that I've found is that I just need to change this to use TLS instead of SSL, and the other answers I've seen say to simply do that by adding a curl option to my function...
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);

I've added that option, though, and I still get the exact same result.  Any information on how I can get this working would be greatly appreciated.  Thanks!

A: Copied from: SSL error can not change to TLS
Try add curl_setopt($curl, CURLOPT_SSL_CIPHER_LIST, 'TLSv1'); to your code.
This will work if you cURL is OpenSSL libssl based but not if nss based.

A: A better solution until Paypal updates its core SDK would be to override the CURLOPT_SSL_CIPHER_LIST directly in your application. This way you don't have to interfere with the sdk-core-php package directly and you will be free to upgrade it in future.
You could add something like the following to your app's bootstrap or payment processing logic:
PPHttpConfig::$DEFAULT_CURL_OPTS[CURLOPT_SSL_CIPHER_LIST] = 'TLSv1';

Just make sure you comment it thoroughly and remember to take it out later when the issue has been patched in the core.

A: I just resolved updating nss library via terminal.

A: If the above does not help, check OPENSSL version. Its likely because of OPENSSL version <= 0.9.8. Updating to PHP7 helps, which comes with higher version of OPENSSL.


text:
Q: Dimension of a vector space of functions
Where $S$ is a set, the functions $f: S \rightarrow \mathbb{R}$ form a vector space under the natural operations: the sum $f+g$ is the function given by $(f +g)(s)=f(s)+g(s)$ and the scalar product is $(r\cdot f)(s) = r\cdot f(s)$. What is the dimension of the space resulting for each domain?
(a) $S = \{1\}$ $\hspace{1mm}$ (b) $S = \{1,2\}$ $\hspace{1mm}$ (c) $S = \{1,...,n\}$

The result of my attempt at the problem is that the dimension in each case should be infinitely large. My reasoning is that the set of functions, in either (a), (b), or (c), contains the space of $n$ degree polynomials functions $\mathscr{P}_n$, as any polynomial function takes values in all mentioned domains and returns a value in $\mathbb{R}$. Since $\mathscr{P}_n$ has an infinitely large dimension, as $n \in \mathbb{N}$ and $\mathbb{N}$ (the set of natural numbers) is infinitely large, the basis of the space containing $\mathscr{P}_n$ is infinitely large, and so must be the bases for the spaces in question. Therefore, the spaces in question have infinitely large dimensions.
However, the solution to the problem is
(a) dimension $ =1$
(b) dimension $ =2$
(c) dimension $ =n$
I see how the solutions apply to each case but my question is why? Where in my reasoning am I making a mistake? Thank you in advance.

A: Hint:
For the general case $S=\{1,...,n\}$, prove that the functions $f_1,...,f_n$ defined as
$f_i(i)=1$ and $f_i(j)=0$ for $i\neq j$, forms a basis.
In other words, show that $f_1,...,f_n$ are linearly independent and that for any function $g:S\rightarrow \mathbb{R}$, we can write $g$ as $\alpha_1f_1 + \alpha_2f_2 + ... + \alpha_nf_n$ for suitable $\alpha_1,...,\alpha_n$.

A: How can a polynomial belong to those spaces? If you are talking about polynomial functions, then you are making a mistake. Consider, for instance, the polynomial functions $x^n$ ($n\in\mathbb N$). They are all distinct as functions from $\mathbb R$ into $\mathbb R$. But they become all the same function if you restrict them to $\{1\}$!


text:
Q: bootstrap4 carousel - stop slide in 'slide.bs.carousel' event I am trying to have two steps with bootstrap4 carousel:

*

*First carousel item is for authentication (it username and password fields)

*Second one is for authorization (lists the groups that the user has access and asks him to choose one)

I want to check if the user id and password is valid before moving to the next slide by javascript code. I have .carousel('pause') but I cannot prevent moving to the next slide. Also I do not want to have an extra button to check the contents.
$('#myCarousel').on('slide.bs.carousel', function (e) {
    // authentication check here

    if (isAuth === false)
    {
        // stay on this slide
    }
    else
    {
        // move the next one
    }

})

Is there any way for doing that?
Note: I disabled auto sliding by setting data-interval="false". The user navigates between slides manually i.e. by clicking or by arrow keys.

A: To stop the slide once the slide.bs.carousel event has been triggered, call preventDefault() on the event variable. This applies to slide events triggered both automatically and manually.
$('#myCarousel').on('slide.bs.carousel', function (e) {
    // checks here
    if (stop) {
        e.preventDefault();
    }
})

See here for the relevant bits from the Bootstrap source.
If you have automatic cycling enabled, this will also allow you to pause the carousel, as it won't automatically resume later in the slide function (see here).
See here for an example (JSFiddle).

A: Use this way:
$('#myCarousel').on('slide.bs.carousel', function (e) {
// authentication check here

if (isAuth === false)
{
   $('#myCarousel').carousel('pause');
   return false; // stay on this slide
}
else
{
   $('#myCarousel').carousel('cycle');
   return true; // move the next one
}

})


text: Q: Function of canonical correlations of two vectors Let the random vector $X = \{X^T_1,X^T_2\}$. Lets say that $G$ is transformation group such that $G = \{Y = Y_1^T, Y_2^T\mid Y_i=A_i X_i+b_i, i=1,2\}$, where $A_1,A_2,(b_1,b_2)$ can take any value from the set of non-random matrices(vectors). How to show that any function invariant to $G$ i.e $\forall$ $Y\in G$ $f(EX,DX) = f(EY,DY)$, is a function of canonical correlations of vectors $X_1$ and $X_2$?


text:
Q: In Rails 5 Api, how do you match an error message to the request json? Sorry if the question is hard understand, but let's say that i have a model Post with an has_many relation to Comments and some validation on the Comments model. Set up like this:
class Post < ApplicationRecord
    validates :title, presence: true, length: {minimum: 3, maximum: 20}, uniqueness: true
    has_many :comments, inverse_of: :post
    accepts_nested_attributes_for :comments
end

class Comment < ApplicationRecord
    validates :message, presence: true, length: {minimum: 3, maximum: 20}, uniqueness: true
    belongs_to :post
end

When I create a new Post, i want to also create one or moreComment(s). (odd, I know)
I do it with this JSON, which have the Comments in an object(instead of array) so that I can set some uuids to the Comments and map it back in the frontend.
{
"post": {
        "comments_attributes": {
            "97b1770c-0798-41d9-9a6c-f31ffeb22048": {
                "title": ""
            },
            "244fbca6-4a73-44dc-8d9d-26cc169ee757": {
                "title": "The first wont pass validation"
            }
        },
        "title": "A title off a post, with prefilled comments(?!)"
    }
}

I take the params, permit check and then save it in the same fashion as I received them in, and then try to save. When the save fails i return
render json: @post.errors, status: :unprocessable_entity

the returing error message is like this:
"comments.title":["is too short (minimum is 3 characters)"]}

How can I associate which of the comments that where invalid?
Of course, a thing such as string length is something that can be handled in the frontend as well, but if it where something that required a unique input it would be more difficult to map it to what object in the JSON that i was suppose to save.

A: *

*remove the  "comments_attributes" from your params

*save the post without comments -> bail out if there are errors here

*loop over your comments and try to add them one by one,
all the while collecting the errors


text:
Q: Why does this code for initializing a list of lists apparently link the lists together? I intend to initialize a list of list with length of n.
x = [[]] * n

However, this somehow links the lists together.
>>> x = [[]] * 3
>>> x[1].append(0)
>>> x
[[0], [0], [0]]

I expect to have something like:
[[], [0], []]

Any ideas?

A: The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want
[[]]*n is similar to
l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:
x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object

In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time


text:
Q: A story about a super soldier name Lambda 602 I'm looking for a novel where the main character is a super-soldier called Lambda 602 who's just like Master Chief from Halo.
He is transported to fantasy world, where he became a familiar their that he believes that its his commander

A: This is the web-novel 'Blessed are the Simple' by naturalpinkflamingo.

Blessed are the Simple tells the story of Lambda Six-Oh-Two, a human
  supersoldier unwittingly summoned by the young elf maiden Elenore
  Redwing. Thrown into a fantasy world of magic, elves, and beast-men,
  Lambda copes by following his programming, which means following
  orders and utilizing military force to handle his problems. Meanwhile,
  Elenore quickly realizes that Lambda is a human war machine whose
  self-proclaimed mission is to "protect and follow her orders," and
  must quickly figure out how to deal with a being whose sole purpose is
  to fight. Follow the adventures of the least-likely familiar and his
  elven commander as they make friends, battle monsters, and perhaps
  save the world.


text:
Q: How do I remove the numeral sign? I am writing in greek and I would like to create an enumerate list with custom alph or Alph label, by removing the accent after each letter so that "α'. " will become "α." etc. My attempt was this:
\documentclass[a4paper,11pt,twocolumn]{article}
\usepackage[no-math,cm-default]{fontspec}
\usepackage{xunicode}
\usepackage{xgreek}
\usepackage{enumitem}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont[Mapping=tex-text,Numbers=Lining,Scale=1.0,BoldFont={Times New Roman Bold}]{Times New Roman}
%---------------------------------
\makeatletter
\renewcommand*{\@alph}[1]{%
  \ifcase#1\or α\or β\or γ\or
    δ\or ε\or στ\or ζ\or η\or θ\or ι\or κ\or
    λ\or μ\or ν\or ξ\or ο\or π\or ρ\or σ\or
    τ\or υ\or φ\or χ\or ψ\or
    ω\else\@ctrerr\fi
}
\renewcommand*{\@Alph}[1]{%
  \ifcase#1\or Α\or Β\or Γ\or
    Δ\or Ε\or ΣΤ\or Ζ\or Η\or Θ\or Ι\or Κ\or
    Λ\or Μ\or Ν\or Ξ\or Ο\or Π\or Ρ\or Σ\or
    Τ\or Υ\or Φ\or Χ\or Ψ\or
    Ω\else\@ctrerr\fi
}
\makeatother
%--------------------------------

\begin{document}
\begin{enumerate}[label=\alph*.]
\item \item \item \item \item \item \item \item \item \item \item
\end{enumerate}
\begin{enumerate}[label=\Alph*.]
\item \item \item \item  \item \item \item \item \item \item \item
\end{enumerate}
\end{document}

But when I have a list with more than 10 items the enumeration is wrong. For example number 11 in greek numbering is "ια" and not "κ"(=20). How can I remove the accent without changing the sequence of the letters?

A: You can use the method suggested for Problem with changing enumeration
\documentclass[a4paper,11pt,twocolumn]{article}

\usepackage[no-math]{fontspec}
\usepackage{xgreek}
\usepackage{enumitem}
\usepackage{etoolbox}

\setmainfont[
  BoldFont={Times New Roman Bold},
]{Times New Roman}

\makeatletter
\renewrobustcmd{\anw@true}{\let\ifanw@\iftrue}
\renewrobustcmd{\anw@false}{\let\ifanw@\iffalse}\anw@false
\newrobustcmd{\noanw@true}{\let\ifnoanw@\iftrue}
\newrobustcmd{\noanw@false}{\let\ifnoanw@\iffalse}\noanw@false
\renewrobustcmd{\anw@print}{\ifanw@\ifnoanw@\else\numer@lsign\fi\fi}
\newrobustcmd{\noanw}{\noanw@true}
\makeatother

\begin{document}
\begin{enumerate}[label=\noanw\alph*.]
\item \item \item \item \item \item \item \item \item \item \item
\end{enumerate}
\begin{enumerate}[label=\noanw\Alph*.]
\item \item \item \item  \item \item \item \item \item \item \item
\end{enumerate}
\end{document}

Note: I removed all the useless declarations in your code.
If you want to always suppress the numeral sign without using \noanw, change the code between \makeatletter and \makeatother into
\makeatletter
\renewrobustcmd{\anw@true}{\let\ifanw@\iffalse}
\renewrobustcmd{\anw@false}{\let\ifanw@\iffalse}\anw@false
\newrobustcmd{\noanw@true}{\let\ifnoanw@\iffalse}
\newrobustcmd{\noanw@false}{\let\ifnoanw@\iffalse}\noanw@false
\renewrobustcmd{\anw@print}{\ifanw@\ifnoanw@\else\numer@lsign\fi\fi}
\makeatother


text:
Q: Can I reuse AD accounts set as SharePoint service accounts in other instances of SharePoint? I'm currently installing a SharePoint 2013 Farm using an AD domain that currently already has a totally separate SharePoint installation.  I was just curious if i could reuse the service accounts already created?
Thanks in advance.

A: Yes you can use same set of services accounts. But there is some risk involved in this approach. We used the same concept but after couple of months we have to separate it(one unique set for each farm).
Let's say, you have to change the password of the accounts once per year or less( as per the security policy or group policy).In this case you have to change the password for the Farm admin account, If you change in the one farm other farm will goes down or lock the account after bad password. one locked account bring both farms down.
So i recommend, you should use separate Farm Admin account(which runs the Central admin app & timer service) and app Pool account.
account like Object cache, or other services configuration(UPA Sync, MMS) can be shared.


text:
Q: WoW Weakaruas Tracking Multiple Enemy Units In World of Warcraft I've been working on a Weakaura for a little while now that will track how many enemy units are alive that the player has damaged. One of the major issues this runs into is that while in a group COMBAT_LOG_EVENT_UNFILTERED forces the aura to fire any time someone in your group performs an action, which can cause a lot of dropped frames. The only other option that I've been able to come across is COMBAT_LOG_EVENT, however this wont trigger when an enemy has died and so it wouldn't be removed from the list.
My Questions: is there any way to gather this data on a thread other than the UI thread to prevent dropped frames? While gathering this data on another thread will the data be able to be used to display information to the user?
Below are the currently used triggers (these all work as expected)
Trigger 1
Type - Custom
Event Type - Event
Event(s) - COMBAT_LOG_EVENT_UNFILTERED
Custom Trigger:
function(...)
    ADDS = ADDS or {}; -- Where enemy units are stored

    local _, _, event, _, src, _, _, _, dest, _, _, _ = select(1, ...);
    local player = UnitGUID("player");

    -- Attempts to only read data coming from the player casting harmful abilities
    if ((event == "SPELL_DAMAGE") and (src == player)) then

        -- Checks if the enemy unit is already being tracked and that it is NOT
        -- a part of your group (prevents friendly fire events from adding a friendly
        -- unit to this list)
        if ((not tContains(ADDS, dest)) and (not tContains(GROUP, dest))) then
            table.insert(ADDS, dest);
        end
    elseif event=="UNIT_DIED" then -- Remove a unit if it has died
        for i = #ADDS, 1, -1 do
            if ADDS[i] == dest then
                table.remove(ADDS, i);
            end
        end
    end

    return true;
end

The above block of code is the cause of the frames being dropped. The next trigger is merely a means to reset the list when combat starts or ends (pretty certain that nothing in this block is causing dropped frames but wanted to include it just in case).
Trigger 2
Type - Custom
Event Type - Event
Event(s) - PLAYER_REGEN_DISABLED, PLAYER_REGEN_ENABLED
function(...)
    GROUP = GROUP or {};

    local size = GetNumGroupMembers();

    if (size == 0) then
        GROUP = {};
    end

    if (size ~= #GROUP and size ~= 0) then
        for i = 1, size do
            local name = GetRaidRosterInfo(i);

            if (name ~= nil) then
                local guid = UnitGUID(name);

                if (not tContains(GROUP, guid)) then
                    table.insert(GROUP, guid);
                end
            end
        end
    end

    ADDS = {};
    return true;
end


text:
Q: Blend 2 bitmaps I have 2 buffers pointing to RGB32 images of different sizes, so my idea is to scale one buffer to match the other one and alphablend these images.
Currently I am able to mix StretchBlt (for scaling performance) and GDI+ drawimage function with a colormatrix for alphablending. This seem to be a bit slow and also it has issues with buffer being used by a different component that uses DirectX. For buffer issue I tried to copy the rows in reverse order and it works except in the DirectX related component.
Bitmap bmp1(width, height, 4bytesperpixel, RGB32, bufferpointer1);
Bitmap blend(width, height, 4bytesperpixel);
Graphics g(&newbmp)

using GDI function
Bitmap bmp2(scaleWidth, scaleHeight, 4bytesperpixel, RGB32, bufferpointer2)
HDC memdc = g.GetHDC();

////  scaling the bufferpointer2 to actual width & height
StretchDIBits(memdc, x,y, width, height, 0, 0,scaleWidth, scaleHeight, bufferpointer2,..)
g.ReleaseDC(memdc); // so that content is copied to the bitmap

//// Then alphablending bmp1 on top of the scaled imaged bmp2
//// Using lockbits to copy the bitmap bytes and unlocking it.

So I would need to replace the GDI+ functions and use Win32 function like AlphaBlend for this. I tried something like this and it shows a black screen
    BITMAPINFO bminfo1 = {};
    bminfo1.bmiHeader.biSize = sizeof( BITMAPINFO );
    bminfo1.bmiHeader.biWidth = w;
    bminfo1.bmiHeader.biHeight = h;
    bminfo1.bmiHeader.biBitCount = m_nBytesPerPixel * 8;
    bminfo1.bmiHeader.biCompression = BI_RGB;
    bminfo1.bmiHeader.biPlanes = 1;

    BITMAPINFO bminfo2 = {};
    bminfo2.bmiHeader.biSize = sizeof( BITMAPINFO );
    bminfo2.bmiHeader.biWidth = sW;
    bminfo2.bmiHeader.biHeight = sH;
    bminfo2.bmiHeader.biBitCount = m_nBytesPerPixel * 8;
    bminfo2.bmiHeader.biCompression = BI_RGB;
    bminfo2.bmiHeader.biPlanes = 1;

    char* pBytes1, *pBytes2;

    HDC hmemdc1 = CreateCompatibleDC(GetDC(0));
    HDC hmemdc2 = CreateCompatibleDC(GetDC(0));

    HBITMAP hBitmap1 = CreateDIBSection(hmemdc1, &bminfo1, DIB_RGB_COLORS, (void**) &pBytes1, NULL, 0);
    SetDIBits(hmemdc1, hBitmap1, 0, bminfo1.bmiHeader.bih, pBuffer[0], &bminfo1, DIB_RGB_COLORS);

    HBITMAP hBitmap2 = CreateDIBSection(hmemdc2, &bminfo2, DIB_RGB_COLORS, (void**) &pBytes2, NULL, 0);
    SelectObject(hmemdc2,hBitmap2);
    StretchDIBits(hmemdc2, 0, 0, w, h, 0, 0,
        sW, sH, pBuffer[1], &bminfo2, DIB_RGB_COLORS, SRCCOPY );

    BLENDFUNCTION bStruct;
    bStruct.BlendOp = AC_SRC_OVER;
    bStruct.BlendFlags = 0;
    bStruct.SourceConstantAlpha = 255;
    bStruct.AlphaFormat = AC_SRC_ALPHA;

    SelectObject(hmemdc1,hBitmap1);
    SelectObject(hmemdc2,hBitmap2);

    //blend bmp2 on bmp1
    BOOL res = AlphaBlend(hmemdc1, 0, 0, w, h, hmemdc2, 0, 0, w, h, bStruct);

    //for testing output
    SelectObject(hmemdc1,hBitmap1);
    BitBlt(GetDC(0),0,0,width,height,hmemdc1,100,100,SRCCOPY);

    //copy the bitmap buffer
    memcpy(out, pBytes1, (w * m_nBytesPerPixel) * h);

I am not sure if it is possible to use AlphaBlend function to mix bitmaps per-pixel based from 2 memory DCs. Any help would be highly appreciated.

A: This part is wrong:
bminfo1.bmiHeader.biSize = sizeof( BITMAPINFO );

It should be sizeof(BITMAPINFOHEADER) otherwise it ruins everything. Also you can't use GetDC(0) for any proper painting. Use instead:
HDC hdc = GetDC(hwnd);
...
ReleaseDC(hwnd, hdc);

or use HDC from BeginPaint. Since you are using GDI+ then you must have HBITMAP handles from bmp->GetHBITMAP(), there is no reason to convert to memory and back to HBITMAP
For AlphaBlend set SourceConstantAlpha = 128; in case alpha channel is not set.
void blend(HDC hdc, RECT rc, HBITMAP hbitmap1, HBITMAP hbitmap2)
{
    HDC memdc1 = CreateCompatibleDC(hdc);
    HDC memdc2 = CreateCompatibleDC(hdc);

    BITMAP bmp1, bmp2;
    GetObject(hbitmap1, sizeof(BITMAP), &bmp1);
    GetObject(hbitmap2, sizeof(BITMAP), &bmp2);

    SelectObject(memdc1, hbitmap1);
    SelectObject(memdc2, hbitmap2);

    BLENDFUNCTION blend = { 0 };
    blend.SourceConstantAlpha = 128;

    SetStretchBltMode(hdc, COLORONCOLOR);
    AlphaBlend(memdc2, 0, 0, bmp2.bmWidth, bmp2.bmHeight, memdc1, 0, 0, bmp1.bmWidth, bmp1.bmHeight, blend);
    StretchBlt(hdc, 0, 0, rc.right, rc.bottom, memdc2, 0, 0, bmp2.bmWidth, bmp2.bmHeight, SRCCOPY);

    //or create another memdc to get dibs

    DeleteDC(memdc1);
    DeleteDC(memdc2);
}

In case you want to get dibs, then don't draw on hdc, instead create a third memdc and another HBITMAP, then use GetDIBits
HDC memdc = CreateCompatibleDC(hdc);
HBITMAP hbmp = CreateCompatibleBitmap(hdc, rc.right, rc.bottom);
SelectObject(memdc, hbmp);
SetStretchBltMode(memdc, COLORONCOLOR);
StretchBlt(memdc, 0, 0, rc.right, rc.bottom,
    memdc2, 0, 0, bmp2.bmWidth, bmp2.bmHeight, SRCCOPY);

int w = rc.right;
int h = rc.bottom;
BITMAPINFOHEADER bmpInfoHeader = { sizeof(BITMAPINFOHEADER) };
bmpInfoHeader.biWidth = w;
bmpInfoHeader.biHeight = h;
bmpInfoHeader.biBitCount = 32;
bmpInfoHeader.biCompression = BI_RGB;
bmpInfoHeader.biPlanes = 1;

DWORD size = w * 4 * h;
char *dib = new char[size];
GetDIBits(hdc, hbmp, 0, h, dib, (BITMAPINFO*)&bmpInfoHeader, DIB_RGB_COLORS);
...
DeleteDC(memdc);
DeleteObject(hbitmap);
delete[]dib;

Edit
Method 2: This method should be faster because it uses one StretchBlt and one AlphaBlend. This way you can use pre-computed alphas, although it's not necessary.
Use the other method with 2 AlphaBlend only if you want to blend both images with background.
void modify_bits(HDC hdc, HBITMAP hbitmap)
{   //expecting 32-bit bitmap
    BITMAP bm = { 0 };
    GetObject(hbitmap, sizeof(bm), &bm);
    int w = bm.bmWidth;
    int h = bm.bmHeight;
    BITMAPINFOHEADER bmpInfoHeader = { sizeof(BITMAPINFOHEADER),
        w, h, 1, 32, BI_RGB, 0, 0, 0, 0, 0 };
    BYTE* bits = new BYTE[w * h * 4];
    if (GetDIBits(hdc, hbitmap, 0, h, bits, (BITMAPINFO*)&bmpInfoHeader, DIB_RGB_COLORS)) {
        BYTE* p = bits;
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                p[3] = 128;
                p[0] = p[0] * p[3] / 255;
                p[1] = p[1] * p[3] / 255;
                p[2] = p[2] * p[3] / 255;
                p += 4;
            }
        }
        SetDIBits(hdc, hbitmap, 0, h, bits, (BITMAPINFO*)&bmpInfoHeader, DIB_RGB_COLORS);
    }
    delete[] bits;
}

void blend2(HDC hdc, RECT rc, HBITMAP hbitmap1, HBITMAP hbitmap2)
{
    int w = rc.right;
    int h = rc.bottom;

    modify_bits(hdc, hbitmap2);

    HDC memdc1 = CreateCompatibleDC(hdc);
    HDC memdc2 = CreateCompatibleDC(hdc);

    BITMAP bmp1, bmp2;
    GetObject(hbitmap1, sizeof(BITMAP), &bmp1);
    GetObject(hbitmap2, sizeof(BITMAP), &bmp2);
    int w1 = bmp1.bmWidth;
    int h1 = bmp1.bmHeight;
    int w2 = bmp2.bmWidth;
    int h2 = bmp2.bmHeight;

    SelectObject(memdc1, hbitmap1);
    SelectObject(memdc2, hbitmap2);

    BLENDFUNCTION blend = { 0 };
    blend.BlendOp = AC_SRC_OVER;
    blend.BlendFlags = 0;
    blend.SourceConstantAlpha = 255;
    blend.AlphaFormat = AC_SRC_ALPHA;

    SetStretchBltMode(hdc, COLORONCOLOR);

    //draw first image normally:
    StretchBlt(hdc, 0, 0, w, h, memdc1, 0, 0, w1, h1, SRCCOPY);

    //AlphaBlend the second image:
    AlphaBlend(hdc, 0, 0, w, h, memdc2, 0, 0, w2, h2, blend);

    DeleteDC(memdc1);
    DeleteDC(memdc2);
}


text:
Q: How do I add new line in olx.style.TextOptions text? I have to create label with 2 rows.
in OL 2 I've did it by adding '\n' in the text label but it seems that ol3 doesn't support it:
 new ol.style.Style({
            text : new ol.style.Text(/** @type {olx.style.TextOptions} */ ({
                text:'line 1 \n line 2'
            }))
        })

How can I break the line between 1 & 2 ?

A: There is no support in the library currently but people have discussed solutions in the ol3-dev Google group as well as pull requests such as: https://github.com/openlayers/ol3/pull/3538


text:
Q: ObserveEvent doesn't run the code the way I'd like it to I would like to make sure that when we click on the button button we send in the verbatimTextOutput, 1 then we pause for 2s and at the end we send 2.
But what I get is a pause for 2s then it sends 1 and 2.
How can I do that ?
library(shiny)

ui <- fluidPage(
  verbatimTextOutput("output", placeholder = TRUE),
  actionButton("b", "button")
)

server <- function(input, output, session) {

  o  <- reactiveVal("--- Hello ---")

  output$output <- renderText(o())

  observeEvent(input$b, {

    o(c(o(), "\n", "- 1 "))
    Sys.sleep(2)
    o(c(o(), "\n", "- 2 "))

  })

}

shinyApp(ui, server)

A: It's possible to do with delay() from shinyjs
library(shiny)
library(shinyjs)

ui <- fluidPage(
    useShinyjs(),
    verbatimTextOutput("output", placeholder = TRUE),
    actionButton("b", "button")
)

server <- function(input, output, session) {

    o  <- reactiveVal("--- Hello ---")

    output$output <- renderText(o())

    observeEvent(input$b, {
        o(c(o(), "\n", "- 1 "))
        delay(2000, o(c(o(), "\n", "- 2 ")))
    })
}

shinyApp(ui, server)

A: library(shiny)
library(magrittr)

ui <- fluidPage(
  verbatimTextOutput("output", placeholder = TRUE),
  actionButton("b", "button")
)

server <- function(input, output, session) {

  v  <- reactiveValues(msg = "--- Hello ---",start = 0)

  output$output <- renderText({
    v$msg
  })

  observeEvent(input$b,{
    v$msg <- paste0(v$msg,"\n","- 1 ")
    v$start <- v$start + 1
  })

  start <- reactive({
    v$start
  })

  start_d <- start %>% debounce(50)

  observeEvent(start_d(),{
    req(start_d() > 0)
    Sys.sleep(2)
    v$msg <- paste0(v$msg,"\n","- 2 ")
  })
}

shinyApp(ui, server)


text:
Q: Why there are so much restriction on LONG datatype in Oracle Why there are so much restrictions on LONG datatype in Oracle? Why it is recommended to use CLOB instead of LONG?

A: Up to Oracle 7, LONG and LONG RAW were the only data types available to store large amounts of data. The restrictions on LONGs have always been there, and always made using them difficult.
Oracle added large object support in Oracle 8i as a superior data type to replace the old types. Generically these are LOBs, with CLOB superseding LONG, and BLOB superseding LONG RAW (plus BFILE etc.). The current document still explains some of the benefits in the "Why not use LONGs?" section:

*

*LOB Capacity: LOBs can store much larger amounts of data. LOBs can store 4GB of data or more depending on you system configuration. LONG and LONG RAW types are limited to 2GB of data.

*Number of LOB columns in a table: A table can have multiple LOB columns. LOB columns in a table can be of any LOB type. In Oracle Database Release 7.3 and higher, tables are limited to a single LONG or LONG RAW column.

*Random piece-wise access: LOBs support random access to data, but LONGs support only sequential access.

*LOBs can also be object attributes.

From 12c you can have VARCHAR2 columns of up to 32k, as @thatjeffsmith mentioned in a comment; which will cover a lot of places CLOBs have had to be used in the past where 4k just wasn't quote enough.
Your question seems to imply that Oracle has added restrictions to LONGs. That isn't the case, and you're looking at it the wrong way around. LOBs were introduced partly to overcome the restrictions that LONGs already had, and the LONG data types are only kept for backward compatibility. Anything written since 8i should be using LOBs, and anything older than that should at least have considered converting LONGs to LOBs by now. (Despite the data dictionary still using LONGs internally...)
I'd suggest that if you don't have to maintain a legacy system that is stuck with LONG columns you can pretty much forget about them - don't be tempted to use them in new tables, and there isn't really much point now even playing aroud with them.


text:
Q: quick approach to migrate classic asp project to asp.net Recently we got a requirement for converting a classic asp project to asp.net.
This one is really a very old project created around 2002/2003. It consists of around 50 asp pages. I found very little documentation for this project, FSD and design documents for only a few modules.
Just giving a quick look into this project my head start to hurt. It is really a mess. I checked the records and found none of the developers who worked on this project work for the company anymore.
My real pain is that this is an urgent requirement and I have to provide an estimated deadline to my supervisor.
I found a similar question classic-asp-to-asp-net, but I need some more insight on how to convert this classic asp project to asp.net in the quickest possible way.

A: Well an estimate is not a promise. Just let your boss know that any estimate you make about codebase you don't know and a technology you don't know is going to be very inaccurate. Make him aware of the risk level.
What makes the conversion so urgent? Perhaps you can add something to the existing codebase to remove the urgency and buy yourself time for a proper port?
Some tips:

*

*Map out what the system does before touching it. Create a test script that you can use to check all the features. You are bound to make mistakes, try to find them fast. Perhaps it will reveal parts you don't need to port.

*Setup an IIS application that runs asp and asp.net side-by-side. Then attempt to port page for page while keeping the thing as a whole working (you may need to put the .NET bits in a separate virtual directory under the same path, I forgot).

*First attempt a near line-by-line port for as much as possible before you start to redo or redesign parts of the code. ASP.NET WebForms aspx pages are the best fit for this. I would not port to MVC, which does not have a page based model.

*Just stick with ASP's inline code style as you move the code over to the ASPX pages. Ignore ASPX's code behind or move some trivial unshared functions to it.

*For pages you ported create a routing rule to redirect X.asp requests to X.aspx transparently.

*If code is in VBscript then consider porting to VB.NET, you can keep a lot of the typeless stuff around (option strict off). If it's jscript, go for C#, dynamic and type inference is your friend there.

*ASP pages typically use COM components as libraries. You can usually keep using those dependencies from .NET even if there are better ways in the BCL. If you can initially postpone migrating libraries do so.

*Examine each page and the pattern within, is it mostly disjoint with other pages or is it using some include based scheme to setup code modules and such. Such included ASP pages might be directly convertable to class files. Typically classes with only static methods (modules in VB.NET).

*Only after completing the line-by-line port start doing redesign. Probably best to make a plan once you get there, you'll know a lot more about the codebase. Now is the time to start modernizing.
I've worked with a system where a similar conversion was half done. Parts were .NET, parts were classic ASP. It could be a valid strategy, port the pages you have new requirements for and nothing more. Eventually the classic ASP all get converted or lesser useful ones fade away.
It ain't gonna be 'quick', trust me ;-)


text:
Q: Loop through JavaScript object and return new object with modified value I have an object which I am forming with all the input values from a form. I want to go through the object and change all the input value to lowercase before I make a post request to the backend. I want to write a function that takes that object and returns a new object with lowercase value
const obj = {name: 'Test', city: 'London'}
const modifiedObj = myFunction(obj)

modifiedObj should be:
{name: 'test', city: 'london'}

A: You can use Object.keys to get the keys of your object, then iterate through them and access each property.

function myFunction(object){
  const newObj = {};
  cons keys = Object.keys(object);
  for(const key of keys){
    if(typeof object[key]!=="string"){
      newObject[key] = object[key];
      continue;
    }
    newObj[key] = object[key].toLowerCase();
  }
  return newObj;
}


text: Q: This appeared when i was executing a python file in pycharm terminal Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.


text:
Q: error: pointer to incomplete class type is not allowed I am stumped at this step while implementing a ternary tree:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct tnode *Tptr;
    typedef struct node
{
    char splitchar;
    Tptr lokid,eqkid,hikid;

}Tnode;

int research(Tptr p,char *s)
{
    if (!p) return 0;
    if (*s<p->
}

int main(){
    return 0;
}

When I move the mouse icon near the p, it shows me a red color and error:
pointer to incomplete class type is not allowed

My question is exactly what is an incomplete class? Please help me, thanks.

A: incomplete class (or type) is the type that is forward declared, but is not defined. Just like your tnode.
Probably you should replace node by tnode as the tag of structure in your example to get what you need.

A: You've typedef'd Tptr as a struct tnode *, but tnode is  not defined or even declared.  Perhaps you meant to name your node struct tnode instead?
BTW, there's an easy way to keep that from happening in the future...
typedef struct tnode {
    ...
} Tnode, *Tptr;

At that point, Tptr is always an alias to the correct type, even if you change tnode's name to something else.

A: "incomplete class type" suggests that your compiler believes this is C++ code rather than C code, since C does not have classes.
Note that line 5 makes Tptr a name for struct tnode *—pointer to a struct named "tnode", not "node" but "tnode", lowercase t, node.  Line 6 starts a typedef, then starts defining a struct named "node", no "t", just "node".  Line 11 finishes off the definition of "struct node", and then supplies a name for the earlier typedef: "Tnode", uppercase T, node.
You have four different names here now: Tptr, Tnode, tnode, and node.  The one with a lowercase "t" has never been "completed", so it's an "incomplete type" (but not class, because C does not have classes).


text:
Q: Add space in the bottom of chrome dev console Each Time I'm using this console I'm struggeling with my mouse to click on the editable line.
So two question :

*

*Is there a way of enlarging this line so it easier to click on it ?

*Is there a command to navigate to it ?

A: The only way to enlarge it is to create a custom theme for DevTools, enable the experiment for using custom themes, and then installing your extension. That way you can get custom CSS into the top-level DevTools scope to modify things.
You may open a bug report on the chromium issue tracker against the DevTools so the team can assess the UX to see if there is anything they should modify internally.


text:
Q: Ansible 2.9.10 error: "msg" "Invalid become method specified, could not find matching plugin: 'disable' While running a YML Ansible Playbook, I get the following error.
fatal: [192.168.0.120]: FAILED! => {"msg": "Invalid become method specified, could not find matching plugin: 'disable'. Use `ansible-doc -t become -l` to list available plugins."}

My Ansible file is quite simple
- name: CONFIG FGT HOSTNAME AND INTERFACE
  hosts: FortiManager
  connection: httpapi
  gather_facts: False

  tasks:

  - name: CONFIRM AUTHORIZE UNAUTHORIZED FMG DEVICE
    pause:
      prompt: "Do you want to add FGT-ISFW as an authorized device?"
      echo: "yes"

I run the "ansible-doc -t become -l" commmand, but I don't see anything related to the msg message and am unsure what to do next.
# ansible-doc -t become -l enable
ksu        Kerberos substitute user
pbrun      PowerBroker run
enable     Switch to elevated permissions on a network device
sesu       CA Privileged Access Manager
pmrun      Privilege Manager run
runas      Run As user
sudo       Substitute User DO
su         Substitute User
doas       Do As user
pfexec     profile based execution
machinectl Systemd's machinectl privilege escalation
dzdo       Centrify's Direct Authorize

Any suggestions? I am running Ansible 2.9.10
# ansible --version
ansible 2.9.10
  config file = /home/fortinet/downloads/FMG-Ansible-Testing/ansible.cfg
  configured module search path = [u'/opt/ansible/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]

A:
Q: "FAILED! => {"msg": "Invalid become method specified, could not find matching plugin: 'disable'.}"

A: According to the error message, it's a misconfiguration. There is no disable become plugin. For example, this is wrong
    become_method: disable

To disable privilege escalation use DEFAULT_BECOME. For example (this is the default)
    become: false

The hard part is to find where the misconfiguration comes from. You're looking for DEFAULT_BECOME_METHOD. Take a look at the configuration
shell> ansible-config dump --changed-only

If it's not there take a look at inventory, group_vars, and host_vars. Search become_method.


text:
Q: Difference between "Security Configuration Manager" and "Security Configuration Wizard" I want some clarifications about differences between SCW and SCM.
strictly Speaking when I use SCM baseline for specific Server Role (domain controller, ftp server, ...), I get for example 200 gpo's and when I use scw for same server role, I get 300 gpo's. And between these gpo's there are very little similarity (after comparing these two gpo's).
Is not this a contradiction? if no, what is the justification?
Thanks in advance...


text:
Q: Speedup restore of 160 GB SQL in 24 core + Optane NVME system i set up a new sql-server, ubuntu 18.4 (MYSQL 5.7), 24 core (48 threads), 256G RAM, System is SATA Raid1 XFS SSD /var/lib/ is mounted on Optane SSD XFS.
In restore i can see that the server has unter 1.0 load so it is quit sleeping. I dont know what i can improve to speedup the restore.
Dump size is 30 GB gzip about 160gb 300 mio entries, attached my mysql.cnf
It is a stand alone server just for mysql.
The old server ist mysql 5.6, i dont know if it is able to copy the ibdata files?

[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
skip-name-resolve
explicit_defaults_for_timestamp = 1
#
key_buffer_size     = 6M
#max_allowed_packet = 16M
#thread_stack       = 192K
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options  = BACKUP
max_connections        = 10000
table_open_cache       = 15000
open_files_limit= 17000
innodb_doublewrite = 0
log_error_verbosity = 1
innodb_buffer_pool_size = 220G
innodb_thread_concurrency = 0
innodb_read_io_threads = 64
innodb_write_io_threads = 64
innodb_buffer_pool_instances = 48
innodb_lock_wait_timeout=120
innodb_io_capacity = 400000
max_heap_table_size = 5G
max_allowed_packet=1G
sort_buffer_size=9M
join_buffer_size=9M
# * Query Cache Configuration
#
query_cache_limit   = 16M
query_cache_size        = 512M
query_cache_type    = 1
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#slow_query_log     = 1
#slow_query_log_file    = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size   = 100M
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

A: Restoring from an SQL dump will be always slow. You can make it faster by:

*

*Increasing innodb_buffer_pool_size to size of the old datadir or what available RAM allows. 220G in your config is a good value, so this option not for you.

*Setting innodb_flush_log_at_trx_commit to 0 or 2.

*Increasing innodb_log_file_size to several GB. 4GB will be OK.

*Disable query_cache.

*disable binlogs.

Do not disable innodb_doublewrite - unsafe.
Yet, I doubt you'll gain much.
To restore the database faster use XtraBackup or cold copy (if you shutdown the old database and copy datadir to the new server it will pick it up w/o problems assuming same MySQL version).


text:
Q: What's the recommended syntax for an image with a link? What's the recommended syntax for an image with a hyperlink? I tried doing it
with the markdown toolbar buttons and the image and link buttons conflict
with each other, so I had to resort to HTML.
For example, to do this:

These work properly:
![alt text][1]
[1]: https://www.gravatar.com/avatar/dd5a7ef1476fb01998a215b1642dfd07

[][2]
[2]: https://meta.stackoverflow.com/users/44330/jason-s

This does not:
![alt text][1]

(single quotes not allowed?)
Is there a way to do the same thing in Markdown without having to resort to HTML?
Return to FAQ index

A: For numerically indexed URLs, just make a new numbered URL.
For example, when you insert an image with the fancy editor, it starts off linking to itself. In HTML terms, the a.href link URL is the same as img.src image URL.
[![alt text][1]][1]

[1]: https://i.stack.imgur.com/wPW28.png

Just add a new URL for the link:
[![alt text][1]][2]

[1]: https://i.stack.imgur.com/wPW28.png
[2]: https://www.timeanddate.com/astronomy/moon/light.html?month=3&day=20&year=2040&hour=19&min=00&sec=0&n=64&ntxt=Chicago&earth=0

The result:

So (http://example.com) can be replaced with [42] ... [42]: http://example.com

A: It is possible to use Markdown for both the image and the link.
You have to do it manually because the the toolbar's default behavior
is to make the clickable image point to the URL of the image itself.

Reference-style
[![alt text][image]][hyperlink]

[hyperlink]: https://meta.stackoverflow.com/users/44330/jason-s
[image]:
https://www.gravatar.com/avatar/dd5a7ef1476fb01998a215b1642dfd07
(tooltip)
  – or –
[image]:
https://www.gravatar.com/avatar/dd5a7ef1476fb01998a215b1642dfd07
"tooltip"

Example

Default behavior, reference-style
Since July 2015 the insert
image feature (Ctrl + G) of the toolbar of the
Stack Exchange Markdown editor by default adds a clickable link to the
image itself.
1
It uses the following syntax:
[![enter image description here][number]][number]

where number is an automatically generated number.
Default example, reference-style
[![Jason's avatar][1]][1]

[1]: https://i.stack.imgur.com/X14m7.png
"Tooltip for Jason's avatar"

To change the link to something else, simply change the second
[number] with (*your URL here*) (in parentheses) or use the
reference style syntax above.

Inline-style
[![alt text](image "tooltip")](hyperlink)
  for example:
[![invisible description of images, read aloud to blind users
](https://i.stack.imgur.com/X14m7.png
"Let's check Jason S' profile page (inline-style)")
](https://meta.stackoverflow.com/users/44330/jason-s)

Default behavior, inline-style
You can get the default behavior without using the [number]
construct.
[![A click on the image links to its own URL.](
https://i.stack.imgur.com/X14m7.png
"A click on the image links to its own URL (inline-style).")
](https://i.stack.imgur.com/X14m7.png)

The observant reader will notice that to achieve the inline-style
default behavior, the URL to the image must be supplied twice.
The first link is there to display the image, the second link
makes the image clickable.

References:

*

*From 2015, the image uploader automatically wraps images in a link
to themselves

*FAQ for Stack Exchange sites
| Editing and Formatting

*Extra square brackets and numbers when using automated link

*Why does the images index on Stack Overflow appear twice?

1 The previous default behavior was to just display the
image - without any link at all. ~ * ~ Even the new default behavior
does not add any tooltip for you. – If you want a tooltip, you have to
add it yourself.


text:
Q: Rails 4 - How to configure google calendar using `fullcalendar_engine` gem In Rails 4.1.4, I am using fullcalendar_engine gem to implement a calendar app. I have  tried to connect it with a google calendar by referring http://fullcalendar.io/docs/google_calendar/. After adding this feature(as mentioned below)  events are not showing in calendar. If I removed googleCalendarApiKey & events options then events will display in calendar.
In views,

<%= link_to 'Create Event', 'javascript:void()', :id=> 'new_event' %>
<%= link_to 'Home', "/" %>

   <%= render 'form' %>

How can I connect this fullcalendar to google calendar?


text:
Q: Get 95 percentile of the variables for SON, DJF, MAM over multiple years' data I have a 45 years of data named ds in the netCDF(.nc) format. It contains three coordinates: time, latitude and longitude.
print(ds)

<xarray.Dataset>
Dimensions:    (latitude: 106, longitude: 193, time: 403248)
Coordinates:
  * latitude   (latitude) float32 -39.2 -39.149525 ... -33.950478 -33.9
  * longitude  (longitude) float32 140.8 140.84792 140.89584 ... 149.95209 150.0
  * time       (time) datetime64[ns] 1972-01-01 ... 2017-12-31T23:00:00
Data variables:
    FFDI       (time, latitude, longitude) float32 dask.array<shape=(403248, 106, 193), chunksize=(744, 106, 193)>
Attributes:
    creationTime:        1525925611
    creationTimeString:  Wed May  9 21:13:31 PDT 2018
    Conventions:         COARDS

I need to calculate 95 percentile of FFDI by seasons, namely SON (Sep, Oct, Nov), DJF (Dec, Jan, Feb), MAM (Mar, Apr, May), JJA (Jun, Jul, Aug).
da_ffdi_95th = ds['FFDI'].reduce(np.percentile, dim='time', q=95)

This created a new DataArray object with percentile variables but the time dimension was dropped.
How can groupby be used with the np.percentile function?

A: Believe it or not, I think you're most of the way there! See DataArrayGroupBy.reduce for more details.
da_ffdi_95th = ds['FFDI'].groupby('time.season').reduce(
    np.percentile, dim='time', q=95)

Since we are using a NumPy function however, the data will be loaded eagerly.  To make this dask-compatible, the function we pass to reduce must be able to operate on NumPy or dask arrays.  While dask implements a function that does this, dask.array.percentile, it only operates on 1D arrays, and is not a perfect match to the NumPy function.
Fortunately, with dask.array.map_blocks, it's easy enough to write our own.  This uses the NumPy implementation of percentile and applies it to each chunk of the dask array; the only thing we need to be careful of is to make sure the array we apply it to is not chunked along the dimension we want to compute the percentile along.
import dask.array as dask_array

def dask_percentile(arr, axis=0, q=95):
    if len(arr.chunks[axis]) > 1:
        msg = ('Input array cannot be chunked along the percentile '
               'dimension.')
        raise ValueError(msg)
    return dask_array.map_blocks(np.percentile, arr, axis=axis, q=q,
                                 drop_axis=axis)

Then we can write a wrapper function that calls the appropriate percentile implementation depending on the type of the input array (either NumPy or dask):
def percentile(arr, axis=0, q=95):
    if isinstance(arr, dask_array.Array):
        return dask_percentile(arr, axis=axis, q=q)
    else:
        return np.percentile(arr, axis=axis, q=q)

Now if we call reduce, making sure to add the allow_lazy=True argument, this operation returns a dask array (if the underlying data is stored in a dask array and is appropriately chunked):
da_ffdi_95th = ds['FFDI'].groupby('time.season').reduce(
    percentile, dim='time', q=95, allow_lazy=True)


text:
Q: Required permissions on AD user objects for SSSD? I was experiencing major issues with SSSD today where newly created users were unable to logon. After troubleshooting I found that the issue was in the AD user object security permissions. Seems like someone from my team recently changed the permissions for authenticated users and unchecked the read checkbox.
So my questions is which user does a Linux server that was joined to a domain with SSSD use to authenticate and retrieve AD objects information? As the users in the ou where the read permissions have been revoked for authenticated users are very critical, I would like to know what user is used to authenticate by SSSD. Could it be the computer object of the Linux server that requires the permissions?
The weird thing is that when I enable read permissions temporarily, id the user after which all works fine. Then I uncheck the read permissions for authenticated users and it seems everything keeps working.. (Of course after emptying the sssd cache) Any insights on which permissions are minimum required by which user are welcome.
We discovered it is the AD computer object which actually authenticates. Giving this object read permissions on the user enables the id command to retrieve the groups. The question is which permissions are minimally required so the id command can get all the groups?

A: Unless you specified ldap_default_bind_dn and ldap_default_authtok in your sssd.conf, it will default to an anonymous bind to the specified LDAP server to retrieve the schema and objects. Anything else, like a logon, will use the provided credentials.

A: After a lot of research we discovered that (as I already mentioned in the question) it is the Linux server computer object that is actually authenticating. Granting read permissions on the user objects to the computer object enables id to work and retrieve all the user groups.
But as we didn't want to grant read on all users, after much trial and error we found that there is acutally only one mandatory required permission and that is Read remote access information. From the moment the Read remote access information checkbox is checked (see screenshot) it is possible to use the ìd command to get all the groups. SSSD is then able to check if the user is in the groups configured with the simple_allow_groups directive in /etc/sssd/sssd.conf


text:
Q: How to check if a type never be a valid generic argument? The code I have so far is as the following, what I want to solve is to get rid of the try-catch:
public static bool IsNeverValidGenericArgument(this Type type) {
    var elementType=type.GetElementType();

    if(null!=elementType) {
        if(type.IsArray)
            try {
                typeof(IList<>).MakeGenericType(elementType);
                return false;
            }
            catch(ArgumentException) {
            }
            catch(TypeLoadException) {
            }

        return true; // pointer or byref
    }

    return
        typeof(void)==type||typeof(RuntimeArgumentHandle)==type
        ||
        typeof(ArgIterator)==type||typeof(TypedReference)==type;
}

I'm trying to write the code of dynamic type construction, and my code will invoke GetInterfaces() on each type passed, but some of the types passed by the consumers' code may cause a TypeLoadException in RuntimeType internally(e.g. typeof(ArgIterator).MakeArrayType().MakeArrayType() in 3.5, but not 4.0+), I need to check if it is never a valid generic argument in the first place. try-catch works, but no good.
Note that the cases that it throws may vary with different version of .Net framework.

Edit:
An alternative version of the method is:
public static bool IsNeverValidGenericArgument(this Type type) {
    var elementType=type.GetElementType();

    if(null!=elementType) {
        if(type.IsArray)
            return elementType.IsNeverValidGenericArgument();

        return true; // pointer or byref
    }

    return
        typeof(void)==type||typeof(RuntimeArgumentHandle)==type
        ||
        typeof(ArgIterator)==type||typeof(TypedReference)==type;
}

But this will reports some types as invalid which in fact would not cause the exception in RuntimeType, such as typeof(ArgIterator).MakeArrayType(2).MakeArrayType().
I know some types are not nomally used, but I can't avoid them to be used in the consumers' code.

A: When you try to construct a generic type with an argument of typeof(ArgIterator).MakeArrayType().MakeArrayType(), it's internal native CLR code that throws the exception. The most important takeaway from that fact is that it's a CLR implementation detail that throws, and it's not part of a standard or a publicly-exposed API that determines the validity of a generic type argument. That means there's no good way to determine whether or not the generic type can be constructed without actually trying it. EDIT: That also means there's no good way to determine whether something will work on a particular version of the CLR and not work on another.
But, more importantly, if you try to construct a generic type with an invalid argument, that is truly an exceptional case, and the correct course of action is to throw an exception. I can't speak to what your code does, but if you're worried about your consumers invoking it with classes that cause TypeLoadExceptions to be thrown, perhaps you should let those errors bubble up so the consumer knows that there's an issue.
TL;DR: You probably shouldn't be doing whatever you're trying to do to handle the exception case. Just let it throw.

A: Is the problem due to your customer potentially passing in types that don't have a valid public parameter-less constructor? If that is the case, you could restrict the input they are allowed to send you by adding a condition to your generic method:
public class MyClass<T>
    where T : new()
{

}

This code will only allow generic types T that have a public constructor with no parameters. You can find more info on the where clause here
I don't know how you have your variadic type arguments implemented, but you could take in a params collection of type T with the above clause added, like so:
public class MyClass<T>
    where T : new()
{
    public void MyMethod(params T[] items)
    {
        //...Do stuff...
    }
}

That would let them pass in as many items as they wanted, but restrict them to generic types that you want to support.

A: It would be helpful if you added some test cases so that we coders could know specifically what you expect.  But you offered a bounty so I am seeing if this gets close to what you want.
results of code below:
Test has definition Test<>
Actual Type is UserQuery+Test`1[System.Int32]
public static class Extensions
{
    /// <summary>
    /// Checks whether this type has the specified definition in its ancestry.
    /// </summary>
    public static bool HasGenericDefinition(this Type type, Type definition)
    {
        return GetTypeWithGenericDefinition(type, definition) != null;
    }

    /// <summary>
    /// Returns the actual type implementing the specified definition from the
    /// ancestry of the type, if available. Else, null.
    /// </summary>
    public static Type GetTypeWithGenericDefinition(this Type type, Type definition)
    {
        if (type == null) throw new ArgumentNullException("type");
        if (definition == null) throw new ArgumentNullException("definition");
        if (!definition.IsGenericTypeDefinition) throw new ArgumentException("The definition needs to be a GenericTypeDefinition", "definition");

        if (definition.IsInterface)
            foreach (var interfaceType in type.GetInterfaces())
                if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == definition)
                    return interfaceType;

        for (Type t = type; t != null; t = t.BaseType)
            if (t.IsGenericType && t.GetGenericTypeDefinition() == definition)
                return t;

        return null;
    }
}

void Main()
{
    Type a = typeof(Test<int>);
    Type b = typeof(Test<>);
    if(a.HasGenericDefinition(b)) Console.WriteLine("Test<int> has definition Test<>");
    Type c = a.GetTypeWithGenericDefinition(b);
    Console.WriteLine("Actual Type is {0}", c.ToString());
}

public class Test<T>
{
    public Test()
    {
    }
}

A: I can't see it can be done much better than what you have already. Here's my version:
// Predicts whether the given type cannot be used as a type argument.
public static bool IsNeverValidGenericArgument(this Type type)
{
  if (type == null)
    throw new ArgumentNullException("type");

  // Pointer types and ByRef types.
  if (type.IsPointer || type.IsByRef)
    return true;

  // The following four special cases were found by reflecting through all types in mscorlib.dll, System.dll, and System.Core.dll.
  // The list may be different in other versions of the framework.
  var exceptions = new HashSet<Type>
  {
    typeof(ArgIterator), typeof(RuntimeArgumentHandle), typeof(TypedReference), typeof(void),
  };
  return exceptions.Contains(type);
}

Note that this considers only if the type system will construct a closed generic type with type as its type argument. There are types that are quite meaningless, such as:
typeof(IList<>).MakeGenericType(typeof(Math))  // will work
// but C# does not allow the notation IList<Math>

where System.Math is a static class (abstract and sealed type). My method will still return false for static classes like that.
Some types don't even exist, such as type = typeof(int).MakeByRefType().MakeArrayType() (will throw), so these bastards can't be checked by my method.

A: Here is an update to your "alternative" version of the code that addresses the issue with ArgIterator.
    public static bool IsNeverValidGenericArgument(this Type type)
    {
        return type.IsNeverValidGenericArgument(true);
    }

    private static bool IsNeverValidGenericArgument(this Type type, bool isRoot)
    {
        var elementType = type.GetElementType();

        if (null != elementType)
        {
            if (type.IsArray)
                return elementType.IsNeverValidGenericArgument(false);

            return true; // pointer or byref
        }

        if (isRoot)
        {
            return
                typeof(void) == type || typeof(RuntimeArgumentHandle) == type
                ||
                typeof(ArgIterator) == type || typeof(TypedReference) == type;
        }
        else
        {
            return (typeof(void) == type || typeof(TypedReference) == type);
        }
    }


text:
Q: Getting error BeanCurrentlyInCreationException: as soon as I expose clientRegistrationRepository bean in my spring boot security configuration I am trying to configure oauth2 login flow in my application. The problem is default configuration is working but as soon as I expose clientRegistrationRepository bean I got the error. First here is my POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                    https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>pk.training.basit</groupId>
<artifactId>Ch-02-SpringBootOAuth2ResourceServerWithIntrospection</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootOAuth2ResourceServerWithIntrospection</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>14</java.version>
    <oauth2-oidc-sdk.version>8.15</oauth2-oidc-sdk.version>
    <mssql-jdbc.version>8.3.1.jre14-preview</mssql-jdbc.version>
    <jjwt-api.version>0.11.2</jjwt-api.version>
    <bootstrap.version>4.5.0</bootstrap.version>
    <jquery.version>3.5.1</jquery.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>

    <!-- do you like thymeleaf? -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- optional, it brings userful tags to display spring security stuff -->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity5</artifactId>
    </dependency>

    <dependency>
        <groupId>nz.net.ultraq.thymeleaf</groupId>
        <artifactId>thymeleaf-layout-dialect</artifactId>
    </dependency>

    <dependency>
        <groupId>com.nimbusds</groupId>
        <artifactId>oauth2-oidc-sdk</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-api</artifactId>
        <version>${jjwt-api.version}</version>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-impl</artifactId>
        <version>${jjwt-api.version}</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
        <version>${jjwt-api.version}</version>
        <scope>runtime</scope>
    </dependency>

    <!-- bootstrap and jquery -->
    ...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Here is my Security Configuration. The following configuration is working. But please note that I have comment out the //@Bean above the  public ClientRegistrationRepository clientRegistrationRepository() in OAuth2LoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter.
@Configuration
@EnableGlobalMethodSecurity(
    prePostEnabled = true,
    order = 0,
    mode = AdviceMode.PROXY,
    proxyTargetClass = false
)
@EnableWebSecurity
public class SecurityConfiguration  {

    private static final String KEY_STORE_FILE = "oauth2/basit-jwt.jks";
    private static final String KEY_STORE_PASSWORD = "basit-pass";
    private static final String KEY_ALIAS = "basit-oauth-jwt";

    @Autowired
    private UserPrincipalService userPrincipalService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    };

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
         builder
             .userDetailsService(this.userPrincipalService)
                 .passwordEncoder(passwordEncoder())
         .and()
             .eraseCredentials(true);
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

        @Bean
        public KeyPair keyPair() {
            ClassPathResource ksFile = new ClassPathResource(KEY_STORE_FILE);
            KeyStoreKeyFactory ksFactory = new KeyStoreKeyFactory(ksFile, KEY_STORE_PASSWORD.toCharArray());
            KeyPair keyPair = ksFactory.getKeyPair(KEY_ALIAS);
            return keyPair;
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        }

        @Bean
        public OpaqueTokenIntrospector introspector() {
            return new JwtOpaqueTokenIntrospector();
        }

        @Override
        protected void configure(HttpSecurity apiHttpSecurity) throws Exception {

            apiHttpSecurity.httpBasic().disable()
            .formLogin(AbstractHttpConfigurer::disable)
            .csrf(AbstractHttpConfigurer::disable)
            .antMatcher("/api/**")
            .authorizeRequests(
                    authorize -> authorize.mvcMatchers(HttpMethod.POST, "/oauth2/token").permitAll()
                        .mvcMatchers(HttpMethod.POST, "/oauth2/introspect").permitAll()
                        .mvcMatchers(HttpMethod.GET, "/api/message").hasAuthority("READ")
                        .mvcMatchers(HttpMethod.POST, "/api/message").hasAuthority("WRITE")
                        .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken)
            .sessionManagement(sessionManagement ->
                sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        }
    }

    @Configuration
    @PropertySource("application-oauth2.properties")
    @Order(2)
    public static class OAuth2LoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        // additional configuration for non-Spring Boot projects
        private static List<String> clients = Arrays.asList("google", "facebook", "zapier");

        private static String CLIENT_PROPERTY_KEY = "spring.security.oauth2.client.registration.";

        @Autowired
        private Environment env;

        //@Bean
        public ClientRegistrationRepository clientRegistrationRepository() {

            List<ClientRegistration> registrations = clients.stream()
                    .map(c -> getRegistration(c))
                    .filter(registration -> registration != null)
                    .collect(Collectors.toList());

            return new InMemoryClientRegistrationRepository(registrations);
        }

        private ClientRegistration getRegistration(String client) {

            String clientId = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-id");

            if (clientId == null) {
                return null;
            }

            String clientSecret = env.getProperty(CLIENT_PROPERTY_KEY + client + ".client-secret");
            if (client.equals("google")) {
                return CommonOAuth2Provider.GOOGLE.getBuilder(client)
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .build();
            }

            if (client.equals("facebook")) {
                return CommonOAuth2Provider.FACEBOOK.getBuilder(client)
                    .clientId(clientId)
                    .clientSecret(clientSecret)
                    .build();
            }

            if (client.equals("zapier")) {
                ClientRegistration zapierClientRegistration = zapierClientRegistration();
                return zapierClientRegistration;
            }

            return null;
        }

        private static ClientRegistration zapierClientRegistration() {
            return ClientRegistration.withRegistrationId("zapier")
                .clientId("zapier")
                .clientSecret("Zapier")
                .clientAuthenticationMethod(ClientAuthenticationMethod.POST)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUriTemplate("https://zapier.com/dashboard/auth/")
                .scope("openid", "profile", "email", "address", "phone")
                .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth")
                .tokenUri("https://www.googleapis.com/oauth2/v4/token")
                .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo")
                .userNameAttributeName(IdTokenClaimNames.SUB)
                .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs")
                .clientName("Zapier")
                .build();
        }

        @Override
        protected void configure(HttpSecurity oauthHttpSecurity) throws Exception {

            oauthHttpSecurity
                .antMatcher("/oauth2/**")
                .authorizeRequests(
                    authorize -> authorize.mvcMatchers(HttpMethod.GET, "/oauth2/login").permitAll()
                        .anyRequest().authenticated()
            )
            .oauth2Login();
            //.oauth2Login(oauth2 ->
                   oauth2.clientRegistrationRepository(clientRegistrationRepository())
                //.loginPage("/oauth2/login")
            //);
        }
    }

    @Configuration
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Bean
        protected SessionRegistry sessionRegistryImpl() {
            return new SessionRegistryImpl();
        }

        ///Very important ,you wont login again after logout if you dont include this
        @Bean
        public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
            return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
        }

        @Bean
        public CsrfTokenRepository csrfTokenRepository(){
            HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
            return repository;
        }

        @Override
        public void configure(WebSecurity security) {
            security.ignoring().antMatchers("/css/**", "/img/**", "/webjars/**", "/favicon.ico");
        }

        @Override
        protected void configure(HttpSecurity security) throws Exception {

            security
                .authorizeRequests()
                .antMatchers("/session/list").hasAuthority("VIEW_USER_SESSIONS")

                // Any request simply requires authentication, regardless of permissions.
                .anyRequest()
                .authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login?loginFailed")
                    .defaultSuccessUrl("/ticket/list")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .permitAll()
            .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/login?loggedOut")
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .deleteCookies("JSESSIONID")
                    .permitAll()
            .and()
                .sessionManagement()
                    .sessionFixation()
                    .changeSessionId()
                    .maximumSessions(1)
                    .maxSessionsPreventsLogin(true)
                    .sessionRegistry(this.sessionRegistryImpl())
                .and()
            .and()
                .csrf()
                    .csrfTokenRepository(csrfTokenRepository())
                    .requireCsrfProtectionMatcher((r) -> {
                        String m = r.getMethod();
                        return !r.getServletPath().startsWith("/api/") && ("POST".equals(m) || "PUT".equals(m) ||
                                    "DELETE".equals(m) || "PATCH".equals(m));
                    });
        }
    }
}

But if I open @Bean on public ClientRegistrationRepository clientRegistrationRepository() in OAuth2LoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter. I get the following error
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.FormLoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setAuthorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientService' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setAuthorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientService' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setAuthorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientService' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientRepository' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientService' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:538) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizedClientService' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2WebSecurityConfiguration.class]: Unsatisfied dependency expressed through method 'authorizedClientService' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:538) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfiguration.OAuth2LoginWebSecurityConfigurerAdapter': Unsatisfied dependency expressed through method 'setContentNegotationStrategy' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:723) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mvcContentNegotiationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.java:347) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:219) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1304) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]

What I am doing wrong here. Default is working but exposing ClientRegistrationRepository clientRegistrationRepository() as bean causing this error.
Is there any other settings that I need to expose here ?
Thanks

A: It is better not to create beans inside the WebSecurityConfigurerAdapter implementation. Create all your beans in a separate general configuration and reference them using @Autowired, for example:
@Configuration
@EnableWebMvc
public class SpringConfiguration {
    @Bean
    public OpaqueTokenIntrospector introspector() {
        return new JwtOpaqueTokenIntrospector();
    }
}

and then define WebSecurityConfigurerAdapter inside an another file:
@Configuration
@EnableWebSecurity
public class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    protected OpaqueTokenIntrospector opaqueTokenIntrospector;

    .... here is the code which uses token introspector ....
}


text: Q: Every time I route to a new page I have to check the server with axios in a Vue JS app So every time, I route to a new page on the click of certain divs I have to check if the name of the div exists in the server with axios and display all the information about the div clicked from the server. I was hoping to use the router.beforeEach methods or an @click method then router.addRoute and then router.push. Any suggestions on what I can do?


text:
Q: Validation Rule: User only can edit the status field during the edition. No other field should be edit This is not a duplicated question, but a new one. I created a formula where the user can or should only edit the status field when the status is equal to "Under approval". However, when I change the status to approve or rejected, I can edit the record name and payment name during the edition. How can I prevent user to modify the payment name and account name (lookup) during the record edition? The user should only change the status, not the other fields. The system should not allow the user to save the record, because only the status field can be edit. This is my current formula:
AND(ISPICKVAL( PRIORVALUE( Status__c ), "Under Approval"),AND( NOT(ISPICKVAL(Status__c, "Unpaid")), NOT(ISPICKVAL(Status__c,"Paid"))),
NOT(ISPICKVAL(Status__c, "Approved")),
NOT(ISPICKVAL(Status__c, "Rejected")))

Thanks for helping me!


text:
Q: Matrix to create sheets and copy certain information I have a unit matrix that illustrates work items for an apartment complex. It expands to 5 floors and has more work items than just the kitchen scope. My end goal is to have a sheet for each unit, listing the specific items needed for that unit. It would be very helpful once construction begins.
I want to do 2 things. 1 - Create new sheets for each unit (C5:C124) using the template. 2 - Copy over the information based on what is marked with an "X"
I know how to create a macros that will create blank sheets from the number of units I have. I'm stuck on integrating the template.
Thank you for reading.
Unit Scope Matrix
Template
Edit 1:
Here is my new code that can take a range of room#s and create new sheets from it. Now I would like to copy and paste the the row next the the according room# cell and paste in the appropriate sheet.
Sub CreateSheets()

    Dim rng As Range
    Dim cell As Range

    On Error GoTo Errorhandling

'Creates popup box asking for the room numbers
    Set rng = Application.InputBox(Prompt:="Select cell range:", _
    Title:="Create sheets", _
    Default:=Selection.Address, Type:=8)

    For Each cell In rng

'Check if cell is not empty
    If cell <> "" Then

'Insert worksheet and name the worksheet based on cell value
    Sheets("Template").Copy After:=Sheets("Unit Types")

'Name new sheet based off two cells on Bid Summary List Cells (Bi and Di)
ActiveSheet.Name = "UNIT-" & cell

'This is where I think I should add the copy/paste lines... but I don't know how.
'Copy unit# row and paste in correct worksheet
    'Range("XX:XX").Copy Range("XX:XX")

    End If

'Continue with next cell in cell range
Next cell

'Go here if an error occurs
Errorhandling:

'Stop macro
End Sub

A: The code to copy the template and rename it is easy enough to make. Start recording, do one manually, stop recording, then press Alt-F11 to see how it's done, then steal from that to make your own function.
I suspect you'll end up with something that looks like
Function NewSheet(nm as String) as Worksheet
  Dim template As Worksheet

  set template = ActiveWorkbook.sheets('template')
  set NewSheet = template.copy(ActiveWorkbook)
  NewSheet.name = nm // change the tab name
  NewSheet range('B1') = nm // add to the sheet as well
End Function

(warning: syntax and method names might unintentionally be wrong, this is intended to give you a head start, not do it for you)
and then you'll need to write a macro that loops through column C and calls your function. In this case you can ignore that NewSheet returns a new Worksheet object, but this way provides flexible code for future needs. Also, by isolating what you need to do to make a new worksheet as its own function that's called multiple times, It's easier to reason through and test, and the looping code that calls it is much easier to read as well.
Try searching for "Excel VBA looping examples" to get a head start on looping if you are unfamiliar.