text:
Q: Special values of $p$-adic $L$-functions. This is a very naive question really, and perhaps the answer is well-known. In other words, WARNING: a non-expert writes.
My understanding is that nowadays there are conjectures which essentially predict (perhaps up to a sign) the value $L(M,n)$, where $M$ is a motive, $L$ is its $L$-function, and $n$ is an integer. My understanding of the history is that (excluding classical works on rank 1 motives from before the war) Deligne realised how to unify known results about $L$-functions of number fields and the B-SD conjecture, in his Corvallis paper, where he made predictions of $L(M,n)$, but only up to a rational number and only for $n$ critical. Then Beilinson extended these conjectures to predict $L(M,n)$ (or perhaps its leading term if there is a zero or pole) up to a rational number, and then Bloch and Kato went on to nail the rational number.
Nowadays though, many motives have $p$-adic $L$-functions (the toy examples being number fields and elliptic curves over $\mathbf{Q}$, perhaps the very examples that inspired Deligne), and these $p$-adic $L$-functions typically interpolate classical $L$-functions at critical values, but the relationship between the $p$-adic and classical $L$-function is (in my mind) a lot more tenuous away from these points (although I think I have seen some formulae for $p$-adic zeta functions at $s=0$ and $s=1$ that look similar to classical formulae related arithmetic invariants of the number field).
So of course, my question is: is there a conjecture predicting the value of $L_p(M,n)$, for $n$ an integer, and $L_p$ the $p$-adic $L$-function of a motive? Of course that question barely makes sense, so here's a more concrete one: can one make a conjecture saying what $\zeta_p(n)$ should be (perhaps up to an element of $\mathbf{Q}^\times$) for an integer $n\geq2$ and $\zeta_p(s)$ the $p$-adic $\zeta$-function? My understanding of Iwasawa theory is that it would only really tell you information about the places where $\zeta_p(s)$ vanishes, and not about actual values---Iwasawa theory is typically only concerned with the ideal generated by the function (as far as I know). Also, as far as I know, $p$-adic $L$-functions are not expected to have functional equations, so the fact that we understand $\zeta_p(s)$ for $s$ a negative integer does not, as far as I know, tell us anything about its values at positive integers.

A: Actually, p-adic L-functions are expected to satisfy functional equations compatible with the classical ones. For M an ordinary motive, Coates and Perrin-Riou conjectured the interpolation property at critical integers and the expected functional equation in some papers in the early nineties (see for example this). In particular, the Kubota-Leopoldt p-adic L-functions interpolate all critical values of the classical Dirichlet L-functions (up to a period and a multiple). For modular forms, Mazur-Tate-Teitelbaum, in their 1986 paper) prove a p-adic functional equation in section 17. In fact, the two-variable p-adic L-function of an ordinary family of modular forms satisfies a two-variable functional equation interpolating the one-variable functional equation at each weight (see for example Greenberg-Stevens' inventiones paper) (I'd post more mathscinet links but it appears to be down...).
As for the values of the p-adic L-function at non-critical integers, that's much more mysterious. Rubin has a computation outside of the critical points for a CM elliptic curve in section 3.3 of his paper in the "p-adic monodromy and BSD" proceedings. I think I've seen other cases, but generally it takes a lot of effort, I think.
(Also, regarding Iwasawa theory's concern with values of L-functions, it is true that the Main Conjecture is only an equality of ideals in some power series ring, but one can still hope to construct p-adic L-functions on the analytic side that do a nice job at interpolating, say up to a p-adic unit.)

A: Here's a nice expository article by Colmez on Perrin-Riou's conjectures:
http://people.math.jussieu.fr/~colmez/851bourbaki.pdf

A: Others have hinted at it, but let me emphasize the point. At least if you are happy to assume all conjectures (and perhaps that your motive has good reduction at $p$), the conjectural landscape for $p$-adic $L$-functions is as complete as that for usual $L$-functions. Namely: there is a conjectural description of the value of the cyclotomic $p$-adic $L$-function at any integer (in fact any character $\eta\chi_{cyc}^{s}$ with $\eta$ finite).
This can either be done in B.Perrin-Riou's style, see Fonctions $L$ $p$-adiques des représentations $p$-adiques, or in K.Kato's style, in which case it follows from the conjectures on special values of $L$-functions taking into account the action of a group algebra (the so-called equivariant conjectures). In fact, I exaggerate slightly here: at some special values, there could be an exceptional zero, in which case the leading term should incorporate an $\mathcal{L}$-invariant, and I don't think this has been (conjecturally) defined in all generality.
Also, as Rob H. wrote, $p$-adic $L$-function are indeed expected to satisfy a functional equation. This can be seen either from Perrin-Riou's conjectural construction from motivic elements, in which case the functional equation follows from the explicit reciprocity law of Perrin-Riou (and Colmez in the de Rham case) or via Iwasawa main conjectures, in which case it follows from duality results for cohomology complexes.
So everything you could wish for is conjectured. Not much, of course, is actually known.

A: I'd like to write a better response, but I must be brief.
For now, let me offer some places to read. Long story short, it is  predicted that there's a relationship between special values of $p$-adic $L$-functions and syntomic regulators (which are the analogue of Beilinson's regulators in the $p$-adic world).

*

*The beautiful paper of Manfred Kolster and Thong Nguyen Quong Do is, I think, a very readable resource.

*The best results I know in this direction are Besser's papers here and here, which use rigid syntomic cohomology.

*Besser's overview talk at the conference in Loen (notes available here) was a real joy.


text:
Q: Passing parameter to Action from Kendo grid toolbar using pure c# I need to add button to kendo grid toolbar which will show popup window on click. I also need to wrap this grid in a helper which will return grid with this button. The proplem is that I need to pass parameter to action which shows popup window (grid type to be specific), but I can't use razor syntax as this helper defined in *.cs file, and I can't find the way to do it by regular c#. Can I make this in some way? Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.UI;

namespace Test.WebUI.Helpers
{

public static class ExtendedGridHelper
{

