text:
Q: What would be the best and cleanest way to create a service function which needs to do two nested rest calls depending on each other? I'm using Todd Mottos and John Papas Styleguide and am quite familiar with both. Now I'm trying to create a data service with a function which needs to do two nested REST-calls, the second depends on the first. what would be the best and cleanest way to achieve this?
I did write three functions:
[...]
return {
    get: get
};

var benutzerkennung = {};

// API function
function get(referenzID, versorgungsfallIdent) {
    return getBenutzerkennung()
        .then(function() {
            return getMasterData(referenzID, versorgungsfallIdent);
        })
        .catch(requestFailed);
}

function getBenutzerkennung() {
    return commonQueryService
        .requestBenutzerkennung()
        .then(function(response) {
            benutzerkennung = response.data.reference;
        });
}

function getMasterData(referenzID, versorgungsfallIdent) {
    // "data" is just a simple js-object filled with the three params, two coming
    // from the controller calling .save() and one coming from the first request
    var data = getFilledDataObject(benutzerkennung, referenzID, versorgungsfallIdent);

    return $http
        .post('./services/anStammdatenService/get/getANStammdaten', data)
            .then(function (response) {
                return response.data;
            });
}

so you see that the Service-Method to be called from the controller is
function save()
and it does the first request wrapped in the function "getBenutzerkennung()" which is required for the next request, wrapped in "getMasterData()". Is that a good codestyle?
Would be much appreciated!

A: Avoid mutating variables outside a .then method when chaining promises.

BAD
var outside;

function getA (params){
    return serviceA(params).then(function(response) {
        outside = response.data;
    });
}

function getB (params){
    return getA(params).then(function() {
         return serviceB(params,outside)
    });
}

The code risks closure problems. If the getB function is called multiple times before the previous chained XHRs complete, the outside variable may not be set properly.
Chain data properly
function getA (params){
    return serviceA(params).then(function(response) {
        return response.data;
    });
}

function getB (params){
    return getA(params).then(function(dataA) {
         return serviceB(params,dataA);
    });
}

A: I'm not familiar with the style guides you mentioned but in general I would tend to do something like this:
const get = () => commonQueryService
  .requestBenutzerkennung()
  .then(function(response) {
      return response.data.reference;
  })
  .then(function(benutzerkennung){
    var data = getFilledDataObject(benutzerkennung, referenzID, versorgungsfallIdent);
    return $http.post('./services/anStammdatenService/get/getANStammdaten', data)

  })
  .then(function (response) {
      return response.data;
  })

If you like you could extract the functions you pass to the .then()s so you'll get a nice clean promise pipeline at the end. Something like this
const getData = function(response) {
  return response.data.reference;
}

const postData = function(benutzerkennung){
  var data = getFilledDataObject(benutzerkennung, referenzID, versorgungsfallIdent);
  return $http.post('./services/anStammdatenService/get/getANStammdaten', data)
}

const sendResponse = function (response) {
  return response.data;
}

const get = () => commonQueryService
  .requestBenutzerkennung()
  .then(getData)
  .then(postData)
  .then(sendResponse)

You may offcourse use more declarative names for your functions.