    public static Kendo.Mvc.UI.Fluent.GridBuilder<T> ExtendedGrid<T>(this HtmlHelper helper, string name, Tuple<string, string> dataAccessing)
        where T : class
    {
        return helper.Kendo().Grid<T>()
            .Name(name)
            //.DataSource(src => src.Ajax().Read(read => read.Action("GetInstances", "ExtendedGrid")))
            .DataSource(src => src.Ajax().Read(dataAccessing.Item1, dataAccessing.Item2))
            .Sortable()
            .Pageable(it => it.PageSizes(true))
            .Groupable()
            .Filterable()
            .Reorderable(it => it.Columns(true))
            .Scrollable(it => it.Virtual(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
            .Columns(columns =>
            {
                foreach (var property in typeof (T).GetProperties().OrderBy(it => it.Name))
                {
                    columns.Bound(property.Name).Width(150);
                }
            }
                    )

            .ToolBar(toolbar =>
            {
                toolbar.Custom().Action("ViewPopup", "ExtendedGrid").Text("Settings").HtmlAttributes(new {@class = "modal-link btn btn-success"});
            //This way it works, but I nered to pass parameter.
            }

            );
    }

}
}

Here is an example of usage:
  @(Html.ExtendedGrid<ololo>("Grid1", new Tuple<string, string>("GetInstances", "ExtendedGrid")))

A: For send Parameter to action with kendo DataSource use this code
.DataSource(dataSource => dataSource.Ajax().Read(read => read.Action("Products_Read", "Grid").Data("additionalInfo"))

and in javascript get your json data
function additionalInfo() {
return {
    AdditionalParam : "test"
}

A: I figured this out, maybe it will be usefull for somebody. I just added this to resources:

Settings

and then:
var popupTemplate = Properties.Resources.ToolbarTemplate
            .Replace("~T~", typeof (T).ToString())
            .Replace("~userID~", userID)
            .Replace("~GridName~", name)
            .Replace("~ExportAction~", String.Format("/{0}/{1}", dataAccessing.Item2, dataAccessing.Item1));
.ToolBar(toolbar => toolbar.Template(popupTemplate));

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Logging and performance tuning library I need to performance analyse some real-time code on Windows.
I can't use any of the regular profilers (Vtune,Codeanalyst) because I can't slow the executable down. So I'm using my own timing class based on QueryPerformanceCounter().
Are then any existing (free) C++ libs to log the results - BUT I need them to be buffered to the end of a run, I can't afford the time to write to a file or event log while I'm collecting data.
Easy enough to roll my own, but if there is a way of making log4cplus / qDebug or similar log to a buffer and dump later it would save some effort.

A: I wrote a class that does this, too, because I couldn't find anything that did what I wanted but was still easy to incorporate in to existing code with copy-paste coding techniques.
(edit) Note that as mentioned in the comments, the act of timing itself changes the nature of what you're timing.  But then I'm sure you understand this all too well.  This class has still been very useful to me in finding hotspots & bottlenecks, in addition to giving me at least a rough high-side estimate of how long certain code takes to run.  The code I present here was never intended to be production-worthy.  Use it as such.
Here's a sample output of my class:
Timer Precision = 385 ns

=== Item               Trials    Ttl Time  Avg Time  Mean Time StdDev    ===
    DB Connect         1         0.11 s    0.11 s    0.11 s    0.0000 ps
    Entry Parse        3813      0.33 s    86 us     82 us     18 us
    File Load          1         50 ms     50 ms     50 ms     0.0000 ps
    Option Parse       1         5 ms      5 ms      5 ms      0.0000 ps
    Record Update      3812      0.53 s    140 us    127 us    49 us
============================================================================

Each "Item" is one section of code I wanted to time.  The Timer object uses RAII (via auto_ptr) to allow automatic start & stop.  Here's some sample client-side code demonstrating how to use it:
Sample Code:
int main(int ac, char* av[])
{
    std::auto_ptr<dbg::Timer> section_timer(new dbg::Timer("Option Parse"));
    // MAGIC: Parse the command line...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("File Load"));
    // MAGIC: Load a big file...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("DB Connect"));
    // MAGIC: Establish a DB connection...

    for( /* for each item in the file*/  )
    {
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Entry Parse"));
      // MAGIC: Parse the incoming item
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Record Update"));
      // MAGIC: Update the database
    }

    // Dump the output shown above

    cout << dbg::Timer::DumpTrials() << endl;
}

The implementation of this class is in an include library.  You don't need to compile anything.  I use Boost.Format to do the string formatting, but this could be replaced simply enough.
Here is the implementation (my actual implementation splits this in to two files, core.h and core_dbg.hpp; the latter is #includeed directly from the former).
Implementation:
namespace dbg
{
    class Timer
    {
    public:
        inline Timer(const std::string & name);
        inline Timer(const Timer& rhs);
        inline virtual ~Timer();
        inline std::string format_now() const;
        double current_elapsed() const;

        Timer& operator=(const std::string& name);

        static std::string DumpTrials(bool ClipboardAlso=false);
        static void Reset();
        static std::string format_elapsed(double d) ;

    private:
        typedef std::string key_type;
        typedef double time_type;
        typedef std::multimap<key_type, time_type> times;

        static __int64 TimerFreq();

        LARGE_INTEGER startTime_, stopTime_;
        mutable LARGE_INTEGER intermediateTime_;
        std::string label_;

        static times& TimeMap();

        struct extract_key : public std::unary_function<times::value_type, key_type>
        {
            std::string operator()(times::value_type const & r) const
            {
                return r.first;
            }
        };

        struct extract_val : public std::unary_function<times::value_type, time_type>
        {
            time_type operator()(times::value_type const & r) const
            {
                return r.second;
            }
        };
        struct match_key : public std::unary_function<times::value_type, bool>
        {
            match_key(key_type const & key_) : key(key_) {};
            bool operator()(times::value_type const & rhs) const
            {
                return key == rhs.first;
            }
            match_key& operator=(const match_key& rhs)
            {
                key = rhs.key;
                return * this;
            }
        protected:
            key_type key;
        };

        struct accum_key : public std::binary_function<time_type, times::value_type, time_type>
        {
            accum_key(key_type const & key_) : key(key_), n(0) {};
            time_type operator()(time_type const & v, times::value_type const & rhs) const
            {
                if( key == rhs.first )
                {
                    ++n;
                    return rhs.second + v;
                }
                return v;
            }
        private:
            times::key_type key;
            mutable size_t n;
        };
    };

    inline Timer::Timer(const std::string & name)
    {
        label_ = name;
        QueryPerformanceCounter(&startTime_);
    }

    inline double Timer::current_elapsed() const
    {
        QueryPerformanceCounter(&intermediateTime_);
        __int64 clocks = intermediateTime_.QuadPart-startTime_.QuadPart;
        double elapsed = (double)clocks/(double)TimerFreq();
        return elapsed;
    }

    inline Timer::~Timer()
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
    };

    inline Timer& Timer::operator=(const std::string& name)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = name;
        QueryPerformanceCounter(&startTime_);
        return * this;
    }

    inline Timer::Timer(const Timer& rhs)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = rhs.label_;
        QueryPerformanceCounter(&startTime_);
    }

    inline std::string Timer::format_now() const
    {
        return format_elapsed(current_elapsed());
    }

    inline std::string Timer::DumpTrials(bool ClipboardAlso)
    {
        using boost::io::group;

        if( TimeMap().empty() )
        {
            return "No trials\r\n";
        }

        std::string ret = (boost::format("\r\n\r\nTimer Precision = %s\r\n\r\n")
            % format_elapsed(1.0/(double)TimerFreq())).str();

        // get a list of keys
        typedef std::set<std::string> keyset;
        keyset keys;
        std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());

        size_t maxrows = 0;

        typedef std::vector<std::string> strings;
        strings lines;

        static const size_t t = 9;

        std::string head =
            (boost::format("=== %-s %-s %-s %-s %-s %-s ===")
            //% (t*2)
            //% (t*2)
            % group(std::setw(t*2), std::setprecision(t*2), "Item" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Trials")
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Ttl Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Avg Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Mean Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "StdDev")
            ).str();

        ret += (boost::format("\r\n%s\r\n") % head).str();
        if( ClipboardAlso )
            lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
        // dump the values for each key
        for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
        {
            time_type ttl = 0;
            ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
            size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
            if( num > maxrows )
                maxrows = num;
            time_type avg = ttl / num;

            // compute mean
            std::vector<time_type> sortedTimes;
            dibcore::stl::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
            std::sort(sortedTimes.begin(), sortedTimes.end());
            size_t mid = (size_t)floor((double)num/2.0);
            double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];

            // compute variance
            double sum = 0.0;
            if( num > 1 )
            {
                for( std::vector<time_type>::iterator cur = sortedTimes.begin(); sortedTimes.end() != cur; ++cur )
                    sum += pow(*cur-mean,2.0);
            }

            // compute std dev
            double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;

            ret += (boost::format("    %-s %-s %-s %-s %-s %-s\r\n")
                % group(std::setw(t*2), std::setprecision(t*2) , (*key))
                % group(std::setw(t), std::setprecision(t) , (boost::format("%d") %num).str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(ttl).c_str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(avg) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(mean) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(stddev)) ).str();

            if( ClipboardAlso )
                lines.push_back((
                boost::format("%s\t%s\t%s\t%s\t%s\t%s\r\n")
                % (*key )
                % (boost::format("%d") %num)
                % format_elapsed(ttl)
                % format_elapsed(avg)
                % format_elapsed(mean)
                % format_elapsed(stddev)
                ).str());

        }
        ret += (boost::format("%s\r\n")
            % std::string(head.length(),'=') ).str();

        if( ClipboardAlso )
        {
            // dump header row of data block
            lines.push_back("");
            {
                std::string s;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        s.append("\t");
                    s.append(*key);
                }
                s.append("\r\n");
                lines.push_back(s);
            }

            // blow out the flat map of time values to a seperate vector of times for each key
            typedef std::map<std::string, std::vector<time_type> > nodematrix;
            nodematrix nodes;
            for( times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
                nodes[time->first].push_back(time->second);

            // dump each data point
            for( size_t row = 0; row < maxrows; ++row )
            {
                std::string rowDump;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        rowDump.append("\t");
                    if( nodes[*key].size() > row )
                        rowDump.append((
                        boost::format("%f")
                        % nodes[*key][row]
                    ).str());
                }
                rowDump.append("\r\n");
                lines.push_back(rowDump);
            }

            // dump to the clipboard
            std::string dump;
            for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
            {
                dump.append(*s);
            }

            OpenClipboard(0);
            EmptyClipboard();
            HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
            if( hg )
            {
                char* buf = (char*)GlobalLock(hg);
                if( buf )
                {
                    std::copy(dump.begin(), dump.end(), buf);
                    buf[dump.length()] = 0;
                }
                GlobalUnlock(hg);
                SetClipboardData(CF_TEXT, hg);
            }
            CloseClipboard();
        }

        return ret;
    }

    inline std::string Timer::format_elapsed(double d)
    {
        if( d < 0.00000001 )
        {
            // show in ps with 4 digits
            return (boost::format("%0.4f ps") % (d * 1000000000000.0)).str();
        }
        if( d < 0.00001 )
        {
            // show in ns
            return (boost::format("%0.0f ns")% (d * 1000000000.0)).str();
        }
        if( d < 0.001 )
        {
            // show in us
            return (boost::format("%0.0f us") % (d * 1000000.0)).str();
        }
        if( d < 0.1 )
        {
            // show in ms
            return (boost::format("%0.0f ms") % (d * 1000.0)).str();
        }
        if( d <= 60.0 )
        {
            // show in seconds
            return (boost::format("%0.2f s") % d).str();
        }
        if( d < 3600.0 )
        {
            // show in min:sec
            return (boost::format("%01.0f:%02.2f") % floor(d/60.0) % fmod(d,60.0)).str();
        }
        // show in h:min:sec
        return (boost::format("%01.0f:%02.0f:%02.2f") % floor(d/3600.0) % floor(fmod(d,3600.0)/60.0) % fmod(d,60.0)).str();
    }

    inline void Timer::Reset()
    {
        TimeMap().clear();
    }

    inline __int64 Timer::TimerFreq()
    {
        static __int64 freq = 0;
        static bool init = false;
        if( !init )
        {
            LARGE_INTEGER li;
            QueryPerformanceFrequency(&li);
            freq = li.QuadPart;
            init = true;
        }
        return freq;
    }

    inline Timer::times& Timer::TimeMap()
    {
        static times times_;
        return times_;
    }
};  // namespace dbg


text:
Q: Filling between more than two boundaries Here is a simple example of what I am trying to do; fill the area described by the three inequalities:
$$ y \le 11 + x    \label{1}      \tag{1}$$
  $$ y \le 27 - x               \tag{2}$$
  $$ y \le \frac{1}{5}(90 - 2x) \tag{3}$$
I have so far:
Plot[{11 + x, 27 - x, 1/5 (90 - 2 x)}, {x, 0, 20},
    Filling -> {2 -> {{3}, {White, LightBlue}}}]

Which produces:

My question is how to add multiple constraints on an area in general -- so for this specific question add the constraint specified by equation $\eqref{1}$.

A: r = ImplicitRegion[
   y <= 11 + x && y <= 27 - x && y <= 1/5 (90 - 2 x) && x >= 0 &&
    y >= 0, {x, y}];
Show[Plot[{11 + x, 27 - x, 1/5 (90 - 2 x)}, {x, 0, 20},
  AxesOrigin -> {0, 0}], RegionPlot[r]]

A: Plot[{11 + x, 27 - x, 1/5 (90 - 2 x), Min[11 + x, 27 - x],
  Min[11 + x, 27 - x, 1/5 (90 - 2 x)]}, {x, 0, 20},
 Filling -> {5 -> {Axis, {White, LightBlue}}, 4 -> {{3}, {None, Yellow}}}]

A: Depend on @kglr, but only use three functions.
Plot[{11 + x, 27 - x, 1/5 (90 - 2 x)}, {x, 0, 20}, PlotPoints -> 40,
 Filling -> {3 -> {Axis, {None, Blue}}, 2 -> {{3}, {White, None}},
   1 -> {{3}, {White, None}}}]


text:
Q: disable button click effect in bootstrap I'm working with Bootstrap 4 and I have a small issue with buttons
<button type="submit" class="btn btn-success form-btn">Rechercher</button>

This is how the button shows up