text:
Q: getBoundingClientRect deviation between page loads, alternative? I'm trying to make an animated category navigation panel and I want the highlighted background to move to the selected category: https://gyazo.com/78119b65275f1905bdb8f5ff03ea4746
To do so, I dynamically use getBoundingClientRect to obtain the proper positions of where the block should go. Although between page loads, the values sometimes randomly are offset for no reason and look like this: https://gyazo.com/798be154e3817261bd8f0aa3ec40ac2d
My code is rather simple and I don't understand if there is a way to fix this or if I have to find some other way that avoids getBoundingClientRect.
const projectCategories = document.getElementById("project-categories");
const selector = document.getElementById("category-selector");
const offset = projectCategories.getBoundingClientRect();
const offsetX = offset.left;
console.log(offsetX);
const offsetY = offset.top;
function moveSelector(selector, left, width, height, offsetX, offsetY) {
    selector.style.width = width + "px";
    selector.style.height = height + "px";
    selector.style.transform = "translateX(" + (left - offsetX) + "px)";
}
const initialCategory = document.getElementById("project-categories").getElementsByClassName("active")[0];
const meta = initialCategory.getBoundingClientRect();
const top = meta.top;
moveSelector(selector, meta.left, meta.width, meta.height, offsetX, offsetY);
selector.style.top = (top - offsetY) + "px";
projectCategories.addEventListener("click", (e) => {
    const target = e.target;
    if (target.nodeName === "A") {
        const meta = target.getBoundingClientRect();
        const height = meta.height;
        const width = meta.width;
        const left = meta.left;
        projectCategories.getElementsByClassName("active")[0].classList.remove("active");
        target.classList.add("active");
        moveSelector(selector, left, width, height, offsetX, offsetY);
    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Starting Web APIs I am asked to create a web api for a desktop application that is already developed.
I don t have any background in web development in general and I am somehow stuck in doing it in a very short amount of time
I found several books and guides out there but non of them is to the point and require alot of time ... which I don t have at all .
Can someone guide me to a good how to start tutorial page ? I have basic C# .NET experience and using Visual studio 2012

A: Try this:
Your First ASP.NET Web API


text:
Q: Get a listing of directories that have a certain folder within them (Cocoa) I am working on a Cocoa project (first one so I'm still learning) and I need to get a list of all directories at "x" location that also have a directory named "y" within them. I then need to populate a drop down box with the names of the "x" directories that have the "y" folder inside them. I will be using the drop down box selection to create and name a new directory later on.
I have looked into doing this with multiple different scripting languages but I have yet to find anything that works. I have also searched for a way to do this purely with Objective C, but the only thing I can find is ways to work with files, not directories. I am open to any way to do this, but being so new to Objective C and Cocoa in general, a simple way would be preferred.
If anything is unclear, just let me know and I'll do my best to clarify.


text:
Q: JSON, JavaScript, wrong Japanese Character I have this on my JSON-file (mydata.json on the server):
    "jp": [ "私はあなたを愛しています!",

and more. There is also "de" and "en" and so on and it is displayed correctly. But with these japanese characters, I get these unrecognizable characters. I have read threads here but I can't find a solution. I think it has something to do with the data from the server, wrong asking header, but don't know, how to fix it. I tried this (found here on stackoverflow) (file.js):
    $.ajax({url: myURL, contentType: "application/json; charset=utf-8",
    success: function(dataJSON){
        console.log(dataJSON);
            }
    });

End the outputs of the "de" and "en" (and more) are great, but the japanese characters appear like this:
���͂��Ȃ��������Ă��܂��I

How can I fix it?

A: In the server you need unicode http://unicode-table.com/en/#cjk-radicals-supplement
In javascript there is no problem because it uses unicode

A: set Content-Type: text/html; charset=utf-8
at the  beginning of the the file you request json from it

A: Try this!
Ajax automatically detects the dataType, but here it is explicit.
$.ajax({
    url: myURL,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(dataJSON){
       console.log(dataJSON);
    }
});


text:
Q: vega-lite: how to dynamically resize single plots I'm looking for a way to set the size on a chart either dynamically or at creation of a single vega-lite chart.  So far, I have tried setting width and height on spec.config.cell used for trellis charts which sets the height only, also calling the width() and height() methods on the view object, e.g.
view.height(200).width(200).render()

best I can do is get the canvas to resize and crop the chart, but the chart does not redraw to the specified size. I'm looking for it to work with padding:'strict' to specify the overall size, not just the size of the data rect.

A: Aside from manually setting the bandWidth for ordinals it seems the feature isn't implemented just yet:
https://github.com/vega/vega-lite/issues/1356#issuecomment-231825910


text:
Q: Form Re-Submission in ASP.Net MVC Without using jQuery Ajax Method I have below code if i submit form it submitted properly but suppose i refresh/reload page then it ask for resubmitting Form i want to solve this problem without using Ajax form Submit method or ajax post method
Refere Below Code

Controller:
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Loginview(LogOnModel MD,FormCollection frmCollection)
    {
        if (ModelState.IsValid)
        {

            int result = GetLoginDetails(MD);
            if (result == 100)
               return RedirectToAction("HomeView", "Home");
            else if (result == -1)
                MD.ErrorMessage = "Error Occured please Try Again Later!!";
            else
                MD.ErrorMessage = "Incorrect Username or Password !!";

            //  ViewData["result"] = result; // for dislaying message after saving storing output.
            //  ModelState.Clear();

        }

View
@model MIT.Models.LogOnModel
@{

    Layout = null;

}
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width" />
    <title>Loginview</title>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken();

                        Login

                            Email ID

                            @Html.TextBoxFor(a => a.UserName, new { @class = "form-control", placeholder = "Email ID", @autofocus = "autofocus", @required = "required", @type = "text" })

                            Password

                            @Html.TextBoxFor(a => a.Password, new { @class = "form-control", placeholder = "Password", @required = "required", @type = "password" })

                                (Forgot Password)

                                <button type="submit" class="btn btn-large btn-success pull-left" style="min-width: 80%;">
                                    Login</button>

                                @Html.DisplayFor(a => a.ErrorMessage)

    }

A: It's best practice to once your controller verifies the data is good and you process it, to redirect them to a different view. That way if they do refresh, it will not reprocess your form. Add a return View(yourmodel) at the end of the IsValid if statement to return user to orginal page.
         if (ModelState.IsValid)
         {
           int result = GetLoginDetails(MD);
           if (result == 100)
           {
             //I assume this is a good result?

             //!Process and store user entered data here!

             return RedirectToAction("ResultPage", "Home"); // Take them to a page dislaying message after saving storing output.
           }
           else if (result == -1)
             MD.ErrorMessage = "Error Occured please Try Again Later!!";
           else
             MD.ErrorMessage = "Incorrect Username or Password !!";
         }

         return View(model);  //this takes user back to original page display error message of what they need to correct. If model is valid, code will not get here.


text:
Q: Breaking lines in ToC As a follow-up to this question, I implemented an alternative Table of Contents, contained in an MWE:
\documentclass[11pt,a4paper]{article}
\usepackage[normalem]{ulem}
\usepackage{soul}
\usepackage{lipsum}
\usepackage{hyperref}
\hypersetup{
    colorlinks,
    citecolor=black,
    filecolor=black,
    linkcolor=black,
    urlcolor=black
}
\makeatletter

\setcounter{tocdepth}{1}

\newcommand*{\tocpg@current}{}
\newcommand*{\tocentry}[3]{%
  % #1: level  name
  % #2: title
  % #3: page number
  \ignorespaces
  \ifnum#1>\value{tocdepth}
  \else
    \ifx\tocpg@current\@empty
      p#3: %
      \def\tocpg@current{#3}%
    \else
      \def\tocpg@new{#3}%
      \ifx\tocpg@new\tocpg@current
        ,\ ~%
      \else
        \def\tocpg@current{#3}%
        ;\\p#3: %
      \fi
    \fi
    \uline{#2}%\ignorespaces
  \fi
  \ignorespaces
}
\renewcommand*{\numberline}[1]{}
\def\l@part{\tocentry{-1}}
\def\l@chapter{\tocentry{0}}
\def\l@section{\tocentry{1}}
\def\l@subsection{\tocentry{2}}
\def\l@subsubsection{\tocentry{3}}
\def\l@paragraph{\tocentry{4}}
\def\l@subparagraph{\tocentry{5}}
\makeatother
\begin{document}
\tableofcontents
\section{Section 1}
\lipsum[1-4]
\section{Section 2}
Test
\section{Section with long name}
More Test
\section{Section with even longer name}
\lipsum[3]
\section{This section has a long name}
Wow
\end{document}

This produces exactly the output I would want, but the packages ulem and hyperref seem to be interfering, and the soul package's command \ul is not working inside the ToC.
The problem of \uline is that it doesn't break lines in the ToC:

How could I fix this?

A: Here is the straightforward adaptation of my answer to your other question. The image shows the red boxes created by hyperref, as seen on-screen in certain pdf viewers (not all), they do not show up in print.
\documentclass{article}
\usepackage{blindtext}

\setcounter{tocdepth}{2}
\usepackage{etoc}

\usepackage{hyperref}
\usepackage{soul}

% cf more sophisticated example at end of Part V of etoc manual
% http://ctan.org/pkg/etoc
\newcommand*\inlinetoc {%
\begingroup
\etocsetstyle{section}
   {\etocskipfirstprefix}
   {. }
   {\bfseries \etocname{} \emph{(starting on page \etocpage)}: }
   {.}
\etocsetstyle{subsection}
   {\etocskipfirstprefix}
   {, }
   {\mdseries \etocname{} \ul{(\etocnumber{} on page \etocpage)}}
   {}
\tableofcontents
\endgroup
}

\begin{document}
\inlinetoc
\newpage
\Blinddocument
\end{document}

To get the exact style you need, you will have to modify in the code above the \etocsetstyle{section}... etc...
Here is with addition of
\hypersetup{hidelinks}

inside the \begingroup...\endgroup of the definition of \inlinetoc, in order to hide the red boxes drawn by defaut by hyperref (but the links are still there).

edit
Trying to use soul's \ul more I hit against some problems. The work-around seems to be to use \etocthename which is expandable, and enough \expandafter's to force its expansion before the \ul.
Then, this is wrapped up in \etocthelink to get the hyperref link. The example is again done with \hypersetup{hidelinks} locally, to not be visually confused from the red rectangles in the pdf display which overlap the underlining (notice the underlining breaks across line-endings).
\documentclass{article}
\usepackage{blindtext}

\usepackage{hyperref}
\usepackage{soul}
%\usepackage[normalem]{ulem}
\setcounter{tocdepth}{2}
\usepackage{etoc}

% cf more sophisticated example at end of Part V of etoc manual
% http://ctan.org/pkg/etoc
\newcommand*\inlinetoc {%
\begingroup
\hypersetup{hidelinks}
\etocsetstyle{section}
   {\etocskipfirstprefix}
   {. }
   {\bfseries \etocthelink{\expandafter\ul\expandafter{\etocthename}}
              (starting on page \etocpage): }
   {.}
\etocsetstyle{subsection}
   {\etocskipfirstprefix}
   {, }
   {\mdseries \mdseries
% debugging: \typeout{\etocthename}
    \etocthelink{\expandafter\ul\expandafter{\etocthename}}
    (\etocnumber{} on page \etocpage)}
   {}
\tableofcontents
\endgroup
}

\begin{document}
\inlinetoc
\newpage
\section{a veryvery very very very very  long section title to test soul and
  its macro ul}
\subsection{inside the first section we find a subsection with a very very very
very long name}
\Blinddocument

\end{document}

I do not understand why some closing parentheses disappear altogether in the output. There are there in the expansion of the \etocthename macros, as expected.


text:
Q: Finding 406 MHz frequency using android or iOS app Is it possible to write code that finds the frequency of 406 MHz frequency ? I'm trying to build a search and rescue app
Thanks !

A: 1) There is an Android device with RF capability. See the Earl outdoor tablet. http://meetearl.com
2) An alternative would be to use a RTL-SDR USB dongle to receive the frequency and use the app to control the dongle. The dongles are about $8-20 via eBay. I'd mount the dongle on a directional antenna so reduce RFI from the Android device. There is an existing iSDR app that controls these dongles.


text:
Q: Zigzag on a matrix diagonal Is there a way to draw a continuous zigzag diagonal better than this one ?

my code :
\documentclass[]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{fullpage,amsmath}
\usepackage{times}
\begin{document}

\begin{tikzpicture}[baseline=(A.center)]
  \tikzset{BarreStyle/.style =   {opacity=.3,line width=3 mm,line cap=round,color=#1}}

\matrix(A) [matrix of math nodes, left delimiter  = {[}, right delimiter ={]}]
{ M_{11} &|[color = blue]|  M_{12} & M_{13} &|[color = magenta]| M_{14} & M_{15} &|[color = red]| M_{16} \\
  |[color = blue]|M_{21} & M_{22} & |[color = magenta]|M_{23} & M_{24} & |[color = red]|M_{25} & M_{26} \\
  M_{31} & |[color = magenta]|M_{32} & M_{33} &|[color = red]| M_{34} & M_{35} &|[color = orange]| M_{36} \\
  |[color = magenta]| M_{41} & M_{42} &|[color = red]| M_{43} & M_{44} &|[color = orange]| M_{45} & M_{46} \\
  M_{51} & |[color = red]|M_{52} & M_{53} & |[color = orange]|M_{54} & M_{55} &|[color = olive]| M_{56} \\
 |[color = red]|M_{61} & M_{62} &|[color = orange]| M_{63} & M_{64} &|[color = olive]| M_{65} & M_{66} \\
};

 \draw [BarreStyle=red] (A-1-1.west) to (A-1-2.east);
 \draw [BarreStyle=red] (A-1-2.north) to (A-2-2.south);
 \draw [BarreStyle=red] (A-2-2.west) to (A-2-3.east);
 \draw [BarreStyle=red] (A-2-3.north) to (A-3-3.south);
 \draw [BarreStyle=red] (A-3-3.west) to (A-3-4.east);
 \draw [BarreStyle=red] (A-3-4.north) to (A-4-4.south);
 \draw [BarreStyle=red] (A-4-4.west) to (A-4-5.east);
 \draw [BarreStyle=red] (A-4-5.north) to (A-5-5.south);
 \draw [BarreStyle=red] (A-5-5.west) to (A-5-6.east);
 \draw [BarreStyle=red] (A-5-6.north) to (A-6-6.south);

\end{tikzpicture}

\end{document}

A: Possibly...
\documentclass[]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\usepackage{fullpage,amsmath}
\usepackage{times}
\begin{document}

\begin{tikzpicture}[baseline=(A.center)]
  \tikzset{BarreStyle/.style =   {opacity=.3,line width=3 mm,line cap=round,color=#1}}

\matrix(A) [matrix of math nodes, left delimiter  = {[}, right delimiter ={]}]
{ M_{11} &|[color = blue]|  M_{12} & M_{13} &|[color = magenta]| M_{14} & M_{15} &|[color = red]| M_{16} \\
  |[color = blue]|M_{21} & M_{22} & |[color = magenta]|M_{23} & M_{24} & |[color = red]|M_{25} & M_{26} \\
  M_{31} & |[color = magenta]|M_{32} & M_{33} &|[color = red]| M_{34} & M_{35} &|[color = orange]| M_{36} \\
  |[color = magenta]| M_{41} & M_{42} &|[color = red]| M_{43} & M_{44} &|[color = orange]| M_{45} & M_{46} \\
  M_{51} & |[color = red]|M_{52} & M_{53} & |[color = orange]|M_{54} & M_{55} &|[color = olive]| M_{56} \\
 |[color = red]|M_{61} & M_{62} &|[color = orange]| M_{63} & M_{64} &|[color = olive]| M_{65} & M_{66} \\
};

 \path [fill=red, fill opacity=0.25,rounded corners=0.125cm]
  (A-1-1.north west) \foreach \i in {1,...,6}{ |- (A-\i-\i.south east) }
  \foreach \i in {5,...,1} { |- (A-\i-\i.north east) } -- cycle;

\end{tikzpicture}

\end{document}

A: With {pNiceMatrix} of nicematrix.
\documentclass{article}
\usepackage{nicematrix,tikz}

\begin{document}

\renewcommand{\arraystretch}{1.4}
\setlength{\arraycolsep}{8pt}

$\begin{bNiceMatrix}[margin]
\CodeBefore
    \tikz \fill [red!10,rounded corners]
       (1-|1) |- (2-|2) |- (3-|3) |- (4-|4) |- (5-|5) |- (6-|6) |- (7-|7)
       |- (5-|6) |- (4-|5) |- (3-|4) |- (2-|3) |- (1-|2) -- cycle ;
\Body
    M_{11} &\color{blue}  M_{12} & M_{13} &\color{magenta} M_{14} & M_{15} &\color{red} M_{16} \\
    \color{blue}M_{21} & M_{22} & \color{magenta}M_{23} & M_{24} & \color{red}M_{25} & M_{26} \\
    M_{31} & \color{magenta}M_{32} & M_{33} &\color{red} M_{34} & M_{35} &\color{orange} M_{36} \\
    \color{magenta} M_{41} & M_{42} &\color{red} M_{43} & M_{44} &\color{orange} M_{45} & M_{46} \\
    M_{51} & \color{red}M_{52} & M_{53} & \color{orange}M_{54} & M_{55} &\color{olive} M_{56} \\
   \color{red}M_{61} & M_{62} &\color{orange} M_{63} & M_{64} &\color{olive} M_{65} & M_{66}
\end{bNiceMatrix}$

\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).

A: What about this?

Code (only the changed parts):
\tikzset{BarreStyle/.style = {
    opacity=.3,line width=6 mm,
    line cap=round, line join=round,
    color=#1, shorten >= -0.1ex, shorten <= -1ex}
}

[Same matrix definition]

\draw [BarreStyle=red] (A-1-1.center) to (A-1-2.center)
                                      to (A-2-2.center)
                                      to (A-2-3.center)
                                      to (A-3-3.center)
                                      to (A-3-4.center)
                                      to (A-4-4.center)
                                      to (A-4-5.center)
                                      to (A-5-5.center)
                                      to (A-5-6.center)
                                      to (A-6-6.center);


text:
Q: Add wxWidget to sublime text 3 I'd like to use wxWidget with sublime text 3.
I add the path of wxWidget in my system variables and a the inclure folder to my Project but I still Can't include any .h in m'y script.
The error is :No such file or directory.
I don't know how i Can do It.


text:
Q: C++ How do I instantiate a VkSubProcess object from this header? I'm having a hard time understanding how to instantiate a ViewKit VkSubProcess object. Manpage for this thing is here: VkSubProcess.3
I have read up enough about C++ to understand that this header describes a reference counted abstract base class and I think I more-or-less understand the concepts involved. However, my feeble attempts at actually using this thing have been unsuccessful.
My efforts lead to various compiler errors like:
"The class "RPtr_VkSubProcessRep" has no member "create"
or:
"No instance of constructor 'VkSubProcessRep::VkSubProcessRep' matches the argument list"
Could somebody be kind enough to please show how to instantiate a VkSubProcess object from this header?
For brevity I've removed from the header the functions mentioned in the manpage that come into play only after the instance has been created.
Many thanks.
#ifndef _VKPROCESS_H
#define _VKPROCESS_H

#include <signal.h>
#include <Xm/Xm.h>
#include <Vk/VkCallbackObject.h>
#include <Vk/VkBase.h>
#include <Vk/VkApp.h>

class VkSPCounted : public VkCallbackObject {

    friend class VkSPRPtr_base;

    int nreferences;
    void addRef() { nreferences++; }
    void delRef() {
            if (--nreferences <= 0)
              delete this;
    }

    public:
        VkSPCounted() : VkCallbackObject() { nreferences = 0; }
        virtual ~VkSPCounted();

    private:
        VkSPCounted(const VkSPCounted&);
        VkSPCounted &operator= (const VkSPCounted&);
};

class VkSPRPtr_base : public VkBase {

    public:
        operator void*() { return (void *)ptr; }
        VkSPRPtr_base& operator=(VkSPCounted *tp) {
            if (ptr) ptr->delRef();
            ptr = tp;
            if (ptr) ptr->addRef();
            return *this;
        }
        VkSPRPtr_base& operator=(const VkSPRPtr_base& r){
            if (ptr) ptr->delRef();
            ptr = r.ptr;
            if (ptr) ptr->addRef();
            return *this;
        }

    protected:
        VkSPCounted *ptr;
        VkSPRPtr_base() : VkBase() { ptr = 0; }
        VkSPRPtr_base(const VkSPRPtr_base& r) : VkBase() {
            ptr = r.ptr;
            if (ptr) ptr->addRef();
        }
        VkSPRPtr_base(VkSPCounted *tp) : VkBase() {
            ptr = tp;
            if (ptr) ptr->addRef();
        }
        ~VkSPRPtr_base() {
            if (ptr) ptr->delRef();
        }
};

class VkSubProcessRep;

class RPtr_VkSubProcessRep : public VkSPRPtr_base {

    public:
        RPtr_VkSubProcessRep();
        RPtr_VkSubProcessRep(VkSubProcessRep *tp);
        RPtr_VkSubProcessRep(const RPtr_VkSubProcessRep& that) : VkSPRPtr_base(that) {}
        ~RPtr_VkSubProcessRep();
        RPtr_VkSubProcessRep& operator=(VkSubProcessRep *tp) {
            *((VkSPRPtr_base *) this) = (VkSPCounted *) tp;
            return *this;
        }
        VkSubProcessRep& operator *();
        VkSubProcessRep *operator->();
        int operator !(){ return !ptr; }
};

typedef RPtr_VkSubProcessRep VkSubProcess;

class VkSubProcessRep : public VkSPCounted {

    public:
        static  VkSubProcess create(char* cmd,
                                    int killChildOnExit,
                                    int redirectIn);

        /* Actually create VkSubProcess */
        void     run();

    protected:
        VkSubProcessRep(const char* prog,
                        char **argv,
                        int killChildOnExit,
                        int redirectIn);

        ~VkSubProcessRep();

    private:
        VkSubProcessRep(const VkSubProcessRep&);
        VkSubProcessRep &operator= (const VkSubProcessRep&);
};

#endif

A: Well, after spending the day reading up on C++, I now know that this header describes a Reference-counted Singleton pattern. From what I have read, the static 'create()' function and the protected constructor seem to be typical for this pattern.
You might use it like so:
VkSubProcess process = VkSubProcessRep::create("ls -al", 1, 1);
process->run();


text:
Q: setting ImageButton's background transparent with Theme.Light in android How to set the background color of an ImageButton 'transparent' ?
The following piece of code works when I try it with default android theme, but with 'Theme.Light', I see a gray background.
ImageButton deleteBtn = new ImageButton( this );
deleteBtn.setImageResource( R.drawable.delete_big );
deleteBtn.setBackgroundColor(android.R.color.transparent);

(I need to dynamically create these buttons.. I have seen solutions which mention specifying @null background color using android's layout.xml files. How can I achieve the same thing programmatically ? Any help highly appreciated. Thanks!

A: I had to do something similar to this and I used a transparent png 9patch. Then you can set it to the background with something like:
deleteBtn.setBackgroundResource(R.drawable.transparent_bground);

Edit: here is a 9 patch you can use. Save it in one of your res/drawable folders.

A: Even though this is kind of answered, here's what went wrong.
Watch out for colors. android.R.color.transparent actually is an integer referencing a lookup table, and every time you set a color in Android in Java, it takes in an integer that represents the color.
Now, this is the tricky part: What's happening here is that it's setting the bg color to the lookup table index, which happens to translate to gray. If I remember right, getResources().getColor(id) is a function that can be called from a context or activity to get your correct color.


text:
Q: How can I post an order into woocommerce using Alamofire? I am trying to create an order from iOS to woo commerce using Alamofire. I am searching for a proper solution.
After trying to create an order I get this error:
{
    code = "woocommerce_rest_cannot_create";
    data =     {
        status = 401;
    };
    message = "Sorry, you are not allowed to create resources.";
}

Code:
let parameters: [String: AnyObject] = [
    "consumer_key":"*******" as AnyObject, // here is my user name
    "consumer_secret":"*******" as AnyObject, // here is my secret key

    "shipping_total": "120.00" as AnyObject,
    "total": "6015.00" as AnyObject,
    "customer_id": 0 as AnyObject,
    "billing": [
        "first_name": "Faizul",
        "last_name": "karim",
        "company": "somecompany",
        "address_1": "someAddress",
        "address_2": "someAddress",
        "city": "Dhaka",
        "state": "Dhaka",
        "postcode": "1203",
        "country": "bd",
        "email": "faizulkarim28@gmail.com",
        "phone": "001929838939"
        ] as AnyObject,
    "shipping": [
        "first_name": "Faizul",
        "last_name": "karim",
        "company": "somecompany",
        "address_1": "someAddress",
        "address_2": "someAddress",
        "city": "Dhaka",
        "state": "Dhaka",
        "postcode": "1203",
        "country": "bd",
    ] as AnyObject,
    "line_items":[
        "id": 388,
        "name": "Mens Casual Blazer - 40",
        "product_id": 55677,
        "variation_id": 57619,
        "quantity": 1,
        "tax_class": "",
        "subtotal": "5895.00",
        "subtotal_tax": "0.00",
        "total": "5895.00",
        "total_tax": "0.00",
    ] as AnyObject
]

Alamofire.request("https://infinitymegamall.com/wp-json/wc/v2/orders",method: .post,  parameters: parameters)
    .responseJSON{  response in
        if let json = response.result.value {
            print(json)
        }
    }

A: Are you sure your API Keys have write permissions? If GET works, it's possible that the key allows read only. Double check the permissions in your Woocommerce API Settings.


text:
Q: How to access custom command line options from within a Catch2 test case? I added my own command line option using a custom main file†:
†https://github.com/catchorg/Catch2/blob/master/docs/own-main.md#adding-your-own-command-line-options
  // ...
  auto cli
    = session.cli() // Get Catch's composite command line parser
    | Opt( height, "height" ) // bind variable to a new option, with a hint string
        ["-g"]["--height"]    // the option names it will respond to
        ("how high?");        // description string for the help output

  // ...
}

Now I want to use the height command line option from within a test case. What would be the best way to do this?


text:
Q: Using require() with Ionic V1 I am building an e-commerce mobile application with Ionic V1. I am integrating Instamojo as the payment gateway provider. They provide a npm module https://www.npmjs.com/package/instamojo-nodejs for integration with node applications. However, to us this module we have to make use of the require() functionality.

var Insta = require('instamojo-nodejs'); Insta.setKeys(API_KEY,
  AUTH_KEY);

While trying to use this, I get an error that require is undefined. Can someone, help me out with how to use this in an Ionic v1 app?


text:
Q: Swift 3 FSCalendar select all dates by default I am able to select certain dates while loading the FSCalendar. But I want to load calendar with all dates selected.
var attendance_list = [NSManagedObject]();
//After loading data
for attendanceObj in attendance_list{

            let createdDate =   attendanceObj.value(forKey: "date") as! String;
            self.calendar.select(Utils.convertStringToDate(createdDate))
}

Above code is for selecting dates from an array.
How can I select all dates without any array ?

A: I wouldn't recommend selecting all dates since the beginning of time to the end of the foreseeable future (also, you cannot do it without an array). What I would recommend is getting the beginingOfMonth and endOfMonth (both methods are available) in currentPageDidChange (another available method). Then set the dates between these two dates to selected inside a loop.


text:
Q: raytracing in python: intersection of a polygon and a ray This seems like a common graphics problem, but I don't seem to find anything that does what I want in python:
I have many 4-vertex polygons in 3D space and need to calculate for a given ray which of the polygons is intercepted first and where. So it is basically ray-tracing of those surfaces to see which is in front. I want to do that for a x-y grid of rays to calculate an image. Below is some simple sample data and I would want to basically see two squares where one overlaps the other. I can do that with a 3D plot, but I need the actual values for a given ray, so for example for a y-directed ray from x=0.75, z=0.75, I need to find the y value where the foremost polygon is hit.
Hope this problem is clear. Ideally only common libraries like scipy, numpy, ... are used, but any help is appreciated!
The 5th point in the example-polygons below is just to plot a closed shape.
square1 = np.array([
    [0, 0, 0],
    [1, 0, 0],
    [1, 0.5, 1],
    [0, 0.5, 1],
    [0, 0, 0]])

square2 = square1 + 0.5 * np.ones_like(square1)

# 3D plot of this projection

fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(projection='3d', proj_type='ortho')
ax.set_xlim(-1, 2)
ax.set_ylim(-1, 2)
ax.set_zlim(-1, 2)
#ax.axis('off')
ax.plot(*square1[:,:].T)
ax.plot(*square2[:,:].T)
ax.view_init(elev=0., azim=-90)

# 2D plot of the projection

f, ax = plt.subplots()
ax.set_aspect('equal')
ax.plot(*square1[:,[0,2]].T)
ax.plot(*square2[:,[0,2]].T)
ax.set_xlim(-1, 2)
ax.set_ylim(-1, 2)


text:
Q: How to configure the 500 error page in magento 2 Is there a way to set up a custom 500 page error in magento 2?
I tried to add a 500.phtml file in the pub/errors/default directory but this method only works with 404 errors and maintenance error 503.
I also tried to modify the .htaccess file by adding this line ErrorDocument 500 500.html, but invain.
For more information, I would like to customize this kind of 500 errors.

A: Try add a 500.php (with your custom code) in the pub/errors folder and add this line in the
/pub .htaccess file ErrorDocument 500 /errors/500.php
Hope this help.


text:
Q: Print catcodes in LaTeX with LaTeX3 I have the following MWE which prints the catcode of every character in the list.
The input method is:
\MyList{`+,{`,},`\%,`a}

but I want to simplify as follows:
\MyList{+,{,},\%,a}

Here the MWE:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xparse,expl3}
\ExplSyntaxOn

\cs_new:Npn \catcode_print:n #1
 {
  The~catcode~of~\tl_to_str:n {#1}~is~\char_value_catcode:n {#1} \par
 }
\NewDocumentCommand { \MyList }
 { > { \SplitList { , } } m }
 { \ProcessList {#1} { \catcode_print:n } }
\ExplSyntaxOff
\begin{document}
 \MyList{`+,{`,},`\%,`a}
% \MyList{+,{,},\%,a}
\end{document}

EDIT and PS:
I want to inverse the number to get the corresponding character:
For example:
\tex_number:D A prints 65. But I want to insert 65 and with the result A

A: Not expandably, of course:
\def\achar#1{\begingroup\lccode`!=#1\lowercase{\endgroup!}}

\achar{65}
\achar{`A}
\achar{"41}

will give

A A A

But of course
\char<number>

does the same. The \achar technique can be useful if you want to define a macro to expand to the character given by number (with category code 12):
\def\achar#1#2{\begingroup\lccode`!=#2\lowercase{\endgroup\def#1{!}}}

\achar\firstA{65}
\achar\secondA{`A}
\achar\thirdA{"41}
\show\firstA \show\secondA \show\thirdA

What does \achar do? It starts a group where the lowercase correspondent of the exclamation character is set to character #2 (which is supposed to be a number, in any of the formats TeX allows for specifying an integer constant). This correspondance is maintained by an array (a 256 component vector, in 8 bit TeX, the whole 0x110000 of Unicode for XeTeX and LuaTeX, from 0x0000 to 0x10FFFF): the n-th entry specifies the lowercase correspondent for character number n.
When we say \lowercase{<tokens>}, TeX performs the substitution of each character token with its lowercase correspondent and then inserts back in the input stream the token list so obtained, to be read again. In our case \endgroup, \def and the first argument to \achar are not touched, as they are not character tokens, so only ! is converted, exactly to the character having the number we specified in the second argument. Notice that TeX still hasn't executed \endgroup: it does only when the token list is put back. So the group is closed, the \lccode assignment is forgotten and the \def is executed.
With \achar\firstA{65}, for example, the replacement text for \firstA is A with category code 12, because ! has category code 12 and \lowercase doesn't change this attribute.
The LaTeX3 code is just the same:
\NewDocumentCommand { \achar } { m m }
  {
    \group_begin:
    \char_set_lccode:nn { `! } { #2 }
    \tl_to_lowercase:n { \group_end: \cs_new:Npn #1 { ! } }
  }


text:
Q: voice to sign language translation i am using two activities in my program.In first activity i done coding of voice to text and in second activity i done coding for text to sign langauge i linked it through button.but it doesn't move to another activity.I want this that the textveiw of voice recongnition to be shown on another activity.Please help
fist java code of voice recongnizer
package com.authorwjf.talk2me;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    protected static final int REQUEST_OK = 1;
    public static String EXTRA_MESSAGE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
         Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
         i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
         try {
             startActivityForResult(i, REQUEST_OK);
         } catch (Exception e) {
             Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
         }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_OK  && resultCode==RESULT_OK) {
            ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            ((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
        }
    }
    public void sendMessage(View view) {
        // Do something in response to button
            Intent intent = new Intent(MainActivity.this, Second.class);
            EditText editText = (EditText) findViewById(R.id.text1);
            String message = editText.getText().toString();
            intent.putExtra(EXTRA_MESSAGE, message);
            startActivity(intent);
    }

}

this is xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="132dp"
        android:text="..." />

    <ImageButton
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text1"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:layout_marginTop="37dp"
        android:src="@android:drawable/ic_btn_speak_now" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/text1"
        android:layout_alignBottom="@+id/text1"
        android:layout_alignLeft="@+id/button1"
        android:text="Enter" />

</RelativeLayout>

this is my second activity
package com.authorwjf.talk2me;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

@SuppressLint("NewApi")
public class Second extends Activity {

    // View Objects
        Button translate;
        EditText enterText;
        TextView displayText;
        ImageView aslImages;
        MediaPlayer mP;
        Second thisClass;
        // Variables for Translation and Display
        int phraseIndex = 0; // Keep track of the array indexes
        String letters; // Message to be Translated
        String display; // Will hold the letters already displayed and show them
        String PhraseIndex;
        // Array Libraries For Characters and Image References
        String letterIndex[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
                "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
                "x", "y", "z", "hello", "hi", "happy", "sad", "dad", "mom", "school", " " };

        int aslPics[] = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
                R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h,
                R.drawable.i, R.drawable.j, R.drawable.k, R.drawable.l,
                R.drawable.m, R.drawable.n, R.drawable.o, R.drawable.p,
                R.drawable.q, R.drawable.r, R.drawable.s, R.drawable.t,
                R.drawable.u, R.drawable.v, R.drawable.w, R.drawable.x,
                R.drawable.y, R.drawable.z, R.drawable.hello, R.drawable.happy, R.drawable.sad,
                R.drawable.dad, R.drawable.mom, R.drawable.school, R.drawable.space };

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            thisClass = this;
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // Show the Up button in the action bar.
            setupActionBar();
             // Get the message from the intent
            Intent intent = getIntent();
            String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

            // Create the text view
            TextView textView = new TextView(this);
            textView.setTextSize(40);
            textView.setText(message);

            // Set the text view as the activity layout
            setContentView(textView);

            // Attach objects to view objects
            translate = (Button) findViewById(R.id.buttonTranslate);
            translate.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    setString(v);
                    translateLetter();
                }
            });
            enterText = (EditText) findViewById(R.id.textInput);
            displayText = (TextView) findViewById(R.id.displayText);
            aslImages = (ImageView) findViewById(R.id.aslViewer);
            aslImages.setOnClickListener(new View.OnClickListener() {

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

            // Select all the Text in the enterText Field
            enterText.setSelectAllOnFocus(true);
        }

        // setString Function
        // Acts when the Translate Button is pressed
        public void setString(View v) {
            // Set the text of displayText to'--- '"
            displayText.setText("   ----");

            // Reset the Phrase Index
            phraseIndex = 0;
            display = "";

            // Get the Input Text
            String phrase = enterText.getText().toString();
            letters = phrase.toLowerCase();
        }

        // Displays Image when ImageView Touched.
        // Also displays text of letters already translated

        public void translateLetter() {
            // Checks if letters string is null-displays message
            // If the phrase has not been converted to a string
            if (letters == null) {
                displayText.setText("Press the Translate Button ");
            }

            // Checks if letters string is null-will not display
            // ASL letters until translate Button is pressed
            if (letters != null) {
                // Fetch the current Character in the phrase
                String currentLetter = letters;

                // add the letter to the display string
                display += currentLetter;

                // Search for the corresponding ASL image by Index
                for (int i = 0; i < letterIndex.length; i++) {
                    if (letterIndex[i].contentEquals(currentLetter)) {
                        // Display the image
                        aslImages.setImageResource(aslPics[i]);
                    } // end if
                }// end for
                    // Set the text to display the letters translated
                displayText.setText("   " + display);
                // Advance to the Next Letter in the Phrase
                phraseIndex++;

                // Check to see if you reach the end of the phrase
                if (phraseIndex > letters.length() - 1) {
                    // Reset back to the first character
                    phraseIndex = 0;
                    display = "";
                } // end if
            }// end Function translateLetter()
        }// end if

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.activity_main, menu);
            return true;
        }
        /**
         * Set up the {@link android.app.ActionBar}.
         */
        private void setupActionBar() {

            getActionBar().setDisplayHomeAsUpEnabled(true);

        }

        @SuppressLint("NewApi")
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                // This ID represents the Home or Up button. In the case of this
                // activity, the Up button is shown. Use NavUtils to allow users
                // to navigate up one level in the application structure. For
                // more details, see the Navigation pattern on Android Design:
                //
                // http://developer.android.com/design/patterns/navigation.html#up-vs-back
                //
                NavUtils.navigateUpFromSameTask(this);
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

}

this is second xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/aslViewer"
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:layout_span="2"
            android:onClick="translateletter"
            android:contentDescription="@string/hand_images"
            android:src="@drawable/a" />

    </TableRow>

<TableRow
    android:id="@+id/tableRow3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/displayText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_span="2"
        android:text="@string/T_text"/>
    </TableRow>

<TableRow
    android:id="@+id/tableRow2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/buttonTranslate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:onClick="setString"
       android:text="@string/Translate"/>

    <EditText
        android:id="@+id/textInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/Enter_Text" >

    </EditText>

</TableRow>

</TableLayout>

this menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.authorwjf.talk2me"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.authorwjf.talk2me.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity
            android:name="com.authorwjf.talk2me.Second"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.authorwjf.talk2me.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.authorwjf.talk2me.MainActivity" />
        </activity>
    </application>

</manifest>

A: I think you forgot to call sendMessage(View view) on button click.
add android:onClick="sendMessage" for button2.
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/text1"
    android:layout_alignBottom="@+id/text1"
    android:layout_alignLeft="@+id/button1"
    android:text="Enter"
    android:onClick="sendMessage" />

Also, for safty check for button1,
@Override
public void onClick(View v) {
    if(v.getId()==R.id.button1){
        //Your code
     }
}

Inside second activity, I don't think the use of setContentView(textView); is correct. You may get NullPointerException after this line. I think a 'Toast' is enough. Or declare TextView inside xml instead of dynamic creation.


text:
Q: How to schedule MySQL event during weekend days I would like to trigger an update during the weekend but I failed with many attempts.
I am looking for something like this:
CREATE EVENT on_weekend
ON SCHEDULE EVERY 1 MINUTE
STARTS 'e.g., every Saturday 00:00' ENDS 'e.g., every Monday 00:00'
DO Update...;

A: please try this,
ON SCHEDULE EVERY 1 WEEK STARTS '2014-11-23 12:20:01' ENDS '2015-01-31 12:20:01'

please see [http://www.java2s.com/Code/SQL/Event/Eventscheduleeveryweek.htm]


text:
Q: Swashbuckle Swagger UI padlocks with OAS3 I have an ASP.Net Core Rest Web API documented with Swashbuckles's Swagger generation (.net v5 and Swashbuckle.AspNetCore v5.6.3). It generates Swagger documentation and UI with OAS3 support.
Also my API uses JWT bearer tokens. So, I added this code to the swagger configuration:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
    In = ParameterLocation.Header,
    Name = "Authorization",
    Type = SecuritySchemeType.ApiKey,
    Description = "Put `bearer` keyword in front of token"
});

options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
    {
        new OpenApiSecurityScheme()
        {
            Reference = new OpenApiReference()
            {
                Id = "Bearer",
                Type = ReferenceType.SecurityScheme
            }
        },
        Array.Empty<string>()
    }
});

And as expected, it added the authorization capability to the Swagger UI:

But I also noticed a few padlocks next to every HTTP request.
They are unlocked before authorization:

And after authorization they lock:

How could I get these padlocks to signal if authorization is required or not (I think I've seen the same padlocks somewhere doing this and it seems pretty natural to them to do this kind of thing as well)?
Already tried something like that, but it did not work (request headers no longer contained the jwt token):
options.OperationFilter<SecurityRequirementsOperationFilter>();

I figured out that the problem is that my Swagger is using OAS3 and SecurityRequirementsOperationFilter depending on OAS2. I've tried looking for alternatives, but it looks like there are no similar tools for OAS3.
What should I do?
Should I forget this feature? But that looks like the only purpose of these locks.
Are there any ways to have this feature and stay with OAS3 (also I not sure if I really need OAS3 support that much).

A: After some research, I found the answer here: https://stackoverflow.com/a/61365691/13851956.
So the code is:
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
    Description = "No need to put the `bearer` keyword in front of token",
    Type = SecuritySchemeType.Http,
    Scheme = "bearer",
    BearerFormat = "JWT"
});
options.OperationFilter<AuthorizationOperationFilter>();

public class AuthorizationOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var actionMetadata = context.ApiDescription.ActionDescriptor.EndpointMetadata;
        var isAuthorized = actionMetadata.Any(metadataItem => metadataItem is AuthorizeAttribute);
        var allowAnonymous = actionMetadata.Any(metadataItem => metadataItem is AllowAnonymousAttribute);
        if (!isAuthorized || allowAnonymous)
        {
            return;
        }

        operation.Parameters ??= new List<OpenApiParameter>();
        operation.Security = new List<OpenApiSecurityRequirement>
        {
            new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Id = "Bearer",
                            Type = ReferenceType.SecurityScheme
                        }
                    },
                    Array.Empty<string>()
                }
            }
        };
    }
}

The result is that padlocks appears only next to actions that a marked with [Authorize] and not marked with [AllowAnonymous] attributes:


text:
Q: Div border-radius flickers during css transform I have a pretty simple web page I'm using as a playground for the Angular-Material package. It includes the following section:

HTML:

  C. Monster
  C is for Cookie, and Cookie is for me.
  1 day ago

SCSS:
div.community-photo {
    position: relative;
    width: 60px;
    height: 60px;
    overflow: hidden;
    border: 1px solid transparent;
    border-radius: 50%;

    img {
        position: absolute;
        width: 120px;
        left: -40%;
        border-radius: 50%;
    }
}

On other parts of the page I have some elements (a FAB, various Material Design buttons) that use CSS transforms to achieve effects like buttons sliding out, transparent bubbles and so forth.

<md-fab-speed-dial md-open="social.isOpen" md-direction="left" class="md-fling fixed-low-right" hide-sm show-md show-lg show-gt-lg>
    <md-fab-trigger>
        <md-button aria-label="Social Links" class="md-fab md-warn">
            <md-tooltip md-direction="top">Like Us!</md-tooltip>
            <md-icon class="material-icons"></md-icon>
        </md-button>
    </md-fab-trigger>
    <md-fab-actions>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">Facebook</md-tooltip>
            <md-icon class="fa fa-lg fa-facebook"></md-icon>
        </md-button>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">Twitter</md-tooltip>
            <md-icon class="fa fa-lg fa-twitter"></md-icon>
        </md-button>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">Pinterest</md-tooltip>
            <md-icon class="fa fa-lg fa-pinterest"></md-icon>
        </md-button>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">Instagram</md-tooltip>
            <md-icon class="fa fa-lg fa-instagram"></md-icon>
        </md-button>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">YouTube</md-tooltip>
            <md-icon class="fa fa-lg fa-youtube"></md-icon>
        </md-button>
        <md-button class="md-fab md-raised md-mini" href="">
            <md-tooltip md-direction="top">LinkedIn</md-tooltip>
            <md-icon class="fa fa-lg fa-linkedin"></md-icon>
        </md-button>
    </md-fab-actions>