When I click on it, it stays the same but just after the mouse leaves it it becomes like this

It only shows when I click again with the mouse or the mouse is inside it
I think this has an issue with active selector but I can't find what is causing this problem
Any help would be appreciated

A: I can't replicate the issue. I think you're talking about focus?
    https://codepen.io/amitozdeol/pen/dKOLKB
.btn-success:focus, .btn-success.focus {
    box-shadow: none;
}

Browser: Chrome MacOS
Can you share the jsfiddle or codepen with us?

A: The click effect was coming from the btn class so I removed it from the button
I changed this
<button type="submit" class="btn btn-success form-btn">Rechercher</button>

To this
<button type="submit" class="btn-success form-btn">Rechercher</button>


text:
Q: Duvida sobre GIT e como usar um projeto existente no servidor? Atualmente estou adentrando no método git, e tenho gostado bastante da forma que o desenvolvimento flui. Porém me deparei com um problema. Eu tenho vários projetos que já estão em seus devidos servidores, enviados via FTP tradicional.
Criar o projeto do zero e fazer o deploy em uma pasta vazia foi tranquilo, mas quando há arquivos na pasta não estou conseguindo postar atualizações e nem copiar os arquivos para o meu projeto no GitLab.
A dúvida é como posso copiar os arquivos de um desses projetos para um projeto no GitLab?

A: Se já existe arquivos na pasta, crie um repositório vazio pelo gitLab e em seguida siga os passos abaixo:
cd pasta_projeto
git remote add origin https://gitlab.com/seuUser/nomeDoProjeto.git
git add .
git commit -m "Initial commit"
git push -u origin master

A: Não entendi perfeitamente, mas se você quiser atualizar os arquivos após adicionados.
use o comando dentro da pasta principal do projeto
git pull origin master


text:
Q: Match a values greater than 2000 using Regular Expression i need a regular Expression that is True for inputs above 2000:
for (int i = 1998; i < 10001; i++)
{
    String s = Integer.toString(i);

    // Above Range 2000 to 9999

    System.out.print(i+"\t");

    System.out.println(s.matches("[^1]?[0-9]{1,3}"));
}

A: You should probably just be using integer comparison, but just for fun here's the regex:
/(\d{5,}|[2-9](?=\d*[1-9])\d{3})/g

See it in action here

A: If you want to extract from a string only integers greater than 2000, two ways are possible.
It is note always simple to take in account mathematical considerations within a regex pattern since a regex pattern is build in a character logic. So you can simply extract all integers with [0-9]+ or [1-9][0-9]*, cast the results to integers and test each of them with an if statement.
You can do it directly with the pattern, but you need to carefuly limit the impact on performance avoiding a giant alternation and failing branches. This is the way you can do this:
[3-9][0-9]{3,}
|
2
(?:
    [1-9][0-9]{2,}
  |
    0
    (?:
        [1-9][0-9]+
      |
        0 (?: [1-9][0-9]* | 0 [0-9]+)
    )
)
|
1 [0-9]{4,}

note: to allow 2000, remove all the second main alternative and change the first to [2-9][0-9]{3,}
The main interest of this pattern is that once the regex engine enters in a branch it is always in the good one and has no other branch to test whatever the result (succeed or fail). Note that the three main branches are sorted by probability order, one more time to limit the engine work.
It is possible to improve it more (must be tested) if you enclose all in non capturing group and you check before with a lookahead if the current tested character is a digit. This improvement allows to skip quickly all characters of the string that are not a digit without to test the three branches of the main alternation.
(?=[1-9])(?:pattern)

that gives:
(?=[1-9])(?:[3-9][0-9]{3,}|2(?:[1-9][0-9]{2,}|0(?:[1-9][0-9]+|0(?:[1-9][0-9]*|0[0-9]+)))|1[0-9]{4,})


text:
Q: Meta programming question suspension I've been seeing a lot of these lately:

This account is temporarily suspended for asking programming questions
  on MSO. The suspension period ends on [date-time].

I don't see any way this could be manual, since mods would have to remember the user from earlier posts. If this is in fact automated, how is "programming question" off-topic  distinguished from plain old off-topic? As far as I can tell there is no way to specify in the close vote how a question is off topic.
Do all off topic close votes count towards "asking programming questions" bans?

A: Mods get Community♦ flags if a user has too many consecutive closed posts. They can then act, manually.
Most of the times, the people post on meta to circumvent q-bans on main. We get quite a few of these on meta each day. This suspension reason makes more sense--some other mod message templates are OK when applied, but they don't fit as well.

A: These are all hand made and crafted for each user who may be trying to evade their taxes.
This also is only applied to users who are asking programming questions on a site where another is explicitly set up for that and they're not posting over there because they want to back door their way in from over here.
Moderators can see all questions per user and quickly see if that's the case.
For those that are just on the wrong site first go, they may get a free pass.
None of these are automatic and they are not always suspended, for the above reasons.

A: Here's a rough flow chart:

*

*User asks programming question on Meta

*

*Is the user obviously question banned on Stack Overflow?

*

*Yes: Suspend for attempting to circumvent the question ban, but for how long?

*

*Have they done this before?

*

*Yes: 30+ days, if the noise seems to be a pattern

*No: A week is sufficient, people do improve and come here for help to get back in good standing.

*No: Leave a helpful comment letting the user know they hit the wrong site
It's becoming increasingly common for new users to just get 'lost' somehow all over the network, it happened on Politics just recently. I've been politely asking those who just appear to be lost why they picked Meta to ask their question (wondering, perhaps, does 'meta' mean something in some places that would make a person think it was the right place?) - the majority1 indicated that they didn't realize they were on a different site.
Additionally, it's extremely rare for users that receive these suspensions and the accompanying message to ever reply, or much less contest the suspension. When we do it, we've got them dead to rights.
1Out of the dozen-ish comments I left, I received three replies. Two indicated that they didn't realize they were on an entirely different site.


text:
Q: Loading an image as Texture2D In my program, I want to save some screenshots and load them later on to compute somethings. I created a methode to compute the image names:
static public string generatePhotoName (string cameraName, float time)
{
    return "G:/Data/unity/cameraDemo/" +
        DataController.measurmentPath +
        "/photos" + "/" +
        cameraName + "/" +
        time.ToString () + "_" + cameraName + ".png";
}

This worked fine for saving, but when I try to load an image, File.Exists (filePath)returns false.
But when I hardcoded the filepath, loading works fine too:
static public string generatePhotoName (string cameraName, float time)
{
    return "G:/Data/unity/cameraDemo/demo/photos/Camera/test.png";
}