</md-fab-speed-dial>

This element uses Javascript to apply a style tag with opacity: 1; z-index: 6; transform: translateX(56px); to the buttons when hidden, which it removes when they slide out. A transition: all 0.3s cubic-bezier(0.55, 0, 0.55, 0.2) CSS style provides the animation.
Strangely, when I use any of these elements, from the time the CSS transform animation begins until the time it ends, the border-radius on my div flickers off. It looks like this:

It only looks like that for 1 second, until the CSS transform finishes, but it's a flicker and it's making me sad. The actual CSS attribute doesn't get changed by Javascript or anything, it just flickers.
Just to be clear, it is definitely the border-radius attribute that is malfunctioning and nothing else. The picture itself is much bigger, so I know that the overflow: hidden is staying intact. It's not jumping to the right, so I know the absolute positioning is fine. But for some reason, the border-radius is flickering off momentarily.
Why might this be happening? I know that there are other ways to add a rounded picture to my site (CSS background, for example) but this way seems like the most intuitive and I'd like to keep it.
I have tried adding !important to the border-radius style and it doesn't change anything. However, if I remove the position: absolute; style from the img tag, it doesn't flicker. Therefore, it must be some interaction of position: absolute;, border-radius and transform which is causing the problem.

A: Hopefully someone out there has a better answer, but I've discovered a good workaround.
Change the style for the img tag from this:
position: absolute;
left: -40%;

To this:
margin-left: -40%;

(Removing the position: absolute style.)
This does the same thing and won't flicker.

A: I think there is a bug with using position and border-radius together. Its reported in answers on these questions as well, where when people removed the position property the border-radius worked fine. StackOverflow Question 1 and this one also- StackOverflow Question 2

A: Just add:
-webkit-backface-visibility: hidden;

into the css.


text: Q: Virtualhost apache set document root but serve other files not in root I have this scenario where I need the document root to be public but also the folder test should be served from the same domain. I achieved this using RewriteConditions inside  but when redirected i dont want the folder to be shown so basically when document root is set to public it serves public and if I go to browser I can see that, but if I use rewrite rules it redirects to public but the domain is switched to domain.com/public/(whatever_file) . Is it possible to do that just with virtual hosts and not the rewrite. Ah also I do not want to create more VirtualHosts. cause these to folder will be related.


text:
Q: How to call WEB API with a list of data for delete method I'm trying to make a delete WEB API call through angular $http, and i want to send a list of Ids to my API method.
Here is my angular call.
function deleteItem(id) {
            return $http({ url: delete_Url, data: {itemIds:[id]}, headers: { 'Content-Type': 'application/json' }, method: "DELETE" });
        }

WebAPI
[Route("/product/items")]
        [HttpDelete]
        public HttpResponseMessage RemoveItems( List<Guid> itemIds)
        {
            .....
        }