It even works with "real" image names(i.e. 3.827817_Camera.png).
Using Path.Combine(...) and changing "/" to "\" did not change anything...
// edit: this is my load methode
static public Texture2D loadPhotoToTexture (string filePath)
{

    Texture2D tex = null;
    byte[] fileData;

    if (File.Exists (filePath)) {
        fileData = File.ReadAllBytes (filePath);
        tex = new Texture2D (2, 2);
        tex.LoadImage (fileData); //..this will auto-resize the texture dimensions.
    } else {
        Debug.Log (filePath + " does not exist");
    }
    return tex;
}`

// edit2: some more code
This is how I call the methode
Texture2D photo = DataController.loadPhotoToTexture(photoData.getFileName ());
And this is my class PhotoData
public class PhotoData : BaseData
{
    private string _cameraName;

    public string cameraName {
    get { return _cameraName; }
    set { _cameraName = value; }
    }

    private float _time;

    public float time {
        get { return _time; }
        set { _time = value; }
    }

    public PhotoData ()
    {
    }

    public PhotoData (string cameraName, float time)
    {
        _cameraName = cameraName;
        _time = time;
    }

    public string getFileName ()
    {
        return PlayerController.generatePhotoName (_cameraName, _time);
    }
}

A: The problem was, that I tried to save and load the screenshots in one Update()-call.
I fixed it by changing it to right-click to take and save a screenshot and left-click to load the screenshot.

A: If you want to store images to a certain file on disk, not inside your game folder structure, do this: create a folder, and store its location (filepath). For example:
string screenshotFileName = time.ToString () + "_" + cameraName + ".png"
string screenshotDirectory;
screenshotDirectory = @"C:\someFolder\anotherFolder\";
try { Directory.CreateDirectory(directory); }
catch (Exception e)
{ //you should catch each exception separately
   if (e is DirectoryNotFoundException || e is UnauthorizedAccessException)
       Debug.LogError("OMG PANIC");
}
FileInfo filepath = new FileInfo(screenshotDirectory+screenshotFileName);
if(filepath.Exists)
{
    //load the file
}

You could also simply create a folder, with a relative path, which will be in the same folder as your executable, by changing the screenshotDirectory to
     screenshotDirectory = @"screenshots\"+cameraName+@"\";
Edit:
You seem to load the texture correctly. Are you assigning it to the material's main texture? Where is your code encountering the problem? For example if you're running this script on the same object that you want the texture to be applied:
this.GetComponent<Renderer>().material.mainTexture = loadedTexture;

Also, when you want to load images, it's best that you use the Resources folder, which uses forwards slashes, not . Store everything that you might want to load on runtime there, and use Resources.Load().


text:
Q: module 'pandas' has no attribute 'WidePanel' Hi I am running the following simple OLS:
import pandas as pd
import statsmodels.formula.api as sm

df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C":
[32, 234, 23, 23, 42523]})
result = sm.ols(formula="A ~ B + C", data=df).fit()

Unfortunately, it is throwing the following error:
module 'pandas' has no attribute 'WidePanel'
Can anyone help please?
Thank you


text:
Q: Gulp package-solution not using the Angular.json file when deployed in SPFX I have an SPFX solution where I deploy a bundle.JS file generated by an external Angular project as detailed here:
https://pnp.github.io/generator-spfx/howtos/angularelements/
I have noticed that my solution behaves differently when I test it on the local workbench (using gulp serve) and when I test it in the deployed website (using gulp package-solution --ship after en gulp bundle--ship)
I have some Angular files missing like the Angular.JSON is not used (I miss the jquery import for instance) and some other packages coming from the Angular solution are not imported.
Is it possible to configure the gulp package-solution command to get the same configuration as the gulp serve ?

A: Try
gulp bundle --ship
gulp bundle --debug
gulp package-solution --ship


text:
Q: System.ArgumentException: Destination array was not long enough I am trying to work with a tcp it service that requires me to send an ID as string. I got the method below from a sample code.
I the problem is when i enter strings with 4 chars numbers like "4000", "2000", "3000" the method works but when i enter strings with less that 4 chars "1", "20", or "300"
it returns

System.ArgumentException: Destination array was not long enough. Check
  destIndex and length, and the array's lower bounds.

 public byte[] prepNetworkStreamBuffer(string reqiiredID) {
        byte[] id = UTF8Encoding.UTF8.GetBytes(reqiiredID);
        int l = id.Length;
        byte[] idb = BitConverter.GetBytes(System.Net.IPAddress.HostToNetworkOrder(l));

        byte[] buff = new byte[1 + 1 + id.Length + l];
        buff[0] = 0;
        buff[1] = (byte)VerificationServiceCommands.addIDtoAFIS;
        idb.CopyTo(buff, 1 + 1);
        id.CopyTo(buff, 1 + 1 + idb.Length);

        return buff;
    }

A: I suspect the problem is that the buffer length is
1 + 1 + id.Length + l

When it should be
1 + 1 + idb.Length + l
        ^^^

The best way to check this problem would be to fire up the debugger and take a look at the length of buff.

A: You're copying idb and id to buff, which is only of size 2*id.Length + 2.
So when id is only of size 3, your buff is too small to fit idb, which is of size 4.
You want:
byte[] buff = new byte[1 + 1 + id.Length + idb.Length];

A:     public static bool TryGetArray(ref SomeObject[] source )
    {
        try
        {
            var localSource = new List<SomeObject>{new SomeObject(), new SomeObject()};

            var temp = new SomeObject[localSource.Count + source.Length];
            Array.Copy(source, temp, source.Length);
            Array.ConstrainedCopy(localSource.ToArray(), 0, temp, source.Length, localSource.Count);
            source = temp;
        }
        catch
        {
            return false;
        }
        return true;
    }


text:
Q: How to center align elements of a layout that is added by using  I have created a simple layout that contains 2 imageViews.
This is my code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/root_team1"
    android:layout_gravity="center"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ImageView
        android:id="@+id/team_one_IV"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_centerVertical="true"
        android:background="#004187"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/team_one_IV2"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_marginTop="2dp"
        android:layout_centerVertical="true"
        android:background="#004187"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/team_one_IV" />

</androidx.constraintlayout.widget.ConstraintLayout>

This is what its showing me when i view the layout.

Now i want to include this layout in another layout. This is what i did.
  <include
        android:id="@+id/firstTeam"
        layout="@layout/team_1"
        android:layout_width="0dp"
        android:layout_height="300dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

and this is what i get after including this layout in another layout.

As you can see the layout is attached to the top, but i want it to be in the center of the container, i have defined container height to 300dp. Do i need to use some other type of layout to achieve this?
EDIT:
Complete layout code:
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <include
            android:id="@+id/team_1"
            layout="@layout/team_1"
            android:layout_width="0dp"
            android:layout_height="300dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: So if the layout you are trying to include is the first layout in this post you have to options:
make those imageViews' width wrap_content
or add
app:layout_constraintWidth_default="wrap"


text:
Q: Class objects are irregular when assigning functions Let's say I have a function like this:

def id(x):
  return x

I expect to be able to bind it to any object (let's say x),

x.f = id

and be able to do

x.f(1)
=> 1

However, classes are not regular objects because it does not work :

class X(object):
  pass

X.f = id
x.f(1)
=> unbound method f() must be called with X instance as first argument (got int instance instead)

So that I have to do,

X.f=staticmethod(id)
X.f(1)
=> 1

However it doesn't work with regular objects,

x.f=staticmethod(f)
x.f(1)
=> 'staticmethod' object is not callable

So is there a way to have assignment work as expected in generic code where
I do not know whether the object assigned to is a regular object of a class object
and when the assigned object may be a function?

A: import inspect
if inspect.isclass(X):
   X.f = staticmethod(f)
else:
   X.f = f

The issue isn't the assignment; that works fine. It is that functions on classes take self as their first parameter, and your function doesn't. You can get the actual function back with
X.__dict__['f']
<function f at 0x023A52F0>

or
X.f
<unbound method X.f>
X.f.im_func
<function f at 0x023A52F0>

(You are getting an unbound method instead of the original function, because in Python 2.x that is what happens when you access a method on a class. In Python 3.x that is changed and you just get the original function. I believe it is for backwards compatibility with old-style classes.)

This is a weird thing to want to do: you are working at a very high level of abstraction if you don't even know if the object you are working with is a class or not! For that matter, what if you get passed a built-in type, say a string? You can't set attributes on that! I think you need to work at a slightly lower level.

A: Define your function that you want to bind like this:
def id_(self, x):
    return x

and now you can do something like :
X.f = id_
x = X()
x.f(1)
=> 1

A: I agree that this is fairly odd behavior. Perhaps there is a reason for this; perhaps it is one of those corner cases that never got fully investigated, or, if it was investigated, was considered so obscure as to not be worth addressing. Sometimes happens.
If you want the behavior that assigning a function as a class attribute always makes it a static method, you can do this with a metaclass.
class func2static(type):
    def __setattr__(cls, name, value):
        if type(value) is type(lambda: 0):
            value = staticmethod(value)
        type.__setattr__(cls, name, value)

class X(object):
    __metaclass__ = func2static

Now let's show that both the class and instances of the class can have a function assigned to them, which is then callable.
f = lambda x: x

X.f = f
X.f(3)  # no exception

x = X()
x.g = f
x.g(3)  # also no exception

This doesn't really solve the problem if you are monkey-patching random classes defined in other modules, unfortunately, but you probably shouldn't be doing that anyway.  :-)


text:
Q: How to use a CNG (or AES-NI enabled instruction set) in .NET? I Currently perform a large amount of encryption/decryption of text in c# using AES.
With a pure software system it can take quite a processor hit for a decent amount of time for the lots of datasets required to be decrypted. I know Intel have came out with their AES-NI instruction set and AMD has come out with similar.
I'm using .NET 4.0, I know that the windows CNG framework makes use of these instruction sets, but it does not appear that AesManaged in the .NET world does the same.
There is a fantastic project "CLR Security" which makes a gateway from .NET 3.5 to the windows CNG, however it hasn't been maintained in a year and I'd rather not (if possible) jump on a dying project.
There is a CNGProvider class in .NET 4 but there doesn't appear to be adequate documentation to cobble together a working decryption from it for AES.
Does anyone have experience with the topic they could point me in the right direction on how to get AES-NI implemented in a pure .NET environment, using pre-made classes, without having to do a p/invoke directly from c#? (It'd be fine if there was a wrapper class doing it, as long as it was maintained).

A:
What about AesCryptoServiceProvider? It says that uses CAPI, and so
  hopefully CNG if available. – Rup

This comment has helped tremendously, after doing some digging it looks like AesCryptoServiceProvider will use AES-NI if available. I cannot find any 'official' documentation from Microsoft on this however. When running simple timing benchmarks the difference is ~15x faster so either the API itself is massively optimized (which for a 15x increase is pretty nice optimization) or it uses the AES-NI instruction set.
Unfortunately I don't have a non AES-NI box to test on, but if I ever get one I'll update this thread with results.
So I'm pretty confident this is the API to use for AES-NI but cannot guarantee without further testing.

A:
How to use a CNG (or AES-NI enabled instruction set) in .NET?

I'm going to focus on the AES-NI instruction set question. I found it to be interesting since I wondered it myself (for use in C and C++).
Microsoft added AES-NI support to Visual Studio 2008 SP1 (_MSC_FULL_VER >= 150030729). The earliest you can observe AES-NI in Microsoft products is circa 2008 since earlier compilers did not support it. That means Server 2008 has it, and possibly Windows Vista via a Service Pack, and above.
According to Does MS Crypto API supports AES and AES-NI processor instructions?, both rsaenh.dll and bcryptprimitives.dll have it. The statements made by IvanP tested on Windows 7 and Windows 10.
However, testing on Windows 8.1 reveals...
# Using a Developer Command prompt so dumpbin is on-path:
> dumpbin /disasm c:\Windows\System32\rsaenh.dll > rsaenh.dll.txt
> dumpbin /disasm c:\Windows\System32\bcryptprimitives.dll > bcryptprimitives.dll.txt

Then:
# Using a GitBash terminal for grep
$ grep -i aes rsaenh.dll.txt
$

And:
$ grep -i aes bcryptprimitives.dll.txt
  000000018000234A: 66 0F 3A DF C0 00  aeskeygenassist xmm0,xmm0,0
  0000000180002363: 66 0F 38 DB C0     aesimc      xmm0,xmm0
  000000018000237E: 66 0F 38 DC 41 10  aesenc      xmm0,xmmword ptr [rcx+10h]
  0000000180002384: 66 0F 38 DC 41 20  aesenc      xmm0,xmmword ptr [rcx+20h]
  000000018000238A: 66 0F 38 DC 41 30  aesenc      xmm0,xmmword ptr [rcx+30h]
  0000000180002390: 66 0F 38 DC 41 40  aesenc      xmm0,xmmword ptr [rcx+40h]
  0000000180002396: 66 0F 38 DC 41 50  aesenc      xmm0,xmmword ptr [rcx+50h]
  000000018000239C: 66 0F 38 DC 41 60  aesenc      xmm0,xmmword ptr [rcx+60h]
  00000001800023A2: 66 0F 38 DC 41 70  aesenc      xmm0,xmmword ptr [rcx+70h]
  00000001800023AF: 66 0F 38 DC 01     aesenc      xmm0,xmmword ptr [rcx]
  00000001800023B4: 66 0F 38 DC 41 10  aesenc      xmm0,xmmword ptr [rcx+10h]
  00000001800023C3: 66 41 0F 38 DD 02  aesenclast  xmm0,xmmword ptr [r10]
  000000018001936E: 66 0F 38 DC 41 10  aesenc      xmm0,xmmword ptr [rcx+10h]
  0000000180019374: 66 0F 38 DC 41 20  aesenc      xmm0,xmmword ptr [rcx+20h]
  000000018001937A: 66 0F 38 DC 41 30  aesenc      xmm0,xmmword ptr [rcx+30h]
  0000000180019380: 66 0F 38 DC 41 40  aesenc      xmm0,xmmword ptr [rcx+40h]
  0000000180019386: 66 0F 38 DC 41 50  aesenc      xmm0,xmmword ptr [rcx+50h]
  000000018001938C: 66 0F 38 DC 41 60  aesenc      xmm0,xmmword ptr [rcx+60h]
  0000000180019392: 66 0F 38 DC 41 70  aesenc      xmm0,xmmword ptr [rcx+70h]
  000000018001939F: 66 0F 38 DC 01     aesenc      xmm0,xmmword ptr [rcx]
  00000001800193A4: 66 0F 38 DC 41 10  aesenc      xmm0,xmmword ptr [rcx+10h]
  00000001800193B3: 66 41 0F 38 DD 02  aesenclast  xmm0,xmmword ptr [r10]
  000000018001952E: 66 0F 38 DE C4     aesdec      xmm0,xmm4
  0000000180019533: 66 0F 38 DE CC     aesdec      xmm1,xmm4
  0000000180019538: 66 0F 38 DE D4     aesdec      xmm2,xmm4
  000000018001953D: 66 0F 38 DE DC     aesdec      xmm3,xmm4
  000000018001954B: 66 0F 38 DF C4     aesdeclast  xmm0,xmm4
  0000000180019550: 66 0F 38 DF CC     aesdeclast  xmm1,xmm4
  0000000180019555: 66 0F 38 DF D4     aesdeclast  xmm2,xmm4
  000000018001955A: 66 0F 38 DF DC     aesdeclast  xmm3,xmm4
  000000018002E8B5: 66 0F 38 DE 41 10  aesdec      xmm0,xmmword ptr [rcx+10h]
  000000018002E8BB: 66 0F 38 DE 41 20  aesdec      xmm0,xmmword ptr [rcx+20h]
  000000018002E8C1: 66 0F 38 DE 41 30  aesdec      xmm0,xmmword ptr [rcx+30h]
  000000018002E8C7: 66 0F 38 DE 41 40  aesdec      xmm0,xmmword ptr [rcx+40h]
  000000018002E8CD: 66 0F 38 DE 41 50  aesdec      xmm0,xmmword ptr [rcx+50h]
  000000018002E8D3: 66 0F 38 DE 41 60  aesdec      xmm0,xmmword ptr [rcx+60h]
  000000018002E8D9: 66 0F 38 DE 41 70  aesdec      xmm0,xmmword ptr [rcx+70h]
  000000018002E8E6: 66 0F 38 DE 01     aesdec      xmm0,xmmword ptr [rcx]
  000000018002E8EB: 66 0F 38 DE 41 10  aesdec      xmm0,xmmword ptr [rcx+10h]
  000000018002E8FA: 66 41 0F 38 DF 02  aesdeclast  xmm0,xmmword ptr [r10]
  000000018003F458: 66 0F 38 DC E8     aesenc      xmm5,xmm0
  000000018003F45D: 66 0F 38 DC D8     aesenc      xmm3,xmm0
  000000018003F462: 66 0F 38 DC E0     aesenc      xmm4,xmm0
  000000018003F467: 66 0F 38 DC F0     aesenc      xmm6,xmm0
  000000018003F475: 66 0F 38 DD EF     aesenclast  xmm5,xmm7
  000000018003F47A: 66 0F 38 DD DF     aesenclast  xmm3,xmm7
  000000018003F47F: 66 0F 38 DD E7     aesenclast  xmm4,xmm7
  000000018003F492: 66 0F 38 DD F7     aesenclast  xmm6,xmm7

So, on modern Windows, you need to use something that depends on bcryptprimitives.dll. I don't know what .Net primitives enlist bcryptprimitives.dll.

I also checked the following DLLs on Windows 8.1, and there were no AES-NI instructions present:

*

*advapi32.dll

*bcrypt.dll

*crypt32.dll

*cryptbase.dll

*cryptcatsvc.dll

*cryptdlg.dll

*cryptdll.dll

*cryptext.dll

*cryptnet.dll

*cryptowinrt.dll

*cryptsp.dll

*cryptsvc.dll

There's not much information about the subject on Microsoft's site. I got two hits from csp "aes-ni" site:microsoft.com, and 0 hits for csp "aesni" site:microsoft.com. Whatever is going on, Microsoft is keeping it secret.

A: I had worked in the earliest of chipsets that had these features. At that time Windows 7 didn't have the ability to work with AES. I resorted to the then available Ubuntu and used the Intel doc and with some inline assembly did a cpuid. That served my purpose of a training. Nevertheless one thing I learned is "Intel secure key" was made available almost at the same time as "AES-NI". So if I found RDRAND instruction in the chipset that means I "probably" had AES-NI. So this way the simplest I can do (but not quite documented) is
//PF_RDRAND_INSTRUCTION_AVAILABLE is not documented yet as part of MSDN API as of //this writing
IsProcessorFeaturePresent(PF_RDRAND_INSTRUCTION_AVAILABLE);
We can also use the CPU intrinsics this way
https://learn.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex?view=vs-2019
Also see below document for more "proof".
https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1894.pdf


text:
Q: send packet in linux kernel I wrote a module to send a packet in kernel-space. but after insmod it gives a segmentation fault error. I have tried to change some parts of it but I still get errors.
the code:
//libraries

#define IP_Header_RM 20
#define UDP_Header_RM 8

static int __init init_Module(void){
    unsigned char *Data = "Test_Packet";
    int i = strlen(Data);
    struct sk_buff* skb = alloc_skb(ETH_HLEN + IP_Header_RM + UDP_Header_RM + i, GFP_ATOMIC);
    struct iphdr* iph = (struct iphdr*)skb_push(skb, IP_Header_RM);
    struct ethhdr* eth = (struct ethhdr*)skb_push(skb, sizeof (struct ethhdr));
    struct udphdr* uh = (struct udphdr*)skb_push(skb, UDP_Header_RM);
    struct net_device *Device;
    uint16_t proto;
    uint8_t Mac_Addr[ETH_ALEN] = {0x38, 0xd5, 0x47, 0xa1, 0x07, 0x41};
    Data = skb_put(skb, i);
    skb_reserve(skb, ETH_HLEN);
    Device = dev_get_by_name(&init_net,"enp0s3");
    proto = ETH_P_IP;
    uh->len = htons(i);
    uh->source = htons(2121);
    uh->dest = htons(2121);

    iph->ihl = 5;
    iph->version = 4;
    iph->tos = 0;
    iph->tot_len= htons(IP_Header_RM + i);
    iph->frag_off = 0;
    iph->ttl = 64;
    iph->protocol = IPPROTO_UDP;
    iph->check = 0;
    iph->saddr = 19216805;
    iph->daddr = 19216804;
    skb->protocol = eth->h_proto = htons(proto);
    skb->no_fcs = 1;
    memcpy(eth->h_source, Device->dev_addr, ETH_ALEN);
    memcpy(eth->h_dest, Mac_Addr, ETH_ALEN);

    skb->pkt_type = PACKET_OUTGOING;
    dev_queue_xmit(skb);
    return 1;
    }

static void __exit exit_Module(void){
    printk(KERN_INFO "Done");
    }

module_init(init_Module);
module_exit(exit_Module);

which parts I made mistake?
Thanks in Advance

A: You need to do skb_reserve() up front on the allocated buffer, before doing any skb_put() calls for user data or skb_push() for eth/IP headers.  You were segfaulting trying to skb_push() first, on a buffer without proper reservations.  I also had a few other suggestions for you:

*

*Include your complete source next time!

*Rearrange the order of your pushed headers to make a legit UDP/IP packet

*dev_get_by_name() may fail; should check before trying to memcpy to its buffer

*Push the user data before any eth/IP header(s)

*Return 0 rather than 1 from a module's init() to indicate success

A tutorial page like this may help to put it all together:  http://vger.kernel.org/~davem/skb_data.html
The code below does not segfault on my Debian 10 system with a 4.19 Linux kernel.
//libraries

#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/module.h>
#include <linux/virtio.h>
#include <linux/virtio_net.h>
#include <linux/bpf.h>
#include <linux/bpf_trace.h>
#include <linux/scatterlist.h>
#include <linux/if_vlan.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/average.h>
#include <linux/filter.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <net/route.h>
#include <net/xdp.h>
#include <net/net_failover.h>

#define IP_Header_RM 20
#define UDP_Header_RM 8

static int __init init_Module(void){
    unsigned char *Data = "Test_Packet";
    int i = strlen(Data);
    struct sk_buff* skb = alloc_skb(ETH_HLEN + IP_Header_RM + UDP_Header_RM + i, GFP_ATOMIC);
    struct net_device *Device;
    uint16_t proto;
    struct iphdr* iph;
    struct ethhdr* eth;
    struct udphdr* uh;
    uint8_t Mac_Addr[ETH_ALEN] = {0x38, 0xd5, 0x47, 0xa1, 0x07, 0x41};

    skb_reserve(skb, ETH_HLEN + IP_Header_RM + UDP_Header_RM + i);
    Data = skb_put(skb, i);
    iph = (struct iphdr*)skb_push(skb, IP_Header_RM);
    uh = (struct udphdr*)skb_push(skb, UDP_Header_RM);
    eth = (struct ethhdr*)skb_push(skb, sizeof (struct ethhdr));

    Device = dev_get_by_name(&init_net,"enp0s3");
    if (Device == NULL) {
        printk(KERN_INFO "init_Module: no such device enp0s3\n");
        return 1;
    }
    proto = ETH_P_IP;
    uh->len = htons(i);
    uh->source = htons(2121);
    uh->dest = htons(2121);

    iph->ihl = 5;
    iph->version = 4;
    iph->tos = 0;
    iph->tot_len= htons(IP_Header_RM + i);
    iph->frag_off = 0;
    iph->ttl = 64;
    iph->protocol = IPPROTO_UDP;
    iph->check = 0;
    iph->saddr = 19216805;
    iph->daddr = 19216804;
    skb->protocol = eth->h_proto = htons(proto);
    skb->no_fcs = 1;
    memcpy(eth->h_source, Device->dev_addr, ETH_ALEN);
    memcpy(eth->h_dest, Mac_Addr, ETH_ALEN);

    skb->pkt_type = PACKET_OUTGOING;
    dev_queue_xmit(skb);
    return 0;
    }

static void __exit exit_Module(void){
    printk(KERN_INFO "Done");
    }

module_init(init_Module);
module_exit(exit_Module);

MODULE_DESCRIPTION("Stack Overflow 66846959");
MODULE_LICENSE("GPL");


text:
Q: Python conditional using regex with multiline string I need help with very simples question, a conditional using regex with multiline string. No make sense to me why this not work:
if(re.match(r"\w", " \n\n\n  aaaaaaaaaaaa\n\n", re.MULTILINE)):
    print('ok')
else:
    print('fail')

fail

I expected that result be ok, but no match any data. I trying using https://regex101.com/r/BsdymE/1, but there works and in my code not works.

A: re.match will only return a match if the search string is at the beginning.
https://docs.python.org/3/library/re.html#re.match

re.match(pattern, string, flags=0)
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Try using re.search(pattern, string, flags=0) instead

A: From pydoc re.match:

Try to apply the pattern at the start of the string, returning a
  Match object, or None if no match was found.

(emphasis mine). So, the problem is not with the string being multiline, but rather with it not beginning with a word-class character. If you want to check if a string contains something anywhere, use re.search instead.


text:
Q: Type a special character with a regular keyboard I am trying to reinstall an iMac but I don't have the original Apple keyboard. Instead a  "regular" keyboard is attached.
I can't find out how to type the "at" symbol (@). I need it to enter my Apple ID so I can download Mavericks to reinstall the sytem.
Is there any way to type it or circumvent the Apple ID login?

A: Either look at the keyboard viewer:

Or google for pictures of Apple keyboards:

A: The issue was fixed by temporary switching the input language back to USA, type shift-2 and then change it back to Belgian to proceed.


text:
Q: Dynamically set XML namespace in Jackson I currently have this:
@JacksonXmlRootElement(namespace = "some-ns", localName = "queryResult")
public class QueryResult {
    ...
}

Now I need to make "some-ns" configurable through a config file (i.e. set in runtime).
What's the best way to achieve this?

A: You can write a custom AnnotationIntrospector:
import com.fasterxml.jackson.databind.PropertyName;
import com.fasterxml.jackson.databind.introspect.AnnotatedClass;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlAnnotationIntrospector;

public class MyJacksonXmlAnnotationIntrospector extends JacksonXmlAnnotationIntrospector
{
    private static final long serialVersionUID = 1L;

    @Override
    public PropertyName findRootName(AnnotatedClass ac) {
        PropertyName pn = super.findRootName(ac);
        return pn.withNamespace("custom");
    }
}

and then pass it to the jackson mapper:
    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.setAnnotationIntrospector(new MyJacksonXmlAnnotationIntrospector());
    xmlMapper.writeValue(System.out, new QueryResult());


text:
Q: Java: How can I update a variable used in Runnable lambda? I have the following code. I'm using a ScheduledExecuterService in my scheduleNumbers() method to display a series of random numbers for a specified amount of milliseconds. However, I can't seem to update the curNumber being displayed in the setNumber lambda as "local variables referenced from a lambda expression must be final or effectively final" (Very informative). Is there any way to go about this without using threads? Full code is in a pastebin link below.
private void printNumbers(int[] randomNumbers) {
    int speed = DIFF_TIMES[difficulty.getSelectedIndex()];
    int amount = BASE_AMOUNT + currentScore;
    answerField.setEditable(false);
    scheduleNumbers(randomNumbers, speed, amount);
    currentNumberLab.setText("");
    answerField.setEditable(true);
}

public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
    int curNumber = 0;
    long initialDelay = 1000;
    final Runnable setNumber = () -> {
        currentNumberLab.setText(Integer.toString(randomNumbers[curNumber]));
        System.out.println("Set to " + randomNumbers[curNumber]);
    };
    final ScheduledFuture<?> setNumberHandle = scheduler.scheduleAtFixedRate(setNumber, initialDelay, speed, MILLISECONDS);
    scheduler.schedule(() -> {
        setNumberHandle.cancel(true);
    }, (speed*amount)+initialDelay, MILLISECONDS);
}

Full code.
Edit for clarity:
I'd like to be able to increment curNumber so each time setNumber is run, it sets currentNumberLab to Integer.toString(randomNumbers[curNumber++]).

A: Well actually it is informative...
try the following:
public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
final int curNumber = 0;

It needs to be final because once the method is finished you would loose reference of your local variables inside your thread. The method would be finished but the thread might still be running. Declaring a local variable final helps you to get around this issue.
If you would like to update curNumber in the thread use AtomicInteger instead:
public void scheduleNumbers(int[] randomNumbers, int speed, int amount) {
final AtomicInteger curNumber = new AtomicInteger();
long initialDelay = 1000;
final Runnable setNumber = () -> {

    currentNumberLab.setText(Integer.toString(randomNumbers[curNumber.incrementAndGet()]));
    System.out.println("Set to " + randomNumbers[curNumber.get()]);
};


text:
Q: Larave & Vite - Vite manifest missing odd files
In this image there are 5 separate images all in the same folder. When I run npm run build the manifest file is generated and two of the files are not entered (favicon-32x32|16x16).
The images are clearly present;

When this goes into production I get the following 500 error;
[2022-08-26 14:30:52] production.ERROR: Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. {"view":{"view":"/home/forge/myproject/resources/views/app.blade.php","data":[]},"exception":"[object] (Spatie\\LaravelIgnition\\Exceptions\\ViewException(code: 0): Unable to locate file in Vite manifest: resources/images/favicon/favicon-32x32.png. at /home/forge/myproject/vendor/laravel/framework/src/Illuminate/Foundation/Vite.php:539)

Is there any reason why these files would not be added to the manifest?

A: Check the size of your assets. I ran into an issue a couple of days ago where images smaller then 4kb would be inlined trough base64.
As stated in the vite docs

Assets smaller in bytes than the assetsInlineLimit option will be inlined as base64 data URLs.

Setting
build: { assetsInlineLimit: 0 }

In vite.config.js would eliminate that behavior.
I posted a question about that asset inlinement. See How to make Laravel Vite copy static assets versioned to build folder
Furthermore Vite is not able to locate assets in Blade templates, so you need to tell Vite if you're using the Vite::asset() helper in your blade templates to account of these images. This is done by implementing a little javascript somewhere in your application. (The file should be processed by Vite of course)
import.meta.glob([
  '../images/**',
  '../fonts/**',
]);

See Laravel docs: https://laravel.com/docs/9.x/vite#blade-processing-static-assets
Last thing to check is to make sure you run npm run build on production, might clear your views as well while you're at it by doing a php artisan view:clear
By the way, at the time of writing I'm running into issues with assets used in Blade that fall below the mentioned base64 threshold. At that point they won't work. At the moment I'm setting the assetsInlineLimit to 0 to just skip the base64 inlining. However, I think it's a nice feature and this issue will probably be addressed somewhere in the near feature.


text:
Q: Asynchronous requests I have a modal which will show a list of campos, so I do a GET request for the list and only filter the campos in my JSON. The problem is that the request is taking too long to respond and it just opens the modal without the ready data.  How do I get the JS wait until the for loop end all interactions and then open the modal? I try use $q
$scope.novoCampo = function (index) {
        var deferred = $q.defer();
        contatosAPI.getDados().then(function (response) {
            var campos = [];
            var listaContatos = response.data._embedded.contatos;
            for (var i = 0; i < listaContatos.length; i++) {
                var dados = listaContatos[i].dados;
                for (var j = 0; j < dados.length; j++) {
                    var nomeCampo = dados[j].campo;
                    if (campos.indexOf <= -1) {
                        campos.push(nomeCampo);
                    }
                }
            }
            deferred.resolve(campos);
        }).catch(function (error) {
            alert("Erro ao obter os campos!");
            console.log(error + "\t" + JSON.stringify(error));
            deferred.reject(status);
        });

        deferred.promise.then(function (listaCampos) {
            //Here in my console.log is empty
            console.log("lista " + '\t' + JSON.stringify(listaCampos) + '\t' + listaCampos[0]);
            var modalInstance = $modal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'novoCampo.html',
                controller: 'novoCampoController',
                size: '',
                resolve: {
                    index: function () {
                        return index
                    }
                }
            });

            modalInstance.result.then(function (result) {
                try {
                    $scope.contatos[result.index].dados.push({
                        campo: result.nomeCampo,
                        valor: ""
                    });
                } catch (error) {
                    alert("Erro ao inserir novo campo!");
                }
            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });
        }, function (reject) {
            alert("erro" + reject);
        });

    };

A: I assume you use the $http service in contatosAPI.getDados function. You can set a timeout parameter manually in the configuration of your request so that it doesn't end too early. See Angular documentation of $http


text:
Q: Get and Set Java into Ruby I'm currently learning OOP in ruby language but I'm having some trouble to understand constructor concepts. So I was trying to convert one code that I did in java into ruby. Take a look:
Java code:
public class Test {
       public Test(int[][] array) {
           this.array= array;
      }
       public int[][] getTest() {
           return array;
      }
    }

Ruby code:
class Test
  def Test(*array)
    @test = test
  end
  def getTest()
    return array
  end
end

Is it right? Or should I use initialize class? Thank you in advance!

A: The issue is that array in getTest is a local variable. I have a feeling you want to return the variable that was set in the test method (You can't capitalize method names without define_method, but that's another story). Ruby also has shortcuts for this. Here are a couple ways you could to it:
class Test
  attr_accessor :test
end
my_test = Test.new
my_test.test = "Hello Test"
my_test.test #=> "Hello Test"

The above example uses the built in attr_accessor method to define a setter and a getter method for that variable.
class Test
  def test(value)
    @test = value
  end
  def getTest
    @test
  end
end

This one is the exact same as attr_accessor but it's slightly slower and the getter method is renamed to getTest.
Or, if you want it to be a constructor:
class Test
  def initialize(test)
    @test = test
  end
  def getTest
    @test
  end
end

And lastly, if you actually want the capitalized method name:
class Test
  define_method(:Test) do |test|
    @test = test
  end
  def getTest
    @test
  end
end

A: Java code:
public class Test {
   private int[][] array; // you need to explicitly declare this

   public Test(int[][] array) {
      this.array = array;
   }

   public int[][] getTest() {
       return array;
   }
}

Ruby code:
class Test
  #implicitly declares a getter method 'array' that returns @array field
  attr_reader :array

  # constructor. Test.new(array) to invoke
  def initialize(*array)
    @array = array # sets value to the private fiend @array
  end
end


text:
Q: Is making simple website in "java spring hibernate" is overkilling Initially i was php programmer and was using joomla to build websites .
I could easily build good websites in joomla in few days.
I was learning java spring hibernate  for last three months and now i have build simple user registration logins and members area using spring MVC , hibernate annotation etc.
Now i want to ask that whether from now onwards should i use spring MVC to build site just because i have learned it or its good for me in future.  Because i still feel that the same site can be build in few days in php
Is it the case that in future i can also come on same level as php that i can build simple site in java in few days as well or no matter what experience i have java still is going to take longer than php always
Can any java CMS make my life easier because i want to say good bye to php.
i mean if i want to make just 5 page portfolio website can build in java cms in 1-2 days

A: If by "simple website" you mean a normal page with categories, articles and some navigation (i.e. not a web-application), then yes: Building that from the grounds up with Java + Spring + Hibernate is probably overkill (i.e. those are low-level tools, you'd have to build a lot yourself). I'd stick with the tools built for this specific task, namely some kind of CMS system.
If you want to bring "some Java" into your day-to-day job, then you might want to try looking into a Java CMS system.

A: You should, of course, use the appropriate tools for the job. Spring MVC is not appropriate if you are re-implementing functionality that has already been robustly provided by an existing tool (eg. Joomla etc.).
Given that much of the 'interactive' part of many websites can now be hosted elsewhere (eg. Disqus for comments and so on), you may not need a dynamic website at all and could host the site on one of the many cloud services for static content. This has the advantage that your performance is elastic, and 'cost per user' can be vanishingly low.


text:
Q: Scala: How to return the key that contains an item in their value where value is a Set? I have a Map[Int, Set[Int]]and given an item I want to return the key that indexes to the Set where item exists in. For example if I have a Map(1 -> Set("a"), 2 -> Set("b"), 3 -> Set("c","z")). Say the item is "z" I want to return 3 because 3 is the key that indexes to the set that contains 3.
Here is what I currently have, but I can't seem to find a good way to get the key. I can only get the value, the Set[Int]. Assume the item will only be in one possible set.
def find(djs: Map[Int, Set[Int]], item: Int) :Int = {
for ((key, set) <- djs) {
  if (set.contains(item)) {
    key
  }
}

A: The find operator can work well here:
def find[A, B](m: Map[A, Set[B]], item: B): Option[A] =
    m.find { case (key, set) => set.contains(item) }
     .map  { case (key, set) => key }

A: If you need to return one or None then Option[] would be the way to go. If returning one, many, or none is required then returning a List[] might be in order.
val m = Map(1 -> Set("a"), 2 -> Set("b"), 3 -> Set("c","z"))

m.flatMap{ case (k,vs) => if (vs.contains("z")) Seq(k) else Seq() }  // List(3)
m.flatMap{ case (k,vs) => if (vs.contains("w")) Seq(k) else Seq() }  // List()

A: collectFirst is made for this:
val m = Map(1 -> Set("a"), 2 -> Set("b"), 3 -> Set("c","z"))

m.collectFirst{case (k,v) if v.contains("z") => k}
//> res0: Option[Int] = Some(3)

and I always forget Set can be used as a function itself (i.e. apply is the same as contains)
m.collectFirst{case (k,v) if v("z") => k}
//> res0: Option[Int] = Some(3)


text:
Q: Save entity with entity framework I'm saving entities/records with the EF, but i'm curious if there is another way of doing it.
I receive a class from a MVC controller method, so basicly i have all the info: the class's properties, including the primary key.
Without EF i would do a Sql update (update table set a=b, c=d where id = 5), but with EF i got no further than this:
Get an object with ID of 5
Update the (existing) object with the new object
Submitchanges.
What bothers me is that i have to get the object from the database first, where i have all the info to do an update statement.
Is there another way of doing this?

A: No, the pattern is typically:

*

*select the entity

*Update the properties

*Save your changes

Another SO question on this topic.

A: u will have to create an object, update the properties and then savechanges

try this

using (var context = new NorthWindEntities())
{
    Product prod = new Product();
    prod.Name = "Car toy";
    prod.Price = "10.00";

    prod.SaveChanges();//this method will actuayll save the changes

}


text:
Q: AutoCad: how to choose a font of a text in a script I would like to write an AutoCad script that would print a text but I want to choose a specific font as well (font: txt). How could I do that? Thanks for your help!
For now I have only this:
_text 1079.0292,593.8346 99.8441 0.0 Katarzyna

A: AutoCAD doesn't allow you to directly control the font of text while placing text. In the text commands, you can only choose from a currently existing Style within your DWG. Below is detailed info on the text command within AutoCAD
https://knowledge.autodesk.com/support/autocad/learn-explore/caas/CloudHelp/cloudhelp/2016/ENU/AutoCAD-Core/files/GUID-D1C664DD-63D9-467E-8EC1-2F5A1777A924-htm.html
What you can do, however; is run the -style command with a script, automate the creation of a style with the font you want and then have the text routine in your script reference that style.
Here is an example of that.  You can copy/paste this directly into the AutoCAD command line and see it in action
-style TESTSTYLE
Arial
6 1 0 N N
-text S
TESTSTYLE
16,20
0.0
BLAH

A: You are using _text, so set the font is complicated. but maybe You may use Mtext? If so You can easy set font for example like this:
_-Mtext 1070.0,590.0 1080.0,595.0 {\fTahoma.ttf|;Katarzyna}


text:
Q: need to merge the array with matching the value I have a array like this how  i will get new array
Array
(
    [0] => Array
        (
            [model] => MX555
            [color] => RED
            [qty] => 2
        )

    [1] => Array
        (
            [model] => MX555
            [color] => RED
            [qty] => 2
        )

    [2] => Array
        (
            [model] => MX555
            [color] => Green
            [qty] => 2
        )

    [3] => Array
        (
            [model] => MX555
            [color] => Green
            [qty] => 1
        )
)

I need to return the array like this
Array
(
    [0] => Array
        (
            [model] => MX555
            [color] => RED
            [qty] => 4
        )

    [1] => Array
        (
            [model] => MX555
            [color] => Green
            [qty] => 4
        )
)

A: I'm assuming you want to identify duplicate items by multiple values, in this case both model and color (if you only want to group by the single value color then see RamC's answer instead). One approach is to create an array, where each key is created by concatenating those values:
function mergeQuantitiesByModelAndColor(array $array)
{
    $merged_array = array();
    foreach ($array as $item) {
        $key = $item['model'] . '|' . $item['color'];
        if (!isset($merged_array[$key])) {
            $merged_array[$key] = $item;
        } else {
            $merged_array[$key]['qty'] += $item['qty'];
        }
    }
    return array_values($merged_array);
}

When tested as follows (php 5.6):
$array = array(
    array(
        'model' => 'MX555',
        'color' => 'RED',
        'qty' => 2,
    ),
    array(
        'model' => 'MX555',
        'color' => 'RED',
        'qty' => 2,
    ),
    array(
        'model' => 'MX555',
        'color' => 'Green',
        'qty' => 2,
    ),
    array(
        'model' => 'MX555',
        'color' => 'Green',
        'qty' => 1,
    ),
);

var_dump(mergeQuantitiesByModelAndColor($array));

Gives output:
array(2) {
  [0]=>
  array(3) {
    ["model"]=>
    string(5) "MX555"
    ["color"]=>
    string(3) "RED"
    ["qty"]=>
    int(4)
  }
  [1]=>
  array(3) {
    ["model"]=>
    string(5) "MX555"
    ["color"]=>
    string(5) "Green"
    ["qty"]=>
    int(3)
  }
}

A: Sum Quantity grouping by element
From your question, it is inferable that you want to add the quantity of similar items.
If that is the case, then you can achieve it with the following code snippet.
In the below snippet, I've grouped the items using the element color.
Feel free to change it as per your requirement.
Snippet
$group_by = 'color';

foreach ($data as $item) {
    if (!isset($res[$item[$group_by]])) {
        $res[$item[$group_by]] =  $item;
    } else {
        $res[$item[$group_by]]['qty'] += $item['qty'];
    }
}

Code
$data = [
  [
      'model' => "MX555",
      'color' => "RED",
      'qty' => 2,
  ],
  [
      'model' => "MX555",
      'color' => "RED",
      'qty' => 2,
  ],
  [
      'model' => "MX555",
      'color' => "Green",
      'qty' => 2,
  ],
  [
      'model' => "MX555",
      'color' => "Green",
      'qty' => 1,
  ],
];

$res = [];
$group_by = 'color';

foreach ($data as $item) {
    if (!isset($res[$item[$group_by]])) {
        $res[$item[$group_by]] =  $item;
    } else {
        $res[$item[$group_by]]['qty'] += $item['qty'];
    }
}

print_r(array_values($res));

Output
Array
(
    [0] => Array
        (
            [model] => MX555
            [color] => RED
            [qty] => 4
        )

    [1] => Array
        (
            [model] => MX555
            [color] => Green
            [qty] => 3
        )

)


text:
Q: Scripted Jenkins file for maven package I am writing a Jenkinsfile for Maven package by using scripted syntax
node{
    stage('Checkout')
          git url:'<gir url>',branch: 'master
    stage('build')
          sh 'mvn clean package'
}

my problem is how to declare the maven version in above Jenkinsfile (in scripted syntax only)

A: I just completed a major Jenkins Pipeline/Maven implementation with the Pipeline Maven Integration plugin: https://plugins.jenkins.io/pipeline-maven.
It let's you leverage Maven Tool configuration when you run Maven commands in your pipeline.


text:
Q: Responsive html layout height 100% is not according to parent div I'm really new in html
This is my code

 OUR VISION

        To become the best foundation that is able to nurture holistic global leaders

 OUR MISSION

        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values

So I have 2 column in a row. This is what happened
my first column leaves empty white space below it
Is there any way to have both my columns to extend to 100% parent div's height?

A: Use flex

.w3-row{
display: flex;
align-items: center;
}

.w3-container {
flex: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 OUR VISION

        To become the best foundation that is able to nurture holistic global leaders

 OUR MISSION

        Developing young muslim leaders by nurturing entrepreneurial mindset in order to provide the best
        solution for mankind through Islamic values

A: One solution is to use flex like @Supraja suggested, but an even simpler solution is to give the orange bg to the container of the columns instead of the column itself.
so put .w3-orange on the div with w3-row class:

A: Thats the problem of responsive layouts.
Add the orange background-color to the w3-row.
To prevent the different hights you have to add some hight values to your .w3-containers.


text:
Q: Generalist badge wording isn't clear The generalist badge (which, apparently, is now awarded, contrary to what other questions here on meta suggested) has a very unclear description: "Provided non-wiki answers of 15 total score in 20 of top 40 tags"
What are the "top 40 tags"? According to what ranking? If an answer has more than one tag, does it count towards 20? (i.e., could the badge theoretically be reached with only 4 answers?)
Edit: also, does the "15 total score" apply to each of the 20 tags, or to the total sum? I suspect the latter, otherwise it seems very easy.

A: What are the "top 40 tags"? According to what ranking?
Number of questions with that tag, the order they appear in the tags page
If an answer has more than one tag, does it count towards 20?
I would expect so, there's no reason it wouldn't. It's unlikely that you could actually manage it with 4 answers though, since the top tags are mostly individual languages and it's tough to find questions tagged with five different languages


text:
Q: Which browser pioneered JIT-compiled JavaScript? I learn that, these days, all browsers JIT-compile JavaScript, and NOT interpret it.
I want to ask which browser pioneered this idea, i.e. introduced it for the very first time. I feel that it might be Google Chrome but there's absolutely no article out there to confirm this.


text:
Q: Get post values in controller in yii I have a function in controller
public function actionIndex()
{
            $this->render('dashboard');
}

In dashboard page i have a form update
while trying to click button it goes to actionIndex.
I want to get  post values in update function .. how it will be

A: I assume you are using CActiveForm in your update form. you can do in form update like this
<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'my-form',
        'action'=>CController::createUrl('update')
)); ?>


text:
Q: Python Tkinter - frame weight problem using grid layout root frame weight is correct when button btnOpen is not present (commented). Otherwise the weight of root and frLeft is about 1:1. Why button (or frame frButtons) makes a difference?
Here is the code:
from tkinter import *

root = Tk()
root.title("xxx")
root.geometry("500x400")
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=15)
root.columnconfigure(1, weight=10)

frLeft = Frame(root, bg="#808080")
frLeft.grid(row=0, column=0, sticky="NSEW")

frRight = Frame(root, bg="#FAF0F0")
frRight.grid(row=0, column=1, sticky="NSEW")
frRight.rowconfigure(0, weight=1)

frButtons = Frame(frRight, bg="red")
frButtons.grid(row=0, column=0, sticky="W", padx=10, pady=10)

btnOpen = Button(frButtons, command=open, text='Open', padx=2).grid(row=0, sticky="WS", padx=10)

root.mainloop()

Correct:

Not correct:


text:
Q: scale videos in p:media tag how to scale the video in the media tag?
<p:media value="#{mediaBean.media}" width="250" height="225" player="quicktime"/>

the resolution is bigger thant 250x225 - so I just see parts of the videoscreen - why it's not automatically scaling the video to 250x225 ? any ideas?
regards

A: You have to send scale attribute as parameter (f:param) to the player.
<p:media value="#{mediaBean.media}" width="250" height="241" player="quicktime"/>
        <f:param name="scale" value="tofit" />
</p:media>

Each player specifies what parameters they support.
In your case quicktime supports scale attribute:

scale
SCALE is either TOFIT, ASPECT or a number. By default the value of
  SCALE is 1. If set to TOFIT, the movie is scaled to fit the embedded
  box as specified by the HEIGHT and WIDTH attributes. If this is set to
  ASPECT, the movie will scale to fit the embedded box while maintaining
  the aspect ratio. If this is set with a number, the movie will be
  scaled by that number (e.g. 1.5). Note: Using the number scale
  attribute with a QTVR Panorama movie can degrade the performance of
  the movie even on high-end systems.

Useful links here:
Quicktime
Flash
Windows Media Player


text:
Q: Identify lines and put a > before them Let's say I had this text:
Vivamus ullamcorper adipiscing bibendum.

Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.

Integer cursus malesuada consectetur.
Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
Cras semper, nisl sodales viverra volutpat.
Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.

And wanted to put a > before every line, like so:
> Vivamus ullamcorper adipiscing bibendum.
>
> Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
> Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.
>
> Integer cursus malesuada consectetur.
> Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
> Cras semper, nisl sodales viverra volutpat.
> Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.

What function should I look into/how would i do?

A: You can use str_replace and rtrim for this
 $str = rtrim("> ".str_replace("\n", "\n> ", $str), ">\n");

omit rtrim if you want to retain any trailing >'s
TEST
<?php
$str = 'Vivamus ullamcorper adipiscing bibendum.

Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.

Integer cursus malesuada consectetur.
Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
Cras semper, nisl sodales viverra volutpat.
Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.';

 $str = rtrim(">".str_replace("\n", "\n> ", $str), ">\n");

 echo $str;

OUTPUT
> Vivamus ullamcorper adipiscing bibendum.
>
> Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
> Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.
>
> Integer cursus malesuada consectetur.
> Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
> Cras semper, nisl sodales viverra volutpat.
> Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.

A: <?php
$str = 'Vivamus ullamcorper adipiscing bibendum.

Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.

Integer cursus malesuada consectetur.
Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
Cras semper, nisl sodales viverra volutpat.
Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.';

$str = ">" . $str;
$str = preg_replace("/\n/", "\n>",$str);
print $str;

Prints:
>Vivamus ullamcorper adipiscing bibendum.
>
>Etiam faucibus facilisis tortor, in viverra nulla condimentum eu.
>Vivamus eu tellus adipiscing, molestie nisi vel, malesuada lacus.
>
>Integer cursus malesuada consectetur.
>Curabitur tellus mi, tristique vel urna et, auctor tincidunt augue.
>Cras semper, nisl sodales viverra volutpat.
>Phasellus feugiat quam nec orci accumsan gravida ut vitae risus.


text:
Q: Domination and generalized low 2 sets A function $f : \omega \to \omega$ satisfies the domination property if $f$ is (eventually) dominated by the function $g : n \mapsto \sup \{ t : (\exists e \le n)(\exists \sigma \in 2^n)(\exists \tau \succeq \sigma)[\tau \in W_{e, t+1} \setminus W_{e, t}]\}$.  The significance of the domination property includes that a function without the domination property computes a 1-generic set.
I would like to show

If all functions $M$ computes satisfy the domination property, $M$ is generalized low 2 (GL2).

The proof, I suppose, should involve reducing the $\Sigma^0_2(M)$-complete set $\mathrm{Tot}^M = \{e : \Phi_e^M\text{ is total}\}$ to $(M \oplus 0')'$.  It is easy to see that the complement of $\mathrm{Tot}^M$ is c.e. relative to $M' \le_T (M \oplus 0')'$, so it only remains to show that $\mathrm{Tot}^M$ is c.e. relative to $(M \oplus 0')'$.  For this, I should come up with an $M$-computable function $f$ to appeal to the assumption, but I have no idea what $f$ to pick.  I am aware of the characterization of GL2 sets by Martin, which sounds a little bit similar to the situation above but not quite.
How can I show that?

A: Actually, that can be proved by using Martin's characterization of GL2 sets: a set $A$ is GL2 iff there is a function $ g \le A \oplus 0'$ that dominates all $A$-computable functions.  The function $g$ above is $0'$-computable, and $M \oplus 0'$-computable a fortiori, so the result follows.


text:
Q: HAProxy: configuring SSL with Let's Encrypt I just generate a new SSL certificate using Let's Encrypt. Now I'm trying to configure HAProxy.
These are the folders and certificates:
700  archive
     |--------> 755 company.cxx
                    |------------> 644 fullchain.pem
                    |------------> 644 cert.pem
                    |------------> 644 (etc.)

Right now, these are the permissions of folders and soft links to the certificates in the archive folder:
700  live
     |--------> 755 company.cxx
                    |------------> 777 fullchain.pem
                    |------------> 777 cert.pem
                    |------------> 777 (etc.)

HAProxy is configured like this:
frontend public
    bind :80
    bind :443 ssl crt /etc/letsencrypt/live/company.cxx/fullchain.pem

And the error is this:
Proxy 'public': no SSL certificate specified for bind ':443' at [/etc/haproxy/haproxy.cfg:12] (use 'crt').
Fatal errors found in configuration.

I don't know if the permissions are the problem, but I'm worried about which would be the right way to do this with HAProxy. I will appreciate your help.
EDIT: Just for testing, I tried copying the certificates to /etc/haproxy but it didn't work.

A: The solution is explained on DigitalOcean. In short:

*

*Create a pem file concatenating fullchain.pem and privkey.pem

*Move that new file to /etc/haproxy/certs

*Configure HAProxy

A: As you specified in your own answer, the bare minimum that you need from LetsEncrypt (LE) is a concatenated version of the fullchain.pem and privkey.pem.
But running the LE client manually every time the cert is going to expire sort of defeats the purpose of using LE.  Additionally, you can't use the LE client in standalone mode if your HAProxy instance is already listening on port 80 for other websites.
As an alternative, you may be interested in this HAProxy ACME validation plugin.

The plugin leverages HAProxy's Lua API to allow HAProxy to answer validation challenges using token/key-auth files provisioned by an ACME client to a designated directory.

Essentially, you have HAProxy sending all requests that match the well known ACME validation path to a LUA plugin that automatically answers the request for whatever domain is being requested.  You also have a cron job setup that checks the cert expirations on a regular basis and renews them automatically before they expire.  So your only manual step is requesting the initial cert for a domain and adding the PEM reference to your HAProxy config file. After that, the cron job keeps your cert up to date forever (hypothetically).