Problem is I'm getting nothing into my itemIds List
thanks


text:
Q: Motivation for triangle inequality Triangle inequality is used in one context or the other in analysis.
To list a few
$$ \|x+y\| \leq \|x\| + \|y\| $$
$$ d(x,y) \leq d(x,z) + d(z,y) $$
$$ \mu(A \cup B) \leq \mu(A) + \mu(B) $$
What is the motivation for imposing this? Intutively, it feels if we do not impose triangle inequality, the space will collapse to a trivial space in some sense. I am not able to express this formally. I would appreciate if someone could could throw some light on this and the motivation for triangle inequality?

A: It seems I can't add comments so I decided to post this as an answer, I apologize if it seems trivial or redundant. My point of view is that most occurrences of this inequalities are just minimum principles (something you could summarize as "min $\le$ any"). In each case, the quantity (distance, norm, dimension, cardinal...) can be viewed as a minimum :

*

*The distance between two points is the length of the shortest path between them

*The dimension of a vector space smallest size for a system of generator

*The cardinal of a set is the smallest $n$ for which your set can be embedded in $[\!|1,n|\!]$
...
In that setting, the triangle inequality more or less states that the right hand side correspond to a possibility (of path, generating set, embedding...) :

*

*A path from $x$ to $z$ and then $z$ to $y$ is a path from $x$ to $y$.

*The union of a generating sets gives a generating set for the sum.

*If you can embed $A$ in $A'$ and $B$ in $B'$ then $A \cup B$ can be embedded in the disjoint union of $A'$ and $B'$
...

A: In the context of normed spaces, subadditivity ensures local convexity, and that the Hahn-Banach theorem can be applied.  For example, $L^p[0,1]$ with $0<p<1$ is not locally convex, and worse, it has no nonzero continuous linear functionals.  If you try to define a "norm" by $\|f\|_p = \left(\int |f|^p\right)^{1/p}$, it is not subadditive, although it does satisfy $\|\lambda f\|_p=|\lambda|\|f\|_p$ if $\lambda$ is scalar.  You can instead define a metric by $d(f,g)=\int |f-g|^p$, which gives $L^p$ the structure of an F-space.  The triangle inequality is thus fixed, but the scalars no longer come out nice, and local convexity is lost regardless.
There is in fact a "reverse Minkowski inequality": if $f$ and $g$ in $L^p$ are nonnegative, $0<p<1$, then $\|f\|_p+\|g\|_p\leq \|f+g\|_p$.

A: Any reasonable notion of distance satisfies the triangle inequality, since if you can get from point $A$ to point $B$ using a route of length $d(A, B)$ and from point $B$ to point $C$ using a route of length $d(B, C)$, you can clearly get from point $A$ to point $C$ using a route of length $d(A, B) + d(B, C)$, and the optimal route (of length $d(A, C)$) therefore can't be any longer than this. (This argument is completely rigorous in an intrinsic metric, but there's no reason not to take it as motivation in general.)
Lawvere noticed that the above argument looks an awful lot like composition of morphisms in a category, and that led him to the categorical definition of metric spaces as certain kinds of enriched categories. From this perspective neither the symmetry nor the positive-definiteness axioms are particularly natural, but the triangle inequality is still very natural.
@Rasmus: letting $x = y$ in the reverse triangle inequality gives $0 \ge 2d(x, z)$, so the only "reverse metric space" is a point.


text:
Q: Inequality regarding the $2$ norm of the off diagonal elements of a matrix and its eigenvalues. Let,  $M = (m_{i,j}) \in \mathbb{C}^{n \times n}$ and let $O(M)$ consist of the off diagonal elements of $M$, where the main diagonal element of $O(M)$ is zero. Show that for every eigenvalue $\lambda_j(M)$ there exists an element $m_{k,k}$ so that:
$$|m_{k,k} - \lambda_j(M)| \le ||O(M)||_{2}.$$
Recall that,
$$||O(M)||_{2} = ||O(M)^{*}||_{2}.$$
By the Gershgorin circle theorem, there exists a $k \in \mathbb{N}$ such that:
$$|m_{k,k} - \lambda_j(M)| \le \sum_{i \ne k}|m_{k,j}|.$$
Observe that,
$$||O(M)||_{2} = ||O(M)^{*}||_{2} \ge ||O(M)^{*}e_{k}||_{2} \ge \sum_{i \ne k}|m_{k,j}|,$$
where $e_{k}$ is the $k$'th elementary vector. Thus,
$$|m_{k,k} - \lambda_j(M)| \le ||O(M)||_{2}.$$
Does my proof look good? Any mistakes? Thanks!


text:
Q: How to Log Console Screen into a Text File?
Possible Duplicate:
Mirroring console output to a file

I've a console application in C# and I want to Log into a text file every text appears on the screen. How to do that ?
Unfortunately this thread is closed despite of my comment about the Mirroring console output to a file. The accepted post as answer by that thread IS NOT CORRECT. So why cannot ask the question again? I'm using console interactively and want a copy of all the text on console in a text file. SOS

A: C:\>yourconsoleapp.exe > yourtextfile.txt

edit:  This assumes your console app requires no user input.

A: Replace all references to the Console class with the System.Diagnostics.Trace class.  You can add a ConsoleTraceListener and a TextWriterTraceListener, and then everything you output to the console will end up in both places.

A: You could use Console.SetOut to redirect the output to a file, but then you wouldn't get output to the console as well unless you used a TextWriter that streamed to both.
You could try using System.Diagnostics.Trace and then adding listeners to both the console and a file.
<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="configConsoleListener"
             type="System.Diagnostics.ConsoleTraceListener" />
        <add name="fileLogger"
             type="System.Diagnostics.TextWriterTraceListener"
             initializeData="LogFile.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
 </configuration>

A: This may be overly simplistic, but at a command prompt, if you do:
C:\>MyApplication >> output.txt

That will write all output from that given app to output.txt
If you don't actually need a programmatic solution, this might do the trick.

A: A simple Google search result : here
Sorry I am no longer programming with C# but I checked to code and it does make sense in this approach :)

A: Use log4j.

*

*Go to log4j website and download dll.

*Reference dll in your project.

*Add this to top of your app.config

<appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log-file.txt" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] -%message%newline" />
    </layout>
</appender>

<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] -%message%newline" />
    </layout>
</appender>

*

*Put this as a member of any class you want to log to:
private static readonly ILog log = LogManager.GetLogger(typeof(Foo));

*Put in a line like this to log:

log.Debug("Hello world!");


text:
Q: How to show Array inside array API data on Angular I'm trying to show the data of this API https://swapi.dev/api/people/
{
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
        },
 ]
}

but I always get this error :
How to show it like name and then when someone presses the button to character detail page that shows all detail of the API data on Angular? Thank you!
actor.service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ActorService {

  apiUrl = 'https://swapi.dev/api/people/'

  constructor(private http: HttpClient) { }

  tester(){
    this.http
    .get('https://swapi.dev/api/people/')
    .subscribe(data => {
      console.log(data);
    })
  }

  getActors(){
    return this.http.get(`${this.apiUrl}`);
  }

  getActor(name: string){
    return this.http.get(`${this.apiUrl}/${name}?per_page=10`);
  }
}

actor-list.component
import { Component, OnInit } from '@angular/core';
import { ActorService } from 'src/app/core/services/actor.service';

@Component({
  selector: 'app-actor-list',
  template: `

            {{ actor.results.name }}

              {{ actor.results.name }}

  `,
  styles: [
  ]
})
export class ActorListComponent implements OnInit {
  actors;

  constructor(private actorService: ActorService) { }

  ngOnInit() {
    this.actors = this.actorService.getActors()
  }

}

actor-single.component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ActorService } from 'src/app/core/services/actor.service';

@Component({
  selector: 'app-actor-single',
  template: `

{{ actor.results.name }}

  `,
  styles: [
  ]
})
export class ActorSingleComponent implements OnInit {
actor
  constructor( private actorService: ActorService, private route: ActivatedRoute) { }

  ngOnInit(): void {

    this.route.params.subscribe(params => {
      const actorname = params['actorname'];
      this.actorService
      .getActor(actorname)
      .subscribe(actor => this.actor = actor)
    });
  }
}

A: I think you misunderstood the structure of the api response. There is no field result in a single actor. So actor name should be

{{ actor.name }}

and response is an object with all actors in results property. So you can iterate through actors like this

A: I tried to reproduce your source code, you used wrong property for object.
It should be *ngFor="let actor of actors.results" and change from actor.results.name to actor.name
Demo code https://stackblitz.com/edit/angular-ivy-jjh9mx


text:
Q: What's an alternative to the "functional" package for the function composition operation? In particular, I'm looking for a package w/ support for function composition.
Googling around, there's a lot of references to Collin Winter's functional and its compose() function. However documentation for that is gone: http://www.oakwinter.com/code/functional/
which doesn't lend me much confidence in its continued support.
A few references such as https://mathieularose.com/function-composition-in-python/ provide relatively simple hand-rolled implementation. However, unless it's absolutely necessary, I'd rather go with an existing library of there's one that the community is converging around rather than reimplementing such a basic operation.

A: I'm a big fan of toolz and use it a lot in both personal projects and at work. It's actively maintained, well documented, and seems to be quite mature despite the 0.x version number.
It offers a compose function that might be what you're looking for.
For example:
from toolz import compose

add_one = lambda x: x + 1
square = lambda x: x**2

# Add 1, then square
compose(square, add_one)(2)  # == 9


text:
Q: Ajax not being fired? I'm using the jquery validator plugin, and I'm trying to make my first attempt with AJAX to it.
Right now, I have the following HTML code:

Inserir nova página

                <form id="formulario" class="block-content form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">

Nome da página<input id="page_name" name="textfield" class="required text" type="text" value="" />

Conteúdo da página<textarea id="page_content" name="textarea" class="required uniform" rows="5" cols="40"></textarea>

Limpar

<input type="submit" class="button" name="send" value="Inserir">

And my JS code:


text:
Q: How to select elements for Frank using UIQuery/UISpec? I've been using Frank automation tool to write tests for iOS using cucumber. If I understand correctly, I can point to the different UI elements using UIQuery selectors. I've had a hard time finding documentation about these selectors. How exactly do they work?
Particularly, right now I'm trying to select a UITextField which the Symbiote Frank inspector identifies as UITextField with label "UserName". I've explicitly set that identifier with Xcode using the Accessibility Label property. I've seen that by default, Frank uses the placeholder property to refer to the UITextFields but I don't want to use that.

A: This is a partial response to the particular problem I had regarding how to refer to items by the accessibility label property. For a UITextField with the accessibility label set to UserName the selector "view marked: 'UserName'" seems to work.
The more general question about how selectors work is still open.

A: Consider using the Igor Query Language: https://github.com/dhemery/igor/wiki
I modeled Igor after CSS selectors, and added some syntax to handle some situations that CSS doesn't handle (e.g. "cousins" and selecting views based on the characteristics of their descendants).
The Igor syntax for your query would be:

UITextField[accessibilityLabel=='UserName']

The grammar for Igor is described completely on the wiki.  The wiki also has some examples, though probably not enough.


text:
Q: LWC, handle event null I have a Parent component which is a data table and a child component that is a combobox
For each record in the data table if the user click on an Edit button, then the combobox appear and give the ability to the user to select from a picklist value the one he wants to use.
So I have an event handler HandleEvent that handle the action of changing item selected in the combobox, to test my code and do it step by step. I defined my event that way with a console.log(event.detail.value) and for some reason I get a null !
here is my code:
Parent component:

                                    <template if:false={isEdited}>
                                        {item.Status}
                                    </template>
                                    <template if:true={isEdited}>
                                        <c-edit-picklist
                                        unique-key={item.Id}
                                        object-api-name="Lead"
                                        selected-value={item.Status}
                                        onvalueselect={handleSelection}>
                                        </c-edit-picklist>

                                    </template>

child component JS:
import { LightningElement, wire, api } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { getPicklistValuesByRecordType } from 'lightning/uiObjectInfoApi';

export default class EditPicklist extends LightningElement {

    value = 'inProgress';
    recordTypeId
    @api objectApiName
    @api selectedValue

    handleChange(event) {
        this.value = event.detail.value;
        console.log(event.target.value)
    }

    options = [
        { label: 'Default 1', value: 'Default1' },
        { label: 'Default 2', value: 'Default2' },
        { label: '--None--', value: "" }
    ];

    @wire(getObjectInfo, { objectApiName: '$objectApiName' })
    getRecordTypeId({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
            if(this.recordTypeId === undefined){
                this.recordTypeId = this.record.defaultRecordTypeId;
            }
            console.log("Default Record Type Id", JSON.stringify(this.record.defaultRecordTypeId));
        } else if (error) {
            this.error = error;
            this.record = undefined;
            console.log("this.error",this.error);
        }
    }

    @wire(getPicklistValuesByRecordType, { recordTypeId: '$recordTypeId', objectApiName: '$objectApiName' })
    wiredOptions({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
            let temp_option = []
            console.log("Picklist", this.record.picklistFieldValues.Status.values)
            this.record.picklistFieldValues.Status.values.forEach((element, index) => {
                var op = {label: element.value}
                temp_option.push(op)
            })
            console.log(temp_option)
            this.options = temp_option
            // if(this.record.picklistFieldValues[this.pickListfieldApiName] !== undefined) {

            //     let tempOptions = [{ label: '--None--', value: "" }];
            //     let temp2Options = this.record.picklistFieldValues[this.pickListfieldApiName].values;
            //     temp2Options.forEach(opt => tempOptions.push(opt));

            //     this.options = tempOptions;
            // }
            // //console.log("this.options pick", JSON.stringify(this.options));
            // if(this.selectedValue === '' || this.selectedValue === undefined || this.selectedValue === null) {
            //     this.value = { label: '--None--', value: "" }.value;
            // } else {
            //     this.value = this.options.find(listItem => listItem.value === this.selectedValue).value;
            // }
        } else if (error) {
            this.error = error;
            this.record = undefined;
            console.log("this.error",this.error);
        }
    }

}

I have no idea why it is Null and how should I set my HandleChange in order to provide the selected item to the parent component
If you could explain that I understand for the future it would be amazing
Thx youuu ;)

A: You're not building your options correctly in your wire method getPicklistValuesByRecordType for a combobox. You need a value and label.
You're just pushing labels which is why you see the options in the dropdown, but then have nulls (as there's no value you're pushing).
 this.record = data;
            this.error = undefined;
            let temp_option = []
            console.log("Picklist", this.record.picklistFieldValues.Status.values)
            this.record.picklistFieldValues.Status.values.forEach((element, index) => {
                var op = {label: element.value} //here is the culprit, only adding label and no value:
                temp_option.push(op)
            })

You should be able to do the following:
temp_option.push({
    label: element.value,
    value: element.value
});

You can tell if it's set correctly (with label + value) in that console log for temp_option.


text:
Q: How to create an array of objects in react? I am new to the react world. I am trying to write a code in which when an icon is pressed the Image is added into a favourite category and then on the favourite page the image should be displayed. I am having an issue with not knowing how to dynamically get the value out of the image and add them to favourite category without loosing the pervious value. I think the way I wrote states seems messed up. I write in typescript and use material UI
SearchResults
const [images, setImages] = useState([]);
const [favImage, setFavImage] = useState<ImageProps>({
    id: '',
    farm: 0,
    server: '',
    secret: '',
    title: ''
});

const handleFavImage = ({ farm, server, id, secret, title }: ImageProps): void => {
    setFavImage({ id, farm, server, secret, title });
};

ImageModal
const handleFavourite = (): void => {
    setIcon(!icon);
    if (!icon === true && handleFavImage !== undefined) {
        handleFavImage({ farm, server, id, secret, title });
    }
};

A: Use Image Id as reference.
Use redux store / local storage to store the fav image Ids.
Assuming you have all the images here:
const [images, setImages] = useState([]);

On click of the Icon, pass Image Id of the selected Image and iterate through the images array to find the image props.
just to make you understand how to use the component state array do to this operation:
Lets create a state which will store fav image ids
const [favImages, setFavImages] = useState([]);

On Click will look something like this
const handleOnClick = (imageId) => {
    var arr = [...favImages]; //copy array by value
    arr.push(imageId)
    setFavImages(arr) //override state with new values
}

Now the favImages array has the list of fav image ids.
Now, use this favImages in your favourite page component.
let favImageProps = props.images.filter(image => props.favImages.indexOf(image.id) !== -1)

A: I had the restriction for not using var and let in the code. So I had to change the code.
    const [images, setImages] = useState([]);
    const [favImage, setFavImage] = useState<ImageProps[]>([]);
    const handleFavImage = ({ farm, server, id, secret, title }: ImageProps): void => {
        setFavImage([...favImage, { id, farm, server, secret, title }]);
    };


text:
Q: Why System.Web.Services.Protocols.LogicalMethodInfo cannot be serialized in Azure caching? I'm getting error when I use azure caching but not using HttpRuntime.Cache:
Type 'System.Web.Services.Protocols.LogicalMethodInfo' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

After searching I noticed of this article that says "HttpRuntime.Cache doesn't serialize data at all"  What is the default serialization used by the ASP.net HttpRuntime.Cache

Sample Code:
protected void Page_Load(object sender, EventArgs e)
{
List<myclass> items = new List<myclass>();
MyClass item1 = new MyClass() { ID = 1 };
items.Add(item1);

HttpRuntime.Cache.Insert("test1", items); //working

DataCache cache = new DataCache("default");
cache.CreateRegion("reg");

cache.Put("test2", items, "reg");//error
}

}

public class MyClass
{
public MyClass()
{

Type myType = typeof(MyService);
MethodInfo myMethodInfo = myType.GetMethod("Add");
_log = new **LogicalMethodInfo**(myMethodInfo);
}
public int ID { get; set; }
public **LogicalMethodInfo** _log;
}

public class MyService
{
public int Add(int xValue, int yValue)
{
return (xValue + yValue);
}
}

A: You're getting that error because System.Web.Services.Protocols.LogicalMethodInfo is not serializable. In order to be added into the Azure cache the object must be serialized and sent across the network to the cache server. Obviously that can't be done with non-serializable objects. HttpRuntime.Cache is an in-memory data store. Because it's in-memory it doesn't need to serialize the objects, and hence doesn't care whether the cached objects are serializable.


text:
Q: Mousenter, leave function event jquery What's wrong with this code. It doesn't work.
$(".sider").on("mouseenter") function(event){
$(".sider-post").fadeIn(350);
}).on("mouseleave") function(event){
$(".sider-post").fadeOut(350);
});

Here's the html, the sider should be visible-the border, but the child should fade.
thanks

some content

Any ideas?

A: You are giving ) at the place of , after events.
Should be this
$(".siderr").on("mouseenter", function(event){
  $(".sider-post").fadeIn(350);
}).on("mouseleave", function(event){
   $(".sider-post").fadeOut(350);
});

DEMO

A: Use this
$(".siderr").mouseenter( function(event){
$(".sider-post").fadeIn(350);
});

$(".siderr").mouseleave( function(event){
$(".sider-post").fadeOut(350);
});

hope this may useful


text:
Q: Create HL7 v3 message in java I am new to hl7,
I have created application using hapi2.1 which is applicable to accept hl7 v2 messages & respond them now i want to accept also v3 messages.
Since hapi doesn't support v3 messages is there any way to accept hl7 v3 messages & respond them?
Is there any api available for hl7 v3 messages in java like hapi?

A: No, There is no API as yet developed for HL7 v3 messages, like hapi is for v2.x version, which I believe you are looking for an open source solution, and not hl7 proprietary. However, on the RIM side of healthcare developments, there is RIMBAA. You might be interested in knowing more about it here on this page.


text:
Q: firestore database reference doesnt work with await So I'm trying to use the twitter Api to test functionality and do specific tasks. I decided to use firestore to keep the relevant data. However when I create a database reference and try to use await later on in the code, it gives me an error. This is the code.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const {Firestore} = require('@google-cloud/firestore');
const firestore = new firestore();
const dbRef = firestore.doc('tokens/demo');

const TwitterApi = require('twitter-api-v2').default;
const twitterClient = new TwitterApi({
  clientId: 'clientid',
  clientSecret: 'clientsecret',
});

const callbackURL = 'http://127.0.0.1:5001/twbt-ad868/us-central1/callback';

// STEP 1 - Auth URL
exports.auth = functions.https.onRequest((request, response) => {
    const { url, codeVerifier, state } = twitterClient.generateOAuth2AuthLink(
      callbackURL,
      { scope: ['tweet.read', 'tweet.write', 'users.read', 'offline.access'] }
    );

    // store verifier
    await dbRef.set({ codeVerifier, state });

    response.redirect(url);
  });

exports.callback = functions.https.onRequest((request, response) => {

});

exports.tweet = functions.https.onRequest((request, respone) => {});

and this is the error I get
await dbRef.set({ codeVerifier, state });
^^^^^

SyntaxError: await is only valid in async function

I've tried using this code instead to reference the json file in firestore, but I still get the same error
const dbRef = admin.firestore().doc('tokens/demo');

I'm assuming this is because my program isn't properly accessing the database in firestore? When I run this command

gcloud firestore operations list

I get

Listed 0 items.

If this is the case I'm not sure how to fix this and have my code access the database properly
Thank you in advance for any help you can provide me.

A: You must create an async function in order to have an await since it requires a promise.
async function () { await dbRef.set({ codeVerifier, state });}


text:
Q: OpenLayers 3 icons projection I'm making a map with OpenLayers 3, I have coordinates (EPSG:3857) in PostgreSQL and the map layer is OSM (same projection that the icons, EPSG:3857).
The problem is that when I increment the zoom, the icons disappear... But if I decrement then the icons won't disappear.
Someone told me that the projection's ICONS and LAYER must be the same.
Can someone help me, please?
I'm new in StackOverFlow,
Thank you for your time,
Enrique.
Note: My code is in JSFiddle, can see here: jsfiddle.net/y3sLksg6/

A: Try to set the style to each of your markers individually as in the exaple below, which is a copy from your jsfiddle:
function AddMarkers() {
//create a bunch of icons and add to source vector
  var sizeY = Object.size(coordenadas);
  var x = null;
  var y = null;

  for (var i = 0; i < sizeY; i++) {
    x = coordenadas[i].Longitude;
    y = coordenadas[i].Latitude;
    var iconFeature = new ol.Feature({
        geometry: new ol.geom.Point([x, y]),
        name: 'Marker ' + i,
        population: 4000,
        rainfall: 500
    });
    markers[i] = [x, y];

    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(({
           anchor: [0.5, 46],
           anchorXUnits: 'fraction',
           anchorYUnits: 'pixels',
           opacity: 0.75,
           src: './img/circleRed.png'
       }))
    });
    // This is new !
    iconFeature.setStyle(iconStyle);

    vectorSource.addFeature(iconFeature);
 }
 return vectorLayer;
}


text:
Q: El promedio de todos los números múltiplos de 9 que se encuentran entre el 290 y 2200 Hola estoy aprendiendo en la programacion y tengo muchos problemas en la realización de este ejercicio, si alguien me pudiese ayudar, seria de gran ayuda.
using System;

namespace Ejercicio3
{
    class program
    {
        static void Main(String[] args)
        {
            int numero;
            Console.Write("Ingresar numero: ");
            numero = int.Parse(Console.ReadLine());
            Console.Write("Promedio de los numeros " + numero + "numeros multiplos de 9: " + (((numero * numero * 9) + (numero * 9)) /2) / numero);
            Console.ReadKey();
        }
    }
}

A: La verdad no se mucho del lenguaje, pero seguro si o si debes usar el operador resto % para encontrar la solución de los múltiplos de 9, despues un ciclo for, que recorra los el intervalo de los numeros, y por ultimo sacas el promedio, espero haberte podido ayudar


text:
Q: android AChartEngine: One bar with different color I am using the AChartEngine library to draw bar charts. What I need is for all bars to be in one color and only one bar to be in a different color.
What I have tried is having two XYSeries with one containing 0's.
This displays a gap between the bars as follows:
Could someone please tell me how do I achieve a continuous sequence of bars with just one with a different color?

A: Check Bar chart using achartengine thread. If this does not help check Different color bars using multiple series . I managed to do the same using the concept used by the asker in  second question. In addition I made
renderer.setBarSpacing(0);

A: Well I modified the source code to finally achieve this.
I modified the draw method of XYChart. I added colors for each bar. I found out which bar is in the center of the screen and added a different color for it.
The 'drawSeries' method in BarChart also has to be modified to set the paint color for the lines.


text:
Q: How to set up TortoiseHG with Fiddler2 as proxy server? I want to watch TortoiseHG's web requests to a Mercurial server, but I can't seem to configure it correctly so that I can see the activity from Fiddler. Here's what I've done:
Start Fiddler
TortoiseHg -> Global Settings -> Proxy
Host: 127.0.0.1:8888 (I confirmed within Fiddler that this is correct)
TortoiseHg -> Synchronize
Pull, preview incoming changes
Nothing shows up in Fiddler. Shouldn't I be seeing the requests and responses?
I'm running Windows 7 if that's any help.


text:
Q: grails install plugin blazeds failed due to unresolved dependencies I trying to integrate Flex with Grails through BlazeDS BUT i am stuck with the very first step i.e installing BlazeDS plugin ... it fails everytime i try to install. Following is the complete stacktrace
Resolving plugin JAR dependencies ...
:: problems summary ::
:::: WARNINGS
    module not found: com.adobe.flex#flex-messaging-opt;4.0.0.14931.1

==== grailsHome: tried

  D:\Platforms\Grails\grails-1.3.7\lib/flex-messaging-opt-4.0.0.14931.1.xml

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  D:\Platforms\Grails\grails-1.3.7\lib/flex-messaging-opt-4.0.0.14931.1.jar

==== grailsHome: tried

  D:\Platforms\Grails\grails-1.3.7\dist/flex-messaging-opt-4.0.0.14931.1.xml

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  D:\Platforms\Grails\grails-1.3.7\dist/flex-messaging-opt-4.0.0.14931.1.jar

==== grailsHome: tried

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  D:\Platforms\Grails\grails-1.3.7/plugins/grails-flex-messaging-opt-4.0.0.14931.1.jar

==== grailsCentral: tried

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://svn.codehaus.org/grails-plugins/grails-flex-messaging-opt/tags/RELEASE_4_0_0_14931_1/grails-flex-messaging-opt-4.0.0.14931.1.jar

==== grailsCore: tried

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://svn.codehaus.org/grails/trunk/grails-plugins/grails-flex-messaging-opt/tags/RELEASE_4_0_0_14931_1/grails-flex-messaging-opt-4.0.0.14931.1.jar

==== mavenCentral: tried

  http://repo1.maven.org/maven2/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://repo1.maven.org/maven2/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== ebrRelease: tried

  http://repository.springsource.com/maven/bundles/release/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://repository.springsource.com/maven/bundles/release/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== ebrExternal: tried

  http://repository.springsource.com/maven/bundles/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://repository.springsource.com/maven/bundles/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== http://maven.springframework.org/external: tried

  http://maven.springframework.org/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://maven.springframework.org/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== http://maven.springframework.org/milestone: tried

  http://maven.springframework.org/milestone/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://maven.springframework.org/milestone/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== ebrRelease: tried

  http://repository.springsource.com/maven/bundles/release/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://repository.springsource.com/maven/bundles/release/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== ebrExternal: tried

  http://repository.springsource.com/maven/bundles/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://repository.springsource.com/maven/bundles/external/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== http://maven.sinusgear.com/maven_repo: tried

  http://maven.sinusgear.com/maven_repo/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.pom

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  http://maven.sinusgear.com/maven_repo/com/adobe/flex/flex-messaging-opt/4.0.0.14931.1/flex-messaging-opt-4.0.0.14931.1.jar

==== grailsPlugins: tried

  -- artifact com.adobe.flex#flex-messaging-opt;4.0.0.14931.1!flex-messaging-opt.jar:

  D:\Work\Personal\Grails\todolist/lib/flex-messaging-opt-4.0.0.14931.1.jar

  C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\blazeds-2.0/lib/flex-messaging-opt-4.0.0.14931.1.jar

  C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\hibernate-1.3.7/lib/flex-messaging-opt-4.0.0.14931.1.jar

  C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\spring-security-acl-1.1/lib/flex-messaging-opt-4.0.0.14931.1.jar

  C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\spring-security-core-1.2.1/lib/flex-messaging-opt-4.0.0.14931.1.jar

  C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\tomcat-1.3.7/lib/flex-messaging-opt-4.0.0.14931.1.jar

    ::::::::::::::::::::::::::::::::::::::::::::::

    ::          UNRESOLVED DEPENDENCIES         ::

    ::::::::::::::::::::::::::::::::::::::::::::::

    :: com.adobe.flex#flex-messaging-opt;4.0.0.14931.1: not found

    ::::::::::::::::::::::::::::::::::::::::::::::

[delete] Deleting directory C:\Users\Akeel\.grails\1.3.7\projects\todolist\plugins\spring-security-core-1.2.1
Failed to install plugin [blazeds-2.0]. Plugin has missing JAR dependencies.

I would really appreciate if someone could help me resolving this issue. Thanks

A: I have faced same problem recently on grails 1.3.7. By somehow this problem was reproduced only in Windows but not in Ubuntu. So i just copy ivy cache from Ubuntu to Windows and now it's ok. I don't know can I place this jars on the internet, so anyway you can manually download them from some maven or ivy repository.

A: Add the following line to the repositories section of your BuildConfig.groovy file:
mavenRepo "https://src.springsource.org/svn/spring-flex/tags/spring-flex-1.5.0.RELEASE/local-repo/"

Adapted from this other SO question.

A: It is Windows' problem. It looks like a corrupt ivy cache. Just delete ivy-cache folder in .grails. For Windows 7, it's: C:\Users[USER NAME].grails\ivy-cache.
It will be regenerated when you use grails command. Hope it helps.