text:
Q: How to destructure an enum's fields and as a whole value at the same time? I want to match an enum variant, process it and then pass it further. The code should look like this:
enum Event {
    WindowEvent {
        event: WindowEvent,
        window_id: usize,
    },
}
enum WindowEvent {
    Resized(u8),
}

struct Demo {
    size: u8,
}

impl Demo {
    fn reproduction(&mut self, event: Event) {
        match event {
            e
            @
            Event::WindowEvent {
                event: WindowEvent::Resized(size),
                ..
            } => {
                self.size = size;
                self.handle_event(e);
            }
        }
    }

    fn handle_event(&self, _event: Event) {}
}

This code doesn't pass the borrow checker:
error[E0007]: cannot bind by-move with sub-bindings
  --> src/lib.rs:18:13
   |
18 | /             e
19 | |             @
20 | |             Event::WindowEvent {
21 | |                 event: WindowEvent::Resized(size),
22 | |                 ..
23 | |             } => {
   | |_____________^ binds an already bound by-move value by moving it

error[E0658]: pattern bindings after an `@` are unstable
  --> src/lib.rs:21:45
   |
21 |                 event: WindowEvent::Resized(size),
   |                                             ^^^^
   |
   = note: see issue #65490 <https://github.com/rust-lang/rust/issues/65490> for more information

error[E0382]: use of moved value: `event`
  --> src/lib.rs:21:45
   |
16 |       fn reproduction(&mut self, event: Event) {
   |                                  ----- move occurs because `event` has type `Event`, which does not implement the `Copy` trait
17 |           match event {
18 | /             e
19 | |             @
20 | |             Event::WindowEvent {
21 | |                 event: WindowEvent::Resized(size),
   | |                                             ^^^^ value used here after move
22 | |                 ..
23 | |             } => {
   | |_____________- value moved here

I can fully destructure event and construct it again on pass to handle_event, but this seems wrong. Why should I construct a new object when I can pass the existing one? Why should I care about other fields (there can be plenty of them!) when I could use the wildcard ..:
match event {
    Event::WindowEvent {
        event: WindowEvent::Resized(size),
        window_id,
    } => {
        self.size = size;
        self.handle_event(Event::WindowEvent {
            event: WindowEvent::Resized(size),
            window_id,
        });
    }
}

I found another solution that requires matching twice:
match event {
    e
    @
    Event::WindowEvent {
        event: WindowEvent::Resized(_),
        ..
    } => {
        if let Event::WindowEvent {
            event: WindowEvent::Resized(size),
            ..
        } = e
        {
            self.size = size;
        }
        self.handle_event(e);
    }
}

Is there a better way to destucture an enum variant without losing the original value?

A: In this case, reuse the event value without trying to do fancy pattern matching techniques:
match event {
    Event::WindowEvent {
        event: WindowEvent::Resized(size),
        ..
    } => {
        self.size = size;
        self.handle_event(event);
    }
}

In the future, there will be another option. As the compiler's error messages state:

error[E0007]: cannot bind by-move with sub-bindings
error[E0658]: pattern bindings after an @ are unstable
note: see issue #65490 for more information

On nightly Rust, you can add #![feature(bindings_after_at)] and then change your code to match on a reference:
fn reproduction(&mut self, event: Event) {
    match &event {
        e
        @
        Event::WindowEvent {
            event: WindowEvent::Resized(size),
            ..
        } => {
            self.size = *size;
            self.handle_event(e);
        }
    }
}

fn handle_event(&self, _event: &Event) {}

If the enums you are matching on are Copy, you won't need to take the reference.


text:
Q: Overwrite style properties on select in OpenLayers I want to reuse my basic style function to create an select style by overwriting some of the properties.
This approach is working for fill/stroke colors of linestrings, polygons and texts, but not for images (a circle in my case).
I don't want to create a new image since other properties should be retained.
var selectStyleFunction = function(feature, resolution) {
  var style = styleFunction(feature, resolution)[0];
  style.getImage().getFill().setColor("magenta");

  console.log(style.getImage().getFill().getColor());

  return [style];
};

In this fiddle you can see, that the above code doesn't change the feature style on selection although the log output is correct.
Is there any way to overwrite this property?

A: I found an answer to my question in the api dokumentation of openlayers. It was too obvious to find it in the first place.
https://openlayers.org/en/latest/apidoc/ol.style.Style.html

ol.style.Style
  Container for vector feature rendering styles. Any changes made to the style or its children through set*() methods will not take effect until the feature or layer that uses the style is re-rendered.

So rendering is not triggered by the setters.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing custom type parameters to stored procedures using PyODBC I have a type (of table) and a stored procedure:
CREATE TYPE [Scheduler].[CondType] AS TABLE (condition VARCHAR(32));

CREATE PROCEDURE [Scheduler].[SP_GetResult]
    (@current_time AS NVARCHAR(5),                -- "%HH:%MM"
     @cond_table [Scheduler].[CondType] READONLY)
AS
    SELECT [name], [sched_time], [condition]
    FROM [Scheduler].[ScheduleTable]
    WHERE [condition] IN (SELECT condition FROM @cond_table)
      AND @current_time = [sched_time]

I want to call this stored procedure with the simple text parameter and the complex (list/table) parameter from Python:
# not important technical details
tokenstruct = ...
conn_str = "Driver=%s;Server=tcp:%s,1433;Database=%s;" % (cfg.driver, cfg.sql_server, cfg.sql_database)
conn = pyodbc.connect(conn_str, attrs_before = { 1256:tokenstruct })
cursor = conn.cursor()

# input data
hour_and_minute = "08:00"
conditions = ["tuesday", "weekend"]
sql = "{ call Scheduler.SP_GetResult(@current_time=?, @cond_table=?) }"

# execute stored procedure
cursor.execute(sql, (hour_and_minute, conditions)) # but how to pass arguments properly here?
result_set = cursor.fetchall()

When I try to execute, the simple parameters is OK, but I get an exception like this for the table parameter:

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column, parameter, or variable #2: Cannot find data type tuesday. (2715) (SQLParamData)')

or

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column, parameter, or variable #2: Cannot find data type CondType. (2715) (SQLParamData)')

Question: how could I pass a table type parameter properly?
If I do this from SQL console, it works fine:
DECLARE @DL CondType;
INSERT @DL VALUES ('tuesday'), ('weekday');
EXEC [Scheduler].[SP_GetResult] @current_time = '08:00', @cond_table=@DL;
GO

I've tried to modify the passed parameter but I always get similar error:
conditions = ["tuesday", "weekend"]
conditions = [("tuesday", ), ("weekend", )]
conditions = ("tuesday", "weekend")
conditions = (("tuesday", ), ("weekend", ))


text:
Q: Unable to return value from a recursive function While trying to get value of a key in a nested dictionary by ignoring the hierarchy, it always returns None.
def nested(d,key):
    for i in d.keys():
        if i == key:
            return d[i]
        elif isinstance(d[i], dict):
            nested(d[i],key)

j = {'hello': {'foo': {'bar': {'world':'yeay'}}}}
print(nested(j,'world'))

The expected answer is yeay of course, But what am I missing?


text:
Q: How to treat structures using STL iterators I am new in C++. I am using g++ compiler. I was trying to learn operations of STL library in C++. While working I found some problem in this code. Please explain the reason of the error and how to take care the error.
#include<iostream>
#include<list>
using namespace std;

typedef struct corrd{
int x;
int y;
}XY;

int main()
{
list<XY> values;
list<XY>::iterator current;
XY data[10];
for(int i=0;i<10;i++)
{
    data[i].x = i+10;
    data[i].y = i+20;
}
for(int i=0;i<10;i++)
{
    values.push_front(data[i]);
}
current = values.begin();
while(current!=values.end())
{
    cout<<"X coord:"<<*current->x<<endl;//error: invalid type argument of unary '*' (have 'int'
    cout<<"Y coord:"<<*current->y<<endl;//error: invalid type argument of unary '*' (have 'int'
    current++;
}
}

A: update
cout<<"X coord:"<<*current->x<<endl;
cout<<"Y coord:"<<*current->y<<endl;

to:
cout<<"X coord:"<<(*current).x<<endl;
cout<<"Y coord:"<<(*current).y<<endl;

or
cout<<"X coord:"<<current->x<<endl;
cout<<"Y coord:"<<current->y<<endl;

current is iterator, if you try to dereference it(*current), *current points to real object(x or y) is an object not pointer, so you need to call (*current).x.
If you don't dereference current iterator, you could call operator-> to refer to the real object.
Also note that operator-> and operator* have different precedence, see C++ Operator Precedence.
If you store XY pointer in std::list, you should use iterator this way:
list<XY*> values;
list<XY*>::iterator current;
cout<<"X coord:"<<(*current)->x<<endl;  // parentheses is needed due to Operator Precedence
cout<<"Y coord:"<<(*current)->y<<endl;

A: You use *current to "convert" iterator to object it contains. As You have XY struct there (not as pointer but by value), you should write:
cout<<"X coord:"<<(*current).x<<endl;
cout<<"Y coord:"<<(*current).y<<endl;

( "." instead of "->").
The other way to do it is to use "->" operator of iterator. It allows to use members of contained type (struct or class) directly. Then you need to write:
cout<<"X coord:"<<current->x<<endl;
cout<<"Y coord:"<<current->y<<endl;

Just remove '*'

A: An iterator is a bit like a generalised pointer (it has the same semantics of * and ->). You're correctly using -> to access a member of the structure the iterator points to. That member is of type int, so there's nothing left to dereference. So just do this:
cout<<"X coord:"<<current->x<<endl;
cout<<"Y coord:"<<current->y<<endl;

A: The error "invalid type argument of unary '*' (have 'int')" comes from the following expression: *current->x. What's that int argument of unary *? Well, current->x of course, If you look up your declaration of x, you'll see that it's an int.
So, you could write 5 * current->x, but that's multiplication. Unary *, dereferencing, requires a (smart) pointer or iterator on the right.
Note that -> has higher precedence than unary *, so the code is not parsed as (*current)->x but as *(current->x)


text:
Q: gathering the rank's domain to the rank master to write results Let's say that you separated your domain according to the number of ranks (with mpi_cart_create) then you have the indices of each domain. Then I want to use gatherv to put back a global array in order to write the results. This code seems to work for 2 or 4 processes but doesn't for 8. I feel like I am missing something. There should be no error message.
Edit : each rank contains its local array. Its elements are equal to the rank of the process (from 0 to n_procs). What I am trying to archieve is to put back the global array with gatherv. This is for a finite volume code. My aim is just to reproduce the domain decomposition and what I desire with gatherv. Here, there should be no -10 in the print and the block should be clearly dissociable with the decomposition done by mpi.
The code works as follow : I separate my domain, compute the delimitation/indices associated to each domain, definite my new type that will be received in the global array, then calculate the displacement and use gatherv.
program scatter
   use mpi
   implicit none
   integer,parameter :: nrows = 8,ncols = 8
   integer, dimension(8,8) :: global
   integer, dimension(2)   :: dims_orig,dims,coo,sizes,subsizes,coo_init
   logical,dimension(2) :: periods
   integer, dimension(:,:),allocatable :: local
   integer, dimension(:),allocatable :: displ,counts
   integer :: info,code,rank,n_procs,comm2d
   integer :: ndi,ndj,nni,nnj,nni_last,nnj_last
   integer :: i1,i2,j1,j2,ii1,ii2,jj1,jj2,row,col
   integer :: type0,type_subarray,sizeofint,i,j
   integer :: imax,jmax,loc_size
   integer(kind=mpi_address_kind) :: start,extend
   logical :: reorder

   ! dimensions of the global array
   imax = nrows
   jmax = ncols

   ! default value of the global array
   global = -10

   call mpi_init(code)
   call mpi_comm_rank(mpi_comm_world,rank,code)
   call mpi_comm_size(mpi_comm_world,n_procs,code)

   dims_orig = 0

   CALL MPI_DIMS_CREATE(n_procs ,2,dims_orig,code)

   ! number of domain in each direction
   ndi = dims_orig(1)
   ndj = dims_orig(2)

   ! nni/nnj = sizes of each domain
   nni = nrows/ndi
   nnj = ncols/ndj
   nni_last = nrows-(ndi-1)*nrows/ndi
   nnj_last = ncols-(ndj-1)*ncols/ndj

   dims(1) = ndi
   dims(2) = ndj
   periods = .false.
   reorder = .true.

   call mpi_cart_create(MPI_COMM_WORLD,2,dims,periods,reorder,comm2d,code)

   call mpi_comm_rank(comm2d,rank,code)

   call mpi_cart_get(comm2d,2,dims,periods,coo,code)

   if(coo(1)==ndi-1) then
      nni = nni_last

      i2 = imax
      i1 = i2-nni+1
   else
      i1 = rank/ndj*nni+1
      i2 = i1+nni-1
   endif

   if(coo(2)==ndj-1) then
      nnj = nnj_last

      j2 = jmax
      j1 = j2-nnj+1
   else
      j1 = MOD(rank,ndj)*nnj+1
      j2 = j1+nnj-1
   endif

   print*,rank,"|",i1,i2,j1,j2
   call mpi_barrier(mpi_comm_world,code)
   ! create new types
   sizes = [imax, jmax]
   subsizes = [i2-i1+1,j2-j1+1]
   coo_init = [i1-1   ,j1-1   ]

   call mpi_type_create_subarray(2,sizes,subsizes,coo_init,&
           mpi_order_fortran,MPI_integer,type0,code)

   call mpi_type_size(MPI_INTEGER,sizeofint,code)
   start = 0
   extend = sizeofint*nnj
!   call mpi_type_get_extent(type0,start,extend,code)
   call MPI_TYPE_CREATE_RESIZED(TYPE0,start,extend,TYPE_SUBARRAY,info)
   !type_subarray = type0
   call MPI_TYPE_COMMIT(TYPE_SUBARRAY,code)

   allocate(displ(ndi*ndj))

!   forall(col=1:ndj,row=1:ndi)
!      displ(1+(row-1)+(col-1)*ndi) = (row-1)+(col-1)*imax
!      ! displ(1+(row-1)*ndi+(col-1)) = (row-1)*ndi+(col-1)
!   endforall
   ! computing the displacement
   do i =1,ndi
   do j = 1,ndj
      displ(1+(i-1)+(j-1)*ndj) = (i-1) + (j-1)*imax
   enddo
   enddo
   allocate(local(i1:i2,j1:j2))
   allocate(counts(n_procs))

   counts = 1
   local = rank
   loc_size = (i2-i1+1)*(j2-j1+1)!(i2-i1+1)*(j2-j1+1)

   call mpi_gatherv(local,loc_size,MPI_integer,&
           global,counts,displ,type_subarray,0,&
           MPI_COMM_WORLD,code)
   call mpi_barrier(mpi_comm_world,code)
   if(rank==0) then
      do i = 1,nrows
      print*,global(i,:)
      enddo
   endif
   call mpi_finalize(code)

endprogram scatter


text:
Q: Binding a text box value with condition in aspx page I am using asp form view. I want to bind a text box value based on condition.

    <asp:TextBox ID="txtHaulZoneCodeLEM"
            runat="server"
            CssClass="cagText"
            Text='<%# Bind("HaulZoneCodeLEM") %>'>
    </asp:TextBox>

I have tried this:
<asp:TextBox
    ID="txtHaulZoneCodeLEM"
    runat="server"
    CssClass="cagText"
    Text='<%# ((TextBox) Container.DataItem).HaulZoneCodeLEM != 0 ? ((TextBox) Container.DataItem).HaulZoneCodeLEM : string.Empty %>'>

How to resolve this?
I moved to code behind :

       <asp:TextBox ID="txtHaulZoneCodeLEM" runat="server" CssClass="cagText" Text=ConvertHaulZoneCodeForDisplay('<%# Bind("HaulZoneCodeLEM") %>')>
                                        </asp:TextBox>

In My code behind page I wrote like this :
 Protected Function ConvertHaulZoneCodeForDisplay(ByVal str As String) As String
        If str = 0 Then Return ""
    End Function
End Class

Still I am getting error in the aspx page..

A: Is it possible for you to consider using  event instead of method?
There, you can check the value of the textbox and you can modify it.
Whatismore, if you are binding data to textbox from a datasource, I suggest you to use data binding event.
for more info : http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx


text:
Q: How to prevent View above the keyboard (adjustResize)? My layout has the following structure:

In the manifest I have an attribute that defines the behavior of the keyboard display after the user clicked on the EditText, which is contained in the ScrollView:
android:windowSoftInputMode="adjustResize"

Here is btnApply markup:
<LinearLayout
    android:id="@+id/btnApply"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="false"
    android:layout_alignParentStart="true"
    android:background="#00bbe3"
    android:orientation="vertical"
    android:layout_alignParentTop="false">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="15dip"
        android:text="Continue"
        android:textColor="#ffffff"
        android:textSize="23.75sp"
        android:textStyle="bold" />
</LinearLayout>

So, btnApply floats above the keyboard on top of the ScrollView, and I can scroll all of the EditText's if they don't fit on the screen.
Is it possible to make btnApply doesn't pop up above the keyboard and was pressed to the bottom of the screen?

A: try to change
android:windowSoftInputMode="adjustResize"
to
android:windowSoftInputMode="adjustPan"

moreover you dont need to put editText in scrollView.
You can just simply add
android:scrollbars = "vertical"

to your editText
cheers


text:
Q: Check if url has specific string in python 3 I am new to python and I couldn't figure this out
In this code I need to check if the url has http or not
for link in links:
    if "http" in link.get("href"):
        print("%s" % (link.get("href"), link.text))

When running I got this error:

TypeError: argument of type 'NoneType' is not iterable

How can I fix that?
Thanks in advance for the help.

A: You can just try using string.find.
But it seems like your problem is that link.get("href") returned None.
Your link probably has no "href".

A: I had to guess a little bit what exactly your context was. But this might help you.
You can check if something is None by "if var is None:" and continuing the loop.
But my recommendation is to start with basic tutorials instead of jumping right into some concrete tasks... this might be easier for you :)
from bs4 import BeautifulSoup
import re

website = """#INSERT_HTML_CODE"""
soup = BeautifulSoup(website, 'html.parser')

p = re.compile("https://")
soup = BeautifulSoup(website, 'html.parser')

soup_links = soup.find_all("a")
print(len(soup_links))

counter = 0

for link in soup_links:
    if link is None: # <---- Handle None value with continuing the loop
        continue

    if p.match(link.get("href", "")) is not None: # <--- Handle link element, if https is in href String.
        # If href is not existing. .get() returns "" and nothing is broken
        print("HTTPS found")
        print("%s" % (link.get("href"), link.string) )
        print("")
        counter = counter + 1

print(counter)


text:
Q: set mountain time zone ubuntu The next link helps to stablish the time zone to US/Pacific-New
ln -fs /usr/share/zoneinfo/US/Pacific-New /etc/localtime && dpkg-reconfigure -f noninteractive tzdata
What could be the value(s) for Denver/Mountain time?


text:
Q: Make iterator work with std::ranges functions I have the following code for a 2D-grid iterator.
#include <algorithm>
using std::ranges::count_if;
using std::ranges::for_each;

#include <iostream>
using std::endl;
using std::cout;

#include <iterator>
using std::iterator;
using std::forward_iterator_tag;

#include <memory>
using std::make_shared;
using std::shared_ptr;

#include <stdexcept>
using std::invalid_argument;

#include <vector>
using std::vector;

template <typename T>
class Grid2D;

template <typename T>
class Grid2DIterator : public iterator<forward_iterator_tag, T> {
private:
    Grid2D<T> & grid;
    size_t index;

    size_t getX() const
    {
        return index % grid.sizeX();
    }

    size_t getY() const
    {
        return index / grid.sizeX();
    }
public:
    using iterator = Grid2DIterator<T>;

    Grid2DIterator(Grid2D<T> * grid, size_t index)
        : grid(*grid), index(index)
    {}

    Grid2DIterator()
        : Grid2DIterator(nullptr, 0)
    {}

    T & operator*() {
        return grid(getX(), getY());
    }

    Grid2DIterator & operator++() {
        ++index;
        return *this;
    }

    bool operator==(Grid2DIterator const & other) const {
        return other.grid == grid && index == other.index;
    }

    bool operator!=(Grid2DIterator const & other) const {
        return !(*this == other);
    }
};

template <typename T>
class Grid2D {
private:
    vector<vector<T>> grid;
public:
    Grid2D(size_t x, size_t y, T const & init);
    Grid2D(vector<vector<T>> const & grid);

    T const & operator()(size_t x, size_t y) const;
    T & operator()(size_t x, size_t y);
    bool operator==(Grid2D<T> const & other) const;

    size_t sizeX() const;
    size_t sizeY() const;
    size_t size() const;

    Grid2DIterator<T> begin();
    Grid2DIterator<T> end();
};

template <typename T>
Grid2D<T>::Grid2D(size_t x, size_t y, T const & init)
    : grid(y, vector<T>(x, init))
{
    if (x < 1)
        throw invalid_argument("x must be >= 1");

    if (y < 1)
        throw invalid_argument("y must be >= 1");
}

template <typename T>
Grid2D<T>::Grid2D(vector<vector<T>> const & grid)
    : grid(grid)
{}

template <typename T>
T const & Grid2D<T>::operator()(size_t x, size_t y) const
{
    return grid.at(y).at(x);
}

template <typename T>
T & Grid2D<T>::operator()(size_t x, size_t y)
{
    return grid.at(y).at(x);
}

template <typename T>
bool Grid2D<T>::operator==(Grid2D<T> const & other) const
{
    return sizeX() == other.sizeX() && sizeY() == other.sizeY();
}

template <typename T>
size_t Grid2D<T>::sizeX() const
{
    return grid[0].size();
}

template <typename T>
size_t Grid2D<T>::sizeY() const
{
    return grid.size();
}

template <typename T>
size_t Grid2D<T>::size() const
{
    return sizeX() * sizeY();
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::begin()
{
    return Grid2DIterator(this, 0);
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::end()
{
    return Grid2DIterator(this, sizeX() * sizeY());
}

int main()
{
    vector<vector<int>> vec = {
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15},
        {16, 17, 18, 19, 20},
        {21, 22, 23, 24, 25}
    };
    Grid2D<int> grid(vec);
    for_each(grid, [] (auto const & item) { cout << item << endl; });
    auto cnt = count_if(grid, [] (auto const & i) { return i > 7; });
    cout << "Count: " << cnt << endl;
}

It works fine when using the standard iterator functions from algorithm using Grid2D::begin() and Grid2D::end().
However, my code does not work when I directly pass a Grid2D instance to the functions from std::ranges. The error message I get is very cryptic due to template spewing, but here it goes:
$ LANG=C g++ --std=c++20 grid.cpp -o grid
grid.cpp: In function 'int main()':
grid.cpp:167:13: error: no match for call to '(const std::ranges::__for_each_fn) (Grid2D<int>&, main()::<lambda(const auto:19&)>)'
  167 |     for_each(grid, [] (auto const & item) { cout << item << endl; });
      |     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:184:7: note: candidate: 'template<class _Iter, class _Sent, class _Proj, class _Fun>  requires (input_iterator<_Iter>) && (sentinel_for<_Sent, _Iter>) && (indirectly_unary_invocable<_Fun, std::projected<_Iter, _Proj> >) constexpr std::ranges::for_each_result<_Iter, _Fun> std::ranges::__for_each_fn::operator()(_Iter, _Sent, _Fun, _Proj) const'
  184 |       operator()(_Iter __first, _Sent __last, _Fun __f, _Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:184:7: note:   template argument deduction/substitution failed:
grid.cpp:167:13: note:   candidate expects 4 arguments, 2 provided
  167 |     for_each(grid, [] (auto const & item) { cout << item << endl; });
      |     ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note: candidate: 'template<class _Range, class _Proj, class _Fun>  requires (input_range<_Range>) && (indirectly_unary_invocable<_Fun, std::projected<decltype(std::__detail::__ranges_begin((declval<_Container&>)())), _Proj> >) constexpr std::ranges::for_each_result<std::ranges::borrowed_iterator_t<_Range>, _Fun> std::ranges::__for_each_fn::operator()(_Range&&, _Fun, _Proj) const'
  195 |       operator()(_Range&& __r, _Fun __f, _Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note:   template argument deduction/substitution failed:
/usr/include/c++/11.1.0/bits/ranges_algo.h:195:7: note: constraints not satisfied
In file included from /usr/include/c++/11.1.0/string_view:44,
                 from /usr/include/c++/11.1.0/bits/basic_string.h:48,
                 from /usr/include/c++/11.1.0/string:55,
                 from /usr/include/c++/11.1.0/bits/locale_classes.h:40,
                 from /usr/include/c++/11.1.0/bits/ios_base.h:41,
                 from /usr/include/c++/11.1.0/streambuf:41,
                 from /usr/include/c++/11.1.0/bits/streambuf_iterator.h:35,
                 from /usr/include/c++/11.1.0/iterator:66,
                 from /usr/include/c++/11.1.0/bits/ranges_algobase.h:36,
                 from /usr/include/c++/11.1.0/bits/ranges_algo.h:35,
                 from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_base.h: In substitution of 'template<class _Range, class _Proj, class _Fun>  requires (input_range<_Range>) && (indirectly_unary_invocable<_Fun, std::projected<decltype(std::__detail::__ranges_begin((declval<_Container&>)())), _Proj> >) constexpr std::ranges::for_each_result<std::ranges::borrowed_iterator_t<_Range>, _Fun> std::ranges::__for_each_fn::operator()(_Range&&, _Fun, _Proj) const [with _Range = Grid2D<int>&; _Proj = std::identity; _Fun = main()::<lambda(const auto:19&)>]':
grid.cpp:167:13:   required from here
/usr/include/c++/11.1.0/bits/ranges_base.h:579:13:   required for the satisfaction of 'range<_Tp>' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:639:13:   required for the satisfaction of 'input_range<_Range>' [with _Range = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:579:21:   in requirements with '_Tp& __t' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:581:22: note: the required expression 'std::ranges::__cust::begin(__t)' is invalid
  581 |         ranges::begin(__t);
      |         ~~~~~~~~~~~~~^~~~~
/usr/include/c++/11.1.0/bits/ranges_base.h:582:20: note: the required expression 'std::ranges::__cust::end(__t)' is invalid
  582 |         ranges::end(__t);
      |         ~~~~~~~~~~~^~~~~
cc1plus: note: set '-fconcepts-diagnostics-depth=' to at least 2 for more detail
grid.cpp:168:24: error: no match for call to '(const std::ranges::__count_if_fn) (Grid2D<int>&, main()::<lambda(const auto:20&)>)'
  168 |     auto cnt = count_if(grid, [] (auto const & i) { return i > 7; });
      |                ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:400:7: note: candidate: 'template<class _Iter, class _Sent, class _Proj, class _Pred>  requires (input_iterator<_Iter>) && (sentinel_for<_Sent, _Iter>) && (indirect_unary_predicate<_Pred, std::projected<_Iter, _Proj> >) constexpr std::iter_difference_t<_Iter> std::ranges::__count_if_fn::operator()(_Iter, _Sent, _Pred, _Proj) const'
  400 |       operator()(_Iter __first, _Sent __last,
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:400:7: note:   template argument deduction/substitution failed:
grid.cpp:168:24: note:   candidate expects 4 arguments, 2 provided
  168 |     auto cnt = count_if(grid, [] (auto const & i) { return i > 7; });
      |                ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note: candidate: 'template<class _Range, class _Proj, class _Pred>  requires (input_range<_Range>) && (indirect_unary_predicate<_Pred, std::projected<decltype(std::__detail::__ranges_begin((declval<_Container&>)())), _Proj> >) constexpr std::ranges::range_difference_t<_Range> std::ranges::__count_if_fn::operator()(_Range&&, _Pred, _Proj) const'
  415 |       operator()(_Range&& __r, _Pred __pred, _Proj __proj = {}) const
      |       ^~~~~~~~
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note:   template argument deduction/substitution failed:
/usr/include/c++/11.1.0/bits/ranges_algo.h:415:7: note: constraints not satisfied
In file included from /usr/include/c++/11.1.0/string_view:44,
                 from /usr/include/c++/11.1.0/bits/basic_string.h:48,
                 from /usr/include/c++/11.1.0/string:55,
                 from /usr/include/c++/11.1.0/bits/locale_classes.h:40,
                 from /usr/include/c++/11.1.0/bits/ios_base.h:41,
                 from /usr/include/c++/11.1.0/streambuf:41,
                 from /usr/include/c++/11.1.0/bits/streambuf_iterator.h:35,
                 from /usr/include/c++/11.1.0/iterator:66,
                 from /usr/include/c++/11.1.0/bits/ranges_algobase.h:36,
                 from /usr/include/c++/11.1.0/bits/ranges_algo.h:35,
                 from /usr/include/c++/11.1.0/algorithm:64,
                 from grid.cpp:1:
/usr/include/c++/11.1.0/bits/ranges_base.h: In substitution of 'template<class _Range, class _Proj, class _Pred>  requires (input_range<_Range>) && (indirect_unary_predicate<_Pred, std::projected<decltype(std::__detail::__ranges_begin((declval<_Container&>)())), _Proj> >) constexpr std::ranges::range_difference_t<_Range> std::ranges::__count_if_fn::operator()(_Range&&, _Pred, _Proj) const [with _Range = Grid2D<int>&; _Proj = std::identity; _Pred = main()::<lambda(const auto:20&)>]':
grid.cpp:168:24:   required from here
/usr/include/c++/11.1.0/bits/ranges_base.h:579:13:   required for the satisfaction of 'range<_Tp>' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:639:13:   required for the satisfaction of 'input_range<_Range>' [with _Range = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:579:21:   in requirements with '_Tp& __t' [with _Tp = Grid2D<int>&]
/usr/include/c++/11.1.0/bits/ranges_base.h:581:22: note: the required expression 'std::ranges::__cust::begin(__t)' is invalid
  581 |         ranges::begin(__t);
      |         ~~~~~~~~~~~~~^~~~~
/usr/include/c++/11.1.0/bits/ranges_base.h:582:20: note: the required expression 'std::ranges::__cust::end(__t)' is invalid
  582 |         ranges::end(__t);
      |         ~~~~~~~~~~~^~~~~

What do I have to implement / change to make my Grid2D template be usable with the std::ranges:: functions?
Solution as per the accepted answer
#include <algorithm>
using std::ranges::count_if;
using std::ranges::for_each;

#include <iostream>
using std::endl;
using std::cout;

#include <iterator>
using std::forward_iterator_tag;

#include <memory>
using std::make_shared;
using std::shared_ptr;

#include <stdexcept>
using std::invalid_argument;

#include <vector>
using std::vector;

template <typename T>
class Grid2D;

template <typename T>
class Grid2DIterator {
private:
    Grid2D<T> * grid;
    size_t index;

    size_t getX() const
    {
        return index % grid->sizeX();
    }

    size_t getY() const
    {
        return index / grid->sizeX();
    }
public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = T;
    using difference_type = T;
    using pointer = T*;
    using reference = T&;

    Grid2DIterator(Grid2D<T> * grid, size_t index)
        : grid(grid), index(index)
    {}

    Grid2DIterator()
        : Grid2DIterator(nullptr, 0)
    {}

    T & operator*() const {
        return (*grid)(getX(), getY());
    }

    Grid2DIterator & operator++() {
        ++index;
        return *this;
    }

    Grid2DIterator operator++(int) {
        auto copy(*this);
        operator++();
        return copy;
    }

    bool operator==(Grid2DIterator const & other) const {
        return other.grid == grid && index == other.index;
    }

    bool operator!=(Grid2DIterator const & other) const {
        return !(*this == other);
    }
};

template <typename T>
class Grid2D {
private:
    vector<vector<T>> grid;
public:
    Grid2D(size_t x, size_t y, T const & init);
    Grid2D(vector<vector<T>> const & grid);

    T const & operator()(size_t x, size_t y) const;
    T & operator()(size_t x, size_t y);
    bool operator==(Grid2D<T> const & other) const;

    size_t sizeX() const;
    size_t sizeY() const;
    size_t size() const;

    Grid2DIterator<T> begin();
    Grid2DIterator<T> end();
};

template <typename T>
Grid2D<T>::Grid2D(size_t x, size_t y, T const & init)
    : grid(y, vector<T>(x, init))
{
    if (x < 1)
        throw invalid_argument("x must be >= 1");

    if (y < 1)
        throw invalid_argument("y must be >= 1");
}

template <typename T>
Grid2D<T>::Grid2D(vector<vector<T>> const & grid)
    : grid(grid)
{}

template <typename T>
T const & Grid2D<T>::operator()(size_t x, size_t y) const
{
    return grid.at(y).at(x);
}

template <typename T>
T & Grid2D<T>::operator()(size_t x, size_t y)
{
    return grid.at(y).at(x);
}

template <typename T>
bool Grid2D<T>::operator==(Grid2D<T> const & other) const
{
    return sizeX() == other.sizeX() && sizeY() == other.sizeY();
}

template <typename T>
size_t Grid2D<T>::sizeX() const
{
    return grid[0].size();
}

template <typename T>
size_t Grid2D<T>::sizeY() const
{
    return grid.size();
}

template <typename T>
size_t Grid2D<T>::size() const
{
    return sizeX() * sizeY();
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::begin()
{
    return Grid2DIterator(this, 0);
}

template <typename T>
Grid2DIterator<T> Grid2D<T>::end()
{
    return Grid2DIterator(this, size());
}

int main()
{
    vector<vector<int>> vec = {
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15},
        {16, 17, 18, 19, 20},
        {21, 22, 23, 24, 25}
    };
    Grid2D<int> grid(vec);
    for_each(grid, [] (auto const & item) { cout << item << endl; });
    auto cnt = count_if(grid, [] (auto const & i) { return i > 7; });
    cout << "Count: " << cnt << endl;
}

A: First, the iterator needs to be move-assignable which your iterator is not due to the reference member. Instead of a reference use a pointer or std::reference_wrapper and this issue will disappear.
Then your iterator is missing a post-increment operator.
Also, operator* should be marked const.
I think this should fix all the explicit syntactic requirements of the concepts. I haven't checked whether the semantic requirements are fulfilled. If they are not, the program has undefined behavior.
Also, std::iterator is deprecated. If you compile with -Werror this is likely to make it fail. Instead add the few members it implicitly declares explicitly.


text:
Q: Is it possible to work with the Podio iOS app from other apps? I.e. open Podio and show a specific entry in an app We are in the process of creating an app that communicates with Podio.
During the work flow, we would like our app to open up the Podio iOS app and show a specific entry in one of the apps/tables of Podio.
Is it possible to work with the Podio iOS in such a way?
Can we trigger opening of Podio and navigation inside the app, from outside the app with APIs or similar?
Hope someone can help with any input.
Thanks in advance.

A: Podio iOS will open (or at least offer end-user option to open) links that starts with https://podio.com/*. This is exactly the way to go directly to Podio item from your email (for example), when you received mail notification. So, if you know your item URL, try opening it by system app, and iOS should let Podio app open it.
That won't work for any Podio url, but only for task, status, item urls.


text:
Q: Create function min() by manual calculations I'm completely new to coding and trying to figure out a task which tell us to:
Create 3 functions to compute the minimum, maximum and average temperature By using manual calculations. I've tried to find answer here and i got this which tells me the max number, but i dont really understand the code, can someone explain this code please?
A1 <- as.numeric(readline(prompt = "Write the temperature for Tokyo: "))
B2 <- as.numeric(readline(prompt = "Write the temperature for Johannesburg: "))
C3 <- as.numeric(readline(prompt = "Write the temperature for Stockholm: "))
D4 <- as.numeric(readline(prompt = "Write the temperature for Oslo: "))
E5 <- as.numeric(readline(prompt = "Write the temperature for Amsterdam: "))
F6 <- as.numeric(readline(prompt = "Write the temperature for Mexico city: "))
G7 <- as.numeric(readline(prompt = "Write the temperature for Hanoi: "))
H8 <- as.numeric(readline(prompt = "Write the temperature for Canberra: "))
I9 <- as.numeric(readline(prompt = "Write the temperature for Tbilisi: "))
J10 <- as.numeric(readline(prompt = "Write the temperature for New Delhi: "))

data = data.frame(A1,B2,C3,D4,E5,F6,G7,H8,I9,J10)
datamatrix <- as.matrix(data) #Converts data into a matrix

y=-Inf
z=0
for(i in datamatrix) {

  if(i>y){
    y=i

    if(y!=Inf){z=i}
  }
  else{y=Inf}
}
print(paste0("maximum number is: ", z))

A: A1 <- as.numeric(readline(prompt = "Write the temperature for Tokyo: "))

And the rest to J10 are variables where the value is defined by the user. If you run the above line in the console, it expects you to insert a number.
data = data.frame(A1,B2,C3,D4,E5,F6,G7,H8,I9,J10)
datamatrix <- as.matrix(data) #Converts data into a matrix

This prepares the data
y=-Inf
z=0
for(i in datamatrix) {

  if(i>y){
    y=i

    if(y!=Inf){z=i}
  }
  else{y=Inf}
}
print(paste0("maximum number is: ", z))

This part is a 'for loop' meaning it loops (Goes through) every value in datamatrix (A1 to J10) and assigns it to the i variable and does some calculation on it. The code below the for(i in datamatrix) between the { and } is a chunk of code that is run everytime i is assigned.
That code chunk checks if i is larger than y: if(i > y) which in this case is negative infinity. It assigns i to the y and z variables every time i is larger than y, but in case that y is bigger than i in any iteration, the z variable will not change again as y will be assigned to Inf and i cannot be larger than that.
What this means is that your function does NOT always find the maximum number. You can test this by assigning values to A1 to J10. Only in very specific circumstances will you get the maximum number.
z=-Inf
for(i in datamatrix) {
  if(z < i)
    z <- i
}
print(paste0("maximum number is: ", z))

This for-loop will find the maximum number. I do not claim it is optimal but it should be simpler to understand.
It will loop through the values and check if z is smaller than i. If yes, then i value is assigned to z. In case that a larger number comes along in the loop, it will reassign the i, but only if it is larger, meaning you end upp with the highest value.
Hope this helps.


text:
Q: Data view for A/B Tests? I'm trying to export our Job data to a data warehouse and it'd be helpful to know which of the jobs we're exporting are associated with AB tests. I can definitely see that Marketing Cloud has some other view to associate Jobs with AB tests, but I haven't seen that data exposed in the documentation. Is this something that I can pull via Query, or do I have to rely on manual exports? Do I need to just put all AB Tests in their own tracking folder and filter by Category?

A: Not an exact solution but you can try this:
1- Please go to Tracking - Sends and tick A/B Test in the grid.

2- Then you can click on that column to see all A/B tests and please move them in a folder.

3- Now you can use this SQL to get all the jobIDs in this folder/category:
SELECT j.JobID
FROM _Sent s
JOIN _Job j on s.JobID = j.JobID
WHERE j.Category = 'Folder Name'


text:
Q: Stub Active Record count with parameter I'm struggling to figure out how to stub the following:
def max_post_limit
    Post.on(date).count > some_limit
end

I'm trying to stub the Post... section, not the method.
So far I have tried the following and similar variations. All return either 0 or 1.
before do
    Post.stubs(:on).returns([])
    Post.stubs.(:on).with(date).returns([])
    Post.stubs.(:count).returns(some_limit)
end

Any advice would be much appreciated, thank you.

A: try:
allow(Post).to receive_message_chain(:on, :count) { 123 }


text:
Q: How to pass a functional component inside an event? So, I have a form and I want the user to display the values user fills in the fields as a JSON object at the end when the user clicks the submit button.
In Form.js,
state={
group:[
type-A{col1: "",
col2:""
}
]
}

handleSubmit(event) {
        event.preventDefault();
        <Credentials value={JSON.stringify(this.state)}/>
      }
change = e =>{
        this.setState({[e.target.name]: e.target.value})
    };
 render(){
        return(

            <form >

                    Column1:

                    <input type="text"
                    name="group1"
                    placeholder="Column1"
                    value={this.state.column1}
                    onChange={e=> this.change(e)}
//other fields
//input form fields
 <button onClick={this.handleSubmit}>Submit</button>

In Credentials.js,
    return (

{value}

    )
}

export default Credentials

The above code gives me an error, in handleSubmit() in second line (<Credentials value={JSON.stringify(this.state)}/>)
When the user clicks Submit button, I want to get a JSON object for the data entered in the input fields in the form and update it if the user updates any information in the fields.

A: Move the component to render method. and use conditional rendering.
state = {credentials: false}

handleSubmit = event => {
  event.preventDefault();

  this.setState({
    credentials: true // display Credentials  component
  });

};

render() {
  return (

      <button onClick={this.handleSubmit}>Submit</button>
      {this.state.credentials && (
        <Credentials value={JSON.stringify(this.state)} />
      )}

  );
}


text:
Q: Unusual Topology, interior and closure
On $\mathbb{R}^2$ let $\tau$ the collection of subsets defined as it follows $$A \in \tau \iff (x,y) \in A \implies (y,x) \in A$$
let $$B = \{(x,y) \in \mathbb{R}^2 : y = x\}, C = \{(x,y) \in \mathbb{R}^2 : y = -x\}$$
$D = \{(x,y)\in B\cup C : x \in [-2,3)\}$, find interior, closure and frontier of $D$.

I've noticed that I struggle very much in those kind of exercises, I'm wondering if exists a better approach.
My attempt: After verifying that $\tau$ is actually a topology on $\mathbb{R}^2$, I was thinking that the biggest open set contained in $D$ is the square in $\mathbb{R}^2$, $Q = \{(x,y) \in \mathbb{R}^2 : -2 ≤ x≤ 2, -2 ≤ y≤ 2\}$. For the closure I'm not completely sure but I was thinking of $D$ itself and so the frontier should be:
$$\{(x,y) \in B\cup C: x \in (2,3)\}$$
Am I wrong? Thank you all very much

A: First notice that the set $\{x\in B:x\in[-2,3)\}$ is open . And $\{x\in C: x\in [-2,2]\}$ is open. But if we take a point $(x_{0},y_{0})\in C$ such that $2<x_{0}<3$ . Note that any open set containing $(x_{0},-x_{0})$ must contain $(-x_{0},x_{0})$ and hence cannot be contained in $D$ and hence these points are not interior points.An open set containing such $(x_{0},-x_{0})$  is $\{(x_{0},-x_{0}),(-x_{0},x_{0})\}$ which does not intersect $D\setminus\{(x_{0},-x_{0})\}$ and hence these points are isolated points.
Note that for any point not in $D$ say $(x,y)$ we have the set $\{(y,x),(x,y)\}$ is an open set such that this set is disjoint from $D$ . Hence they cannot be part of the closure of $D$.
Thus $\text{int}(D)=\{x\in B:x\in[-2,3)\}\cup\{x\in C:x\in[-2,2]\}$ .
We have shown that any point outside $D$ cannot be a limit point and hence $\text{cl}(D)=D$ .
The frontier then just consists of the isolated points which are $\{x\in C:x\in (2,3)\}$ .
Note that this also matches with the formula that $\partial(D)=\text{cl}(D)\setminus\text{int}(D)$ . So if you manage to calculate interior and closure you can get the frontier for free.


text:
Q: Subscripted Value is not an array I am trying to assign the first 30 temperatures to the June array, the next 30 to the July array, and the last 30 to the August array. And for some reason, it is telling me that fin >> temp[June]; is "Subscripted Value is not an array." I know I am missing something but I'm stuck nonetheless. Thanks in advance for your help.
#include <iostream>
#include <fstream>

int main() {
    using namespace std;

    string file_name;
    int June[30];
    int July[30];
    int August[30];
    int temp;
    string date;
    const int days = 30;
    string firstline;

    cout << "please enter the file name" << endl;
    cin >> file_name;

    ifstream fin;
    fin.open(file_name);

    if (fin.fail())
    {
        cout << "Failed to open " << file_name << endl;
        exit(1);
    }

    getline(fin, firstline);
    for (int i = 0; i < days; i++)
        fin >> date;
        fin >> temp[June];
        for (int j = 0; j < days; j++)
            fin >> date;
            fin >> temp[July];
            for (int k = 0; k < days; k++)
                fin >> date;
                fin >> temp[August];

    fin.close();
    return 0;
}

A: I cannot reproduce your "Subscripted Value is not an array" error.
Anyway, I see some problems in your code that can be connected (or not).
(1) as observed by kkk, you use temp
fin >> temp[June];

uninitialized

(2) looking your code, I suspect your a Python programmer because your for are indented suggesting that is the indentation that determine the scope of the cycle. I mean... when you write
        for (int k = 0; k < days; k++)
            fin >> date;
            fin >> temp[August];

I suspect that you think that the cycle from zero to days-1 is executed over both fin >> date and fin >> temp[August].
Wrong.
In C/C++ the body of a for is the following statement (only fin >> date) and if you want more statement in the body, you have to include they between { }.
So I suspect that your intention was
for (int i = 0; i < days; i++)
 {
    fin >> date;
    fin >> temp[June];
 }

for (int j = 0; j < days; j++)
 {
    fin >> date;
    fin >> temp[July];
 }

for (int k = 0; k < days; k++)
 {
    fin >> date;
    fin >> temp[August];
 }

(3) the operator a[b], in C (and in C++ for pointers and old C+style arrays), is syntactic sugar for (is defined as) *(a+b).
So, if June is an array, you can write indifferently June[0] or 0[June]. But usually is used the form June[0] and the form 0[June] is an elegant (IMHO) form of obfuscation coding. A dangerous form, because when a class define an operator[], the equivalence is lost and only the first form ins available.
So your
fin >> temp[June];

is technically correct (as far I know and excluding the fact that temp is uninitialized), but I suggest you to write
fin >> June[temp];

or presumably (as observed by bob__)
fin >> June[i]


text:
Q: ASP - Pikaday - Masterpage Im using the pikaday plugin (https://github.com/dbushell/Pikaday). I want to disable all days except Mondays. My current code just block Weekends. As per the doco I should use disableDayFn but I'm unsure of how to use this in my code (below).
<script type="text/javascript">
        $(document).ready(function () {
            $("#<%=TextBox2.ClientID %>").pikaday({ format: 'DD/MM/YYYY', disableWeekends: true, firstDay: 1 });
        });
    </script>

     <asp:TextBox ID="TextBox1" runat="server" </asp:TextBox>

others used the below code but I'm not sure how to make it work with my code
var picker = new Pikaday({
    disableDayFn: function(date){
        // Disable Monday and Tuesday
        return (date.getDay() === 1 || date.getDay() === 2);
    },
    field: document.getElementById('datepicker') })

A: Your example for disabling Monday and Tuesday is correct. To make it your, I suggest you should use the original declaration of Pikaday:
$(document).ready(function (){
    var picker = new Pikaday({
        field: $("#<%=TextBox2.ClientID %>"),
        format: 'DD/MM/YYYY',
        disableWeekends: true,
        firstDay: 1,
        disableDayFn: function(date){
        // Disable Monday and Tuesday
        return (date.getDay() === 1 || date.getDay() === 2);
        }
    });
});

If you still want to use Pikaday plugin, like your original code, you can see below:
$("#<%=TextBox2.ClientID %>").pikaday({
  format: 'DD/MM/YYYY',
  disableWeekends: true,
  firstDay: 1,
  disableDayFn: function(date){
        // Disable Monday and Tuesday
        return (date.getDay() === 1 || date.getDay() === 2);
    }
});


text:
Q: Issue with object within an object in react-native: Undefined is not an object I have an object that I read into state. When I tried to extract a value from within that object in render I get an error saying "undefined is not an object".
So the object looks like this: const currentGrid = {size: {cols: "15", rows: "15"}}
I assign it to state with this.setState({ currentGrid: currentGrid }) in componentWillMount.
In render I do this:
render() {
    return (
      <Container>
        <Content>
          <List>
            <ListItem>
              <Body>
                <Text>{this.state.currentGrid.size.cols}</Text>
              </Body>
            </ListItem>
          </List>
        </Content>
</Container>
);
}

When I load the component I get "TypeError: undefined is not an object (evaluating 'this.state.currentGrid.size.cols')
I know that the object is set in state. If I leave off "cols" the error is:
Invariant: Objects are not valid as React child (found: object with keys {cols, rows}). If you meant to render a collection of children use an Array instead.
Sorry if this is a common error, but I can't find how to do it properly unless I have to convert this embedded object into an array, which doesn't seem right.

A: One possibility here is the first time the app runs currentGrid is undefined. In your render check if it exist before rendering text
render() {
 return (
  <Container>
    <Content>
      <List>
        <ListItem>
          <Body>
            {this.state.currentGrid.size && (
              <Text>{this.state.currentGrid.size.cols}</Text>
            )}
          </Body>
        </ListItem>
      </List>
    </Content>
  </Container>
 );
}


text:
Q: Как отловить клик вне модального окна? Есть такое приложение:
new Vue({
    el: '#app',
    data: {
      formIsActive: false
    },
    ..........
    watch: {
        formIsActive: function (val) {
            if (val) {
                document.addEventListener('click', event => {
                        function ()
                        if (!document.getElementById('modal-content').contains(event.target)) {
                            console.log('outside click');
                            this.formIsActive = false
                        }
                });
            }
        }
    }

По идее я хочу отловить нажатие вне элемента #modalcontent и как-бы работает, но до пояления модального окна.
То-есть события такие:

*

*клик по кнопке переход

*переход formIsActive в состояние true

*срабатывание вотчера

*как следствие отлов события клика вне элемента и еще до
появления модального окна переход formIsActive в false

Так вот вопрос - как отложить addEventListener до открытия модального окна?
fiddle: https://jsfiddle.net/feo2b93x/


text:
Q: Laravel RESTful controller to include subdirectory for 'show' function I am building my Laravel app through the use of RESTful controllers.
Currently, an 'agent' can login, to view all of their 'notifications'.
The structure is:

/agents

When they chose a notification to view, instead of:

/agents/$id

I want it to be:

/agents/notifications/$id

Solely because it follows logically. If it was '/agents/$id' I would expect to see the agent's profile, for example.
Is there a way of including a subdirectory into the 'show' function? Or do I need to create a notification controller that somehow sites within the agent directory.
My route is:

Route::controller('agents', 'AgentsController');

With the show function:
public function show($id)
{
    $alerts = Alert::where('id', $id)->first();
    $this->layout->content = View::make('agents.notification.show', array('alerts' => $alerts));
}

Any help would be hugely appreciated.

A: if you want to use http://laravel.com/docs/controllers#restful-controllers then your controller's method should be named getShow().
Apart from that you can achieve what you want by defining another route like this:
Route::get('agents/notifications/{id}', 'AgentsController@getShow');


text:
Q: Constraining type parameters on case classes and traits I'm a bit confused about how to constrain type parameters so that they will only accept types that have implemented a particular typeclass. Here's some rather contrived sample code:
// I want to tag my favourite types of number with this trait
trait MyFavouriteTypesOfNumber[A]
// implicits necessary because I cannot directly extend Int or Double
implicit def iLikeInts(i: Int): MyFavouriteTypesOfNumber[Int] = new MyFavouriteTypesOfNumber[Int] {}
implicit def iAlsoLikeFloats(f: Float): MyFavouriteTypesOfNumber[Float] = new MyFavouriteTypesOfNumber[Float] {}

// Is the type constraint here correct?
// I am trying to say 'only accept types that implement MyFavouriteTypesOfNumber'
trait PresentMyFavourite[Num <: MyFavouriteTypesOfNumber[Num]] {
  val originalNum: Num
  def packageAsString: String = s"***... ${originalNum} ...***"
  def printPackaged: Unit = println(packageAsString)
}

// again, the case class should only accept types that have implemented MyFavouriteTypesOfNumber
case class ILikeThisNumberAsWellAsItsType[Num: MyFavouriteTypesOfNumber] (
  val originalNum: Num
) extends PresentMyFavourite[Num]

// Would expect these next two lines to work
val three = ILikeThisNumberAsWellAsItsType[Int](3: Int)
three.printPackaged
// But not this one, because I don't like Doubles
val four = ILikeThisNumberAsWellAsItsType[Double](3.0: Double)

I wrote this expecting it to raise an error on the final line val four = ..., but in fact it is giving me a novel error (beyond the one I expected) - could not find implicit parameter for evidence value of type MyFavouriteTypesOfNumber[Int].
If anyone could a) let me know if my original code is correct for what I'm trying to achieve, or b) throw some light on this unexpected error message, then I'd greatly appreciate it.

A: Use val for the type class implementations.
trait MyFavouriteTypesOfNumber[A]
implicit val iLikeInts: MyFavouriteTypesOfNumber[Int] =
  new MyFavouriteTypesOfNumber[Int] {}
implicit val iAlsoLikeFloats: MyFavouriteTypesOfNumber[Float] =
  new MyFavouriteTypesOfNumber[Float] {}

Change PresentMyFavourite into an abstract class so that we can use context bounds.
abstract class PresentMyFavourite[Num : MyFavouriteTypesOfNumber] {
  val originalNum: Num
  def packageAsString: String = s"***... ${originalNum} ...***"
  def printPackaged(): Unit = println(packageAsString)
}

Now the rest should work except for the last line, val four ..., which, as expected, won't compile.
It should be noted that you're going to have to implement every math operation that you want to use for each of your "FavoriteTypesOfNumber". At this point the compiler knows that the type is restricted to Int or Float but, since it could be either, it doesn't know how to add 2 of them together unless you provide the code.


text:
Q: RStan: Use matrix in ordered_logistic() I would like to use ordered_logistic() function in RStan.
Firstly, here is the data (sample):
   gender   age partyID treatment_rand treatment_bias y_randT y_biasT
    <dbl> <dbl>   <dbl>          <dbl>          <dbl>   <dbl>   <dbl>
1       0    21       1              0              0       1       4
2       1    21       7              1              1       3       2
3       0    67       7              0              0       4       4
4       0    78       1              0              0       2       4
5       0    35       8              0              1       4       2

I use the subset of data:
X <- cbind(1, sample[, c("age", "partyID", "gender")])
choice_num <- 5
data_randT <- list(N=nrow(sample), D=ncol(X), t=sample$treatment_rand, X=X, y=sample$y_randT, K=choice_num)

My Stan code is:
data{
    int<lower=2> K;
    int<lower=0> N;
    int<lower=1> D;
    int<lower=1, upper=K> y[N];
    real<lower=0, upper=1> t[N];
    matrix[N,D] X;
}

parameters{
    vector[D] betaX;
    real betaT;
    ordered[K-1] c;
}

model{
    for(n in 1:N)
        y[n] ~ ordered_logistic(betaT*t[n] + X[n]*betaX, c);
}

If I run this code, I got the following error:
> fit_rand <- stan(model_code=stan_OrderedLogit, data=data_randT, seed=seed)
Error in new_CppObject_xp(fields$.module, fields$.pointer, ...) :
  variable does not exist; processing stage=data initialization; variable name=X; base type=matrix_d
In addition: Warning messages:
1: In is.na(x) : is.na() applied to non-(list or vector) of type 'NULL'
2: In FUN(X[[i]], ...) : data with name X is not numeric and not used
failed to create the sampler; sampling not done

What is wrong with the code?

A: I believe it will work if you make X a matrix in R, rather than a data.frame, as in

X <- as.matrix(cbind(1, sample[, c("age", "partyID", "gender")]))

However, I would think you you would first want to expand partyID into a set of dummy variables (excluding a reference category).


text:
Q: .NET Core : NUnit won't execute SetUp NUnit won't execute the SetUp method unless i call it manually. Additionally when i add SetUp() to my test it seems i also have an issue with the test server because i get "StatusCode: 204, ReasonPhrase: 'No Content'" in the response, but the controller works fine if i execute it. I'm using .NET Core 1.1 and NUnit 3.6.1.
Solution is here https://github.com/Narcil/NUnitMCV
My test class:
[TestFixture]
public class FrontendControllerTests : AbstractFrontendTestFixtures
{
    [Test]
    public async Task FrontendAppSettingsTest()
    {
        var response = await _client.GetAsync("/api/values");
        var value = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());

        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        Assert.IsTrue(value.Equals("Some FrontendValue"));
    }

}

My abstract class
public abstract class AbstractFrontendTestFixtures
{
    protected HttpClient _client;
    protected TestServer _server;

    [SetUp]
    protected void SetUp()
    {
        _server = new TestServer(new WebHostBuilder()
            .UseStartup<Frontend.Startup>()
            .UseEnvironment("Testing"));
        _client = _server.CreateClient();
    }

    [TearDown]
    protected void TearDown()
    {
        _client.Dispose();
        _server.Dispose();
    }
}

A: Your SetUp method should be public. If you would like to have additional setup logic in derived classes, just mark the method as virtual in additional.


text:
Q: Svg List Style animation I have a couple of list styles that I would like to animate when the svg's LI is hovered over. The issue I am getting is that the first LI triggers all list Items to animate at the same time. I have tried using just css, and I have also tried using jquery, but I just can figure it out for the life of me. Thanks! You can check my code here

                    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                         viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

                    <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
                    <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
                    <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
                    <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>
                    <g>
                    </svg>
                    Categories

                        <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                             viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

                        <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
                        <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
                        <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
                        <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>
                        <g>
                        </svg>
                        Top Blogs

                        <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                             viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

                        <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
                        <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
                        <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
                        <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>
                        <g>
                        </svg>
                        Gilded

                        <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
                             viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

                        <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
                        <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
                        <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
                        <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>
                        <g>
                        </svg>
                        Controversial

A: This is what i can come up with with you explanation.
I add a listener to the hover event and the mouseLeave event.
With this you can target each li

$("li a").each(function(){
  $(this).hover(function(){
    $(this).css('color','red');
  })

  $(this).mouseleave(function(){
    $(this).css('color','white');
  })
})

$(".hamburger").on("click", function(){
 $(".hamburger").toggleClass("is-active");
 if($(".hamburger").hasClass("is-active")){
  $("#main").css("right", "320px");
 } else {
  $("#main").css("right", "20px");
 }
 $(".side-nav").toggleClass("hidden");
 $("body").toggleClass("menu-active");
});
html,body{
  padding: 0;
  margin: 0;
  height: 10000px;
  background-color: pink;
  box-sizing: border-box;
}

button:focus {outline:0;}

a{
  color: #fff;
}

a:hover, a:active, a:visited, a:focus{
  color: #fff;
  text-decoration: none !important;
}

svg{
  position: relative;
  top: 6px;
  left: -12px;
  height: 15px;
  width: 15px;
  float: left;
}

.menu-active{
  padding-right: 300px;
}

.side-nav{
  position: fixed;
  background-color: gray;
  width: 300px;
  height: 100%;
  z-index: 1;
  right: 0;
}

.open-menu-side{
  position: relative;
  display: block;
  height: 80px;
  width: 100%;
  text-align: center;
  float: right;
}

.side-nav-ul{
  position: relative;
  width: 100%;
  height: 100%;
  margin-top: 40px;
  list-style: none;
  font-size: 20px;
  color: #fff;
}

hr{
  margin-right: 40px;
}

.blogs-ul{
  list-style: none;
  margin-top: 10px;
  height: 100px;
}

.blog{
  height: 150px;
}

.block{
  margin: 20px 0;
  color: #fff;
}

header{
  height: 80px;
  background-color: #fff;
}

.hidden{
  position: absolute;
  right: -300px;
}

#main{
  position: fixed;
  right: 10px;
  top: 10px;
}

.hamburger {
  padding: 15px 15px;
  height: 100%;
  display: inline-block;
  cursor: pointer;
  transition-property: opacity, filter;
  transition-duration: 0.15s;
  transition-timing-function: linear;
  font: inherit;
  color: inherit;
  text-transform: none;
  background-color: transparent;
  border: 0;
  margin: 0;
  overflow: visible; }
  .hamburger:hover {
    opacity: 0.7; }

.hamburger-box {
  width: 40px;
  height: 24px;
  display: inline-block;
  position: relative; }

.hamburger-inner {
  display: block;
  top: 50%;
  margin-top: -2px; }
  .hamburger-inner, .hamburger-inner::before, .hamburger-inner::after {
    width: 40px;
    height: 4px;
    background-color: #000;
    border-radius: 4px;
    position: absolute;
    transition-property: transform;
    transition-duration: 0.15s;
    transition-timing-function: ease; }
  .hamburger-inner::before, .hamburger-inner::after {
    content: "";
    display: block; }
  .hamburger-inner::before {
    top: -10px; }
  .hamburger-inner::after {
    bottom: -10px; }

.hamburger--squeeze .hamburger-inner {
  transition-duration: 0.075s;
  transition-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19); }
  .hamburger--squeeze .hamburger-inner::before {
    transition: top 0.075s 0.12s ease, opacity 0.075s ease; }
  .hamburger--squeeze .hamburger-inner::after {
    transition: bottom 0.075s 0.12s ease, transform 0.075s cubic-bezier(0.55, 0.055, 0.675, 0.19); }

.hamburger--squeeze.is-active .hamburger-inner {
  transform: rotate(45deg);
  transition-delay: 0.12s;
  transition-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1); }
  .hamburger--squeeze.is-active .hamburger-inner::before {
    top: 0;
    opacity: 0;
    transition: top 0.075s ease, opacity 0.075s 0.12s ease; }
  .hamburger--squeeze.is-active .hamburger-inner::after {
    bottom: 0;
    transform: rotate(-90deg);
    transition: bottom 0.075s ease, transform 0.075s 0.12s cubic-bezier(0.215, 0.61, 0.355, 1); }

Home

    Blogs

      <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
        viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

      <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
      <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
      <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
      <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>

      </svg>
      Categories

       <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

       <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
       <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
       <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
       <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>

       </svg>
       Top Blogs

       <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

       <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
       <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
       <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
       <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>

       </svg>
       Gilded

       <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         viewBox="0 0 61.7 61.4" style="enable-background:new 0 0 61.7 61.4;" xml:space="preserve">

       <rect x="20.7" y="5.2" transform="matrix(0.7071 0.7071 -0.7071 0.7071 19.7538 -17.2354)" class="st0 r1" width="20" height="20"/>
       <rect x="36.1" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 35.1571 -23.6156)" class="st0 r2" width="20" height="20"/>
       <rect x="20.7" y="36" transform="matrix(0.7071 0.7071 -0.7071 0.7071 41.5374 -8.2123)" class="st0 r3" width="20" height="20"/>
       <rect x="5.3" y="20.6" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.1341 -1.832)" class="st0 r4" width="20" height="20"/>

       </svg>
       Controversial

Following

Profile

Settings

Logout

    <button class="hamburger hamburger--squeeze" type="button">

    </button>


text:
Q: How to get the fingerprint of a public key? In PHP, I have a public key (already as an OpenSSL resource). I'd like to calculate that public keys fingerprint (SHA1 or other hash).
How do I do this?
PHP version is 7.2 or older.
EDIT: This is not a duplicate of the other question, because that question is about doing this for an SSH key with SSH (and related) commands. I want to do the same thing using PHP and the PHP-extension openssl.

A: I've found the solution myself. The basic idea:

*

*Decode the base64 encoded part of the key in PEM format (after removing spaces from it)

*Hash the resulting binary data.

In code (PHP):
function getPublicKeyFingerprint(string $pemEncodedKey, string $hashAlgorithm = 'sha1')
{
    $keyWithoutPemWrapper = \preg_replace(
        '/^-----BEGIN (?:[A-Z]+ )?PUBLIC KEY-----([A-Za-z0-9\\/\\+\\s=]+)-----END (?:[A-Z]+ )?PUBLIC KEY-----$/ms',
        '\\1',
        $pemEncodedKey
    );
    $keyDataWithoutSpaces = \preg_replace('/\\s+/', '', $keyWithoutPemWrapper);

    $binaryKey = \base64_decode($keyDataWithoutSpaces);

    return \hash($hashAlgorithm, $binaryKey);
}

A: if you need a hash php has multiple hashing functions available:
sha1() - https://php.net/manual/en/function.sha1.php
md5() - https://www.php.net/manual/en/function.md5.php
or use hash() if you need a more specific algorithm - see the docs


text:
Q: jQuery - and operators I have the following code
jQuery(".opsection input").live('change', function(){

What i want to also do is add an 'or' operator so that it runs on a 'change' function also when someone 'clicks' a text field
Any help would be grand.

A: you do it like this
jQuery(".opsection input").live('change click', function(){

This will run the function on either a change or click event.

A: Try this:
jQuery(".opsection input").live('change click', function(){

Check this link for more information: http://api.jquery.com/live/


text:
Q: P.d.f of product of 2 i.i.d r.v We have two r.v.s, $X$ and $Y$, both have density $3x^2$ where $x$ in range $(0,1)$. we want the density function of $Z=XY$.
By the product distribution equation and the fact that $X,Y>0$ we have:
$$f_{Z}(z)=\int_0^13x^2\cdot 3\left(\frac{z}{x}\right)^2\frac{1}{x}dx$$
But wolfram alpha told me that thing does not converge! I think I did everything right and I haven't missed anything,  I ignored the absolute value on $\frac{1}{|x|}$ because $x$ is strictly larger than $0$. I don't know what's happening, please help me out! thank you!

A: You have missed the domain of your probability density functions.
I found this formula for evaluating the product distribution from Wikipedia:
$$f_{Z}(z)=\int _{{-\infty }}^{{\infty }}f_{X}\left(x\right)f_{Y}\left(z/x\right){\frac  {1}{|x|}}\,dx.$$
Therefore for your case, we have
$$
\begin{align}
f_{Z}(z) &=\int _{{-\infty }}^{{\infty }} 3 x^2\cdot \mathbb{1}_{x \in (0, 1)}\cdot 3 \left(\frac{z}{x}\right)^2 \cdot \mathbb{1}_{z/x \in (0, 1)} \cdot {\frac  {1}{x}}\,dx\\
&=  \begin{cases}
\displaystyle \int _{{z }}^{{1 }} 3 x^2\cdot 3 \left(\frac{z}{x}\right)^2 \cdot {\frac  {1}{x}}\,dx & \text{if $z < 1$}\\
\displaystyle 0& \text{if $z \geq 1$}
\end{cases}\\
&= 9z^2 \ln \frac1z \cdot \mathbb{1}_{z \in (0, 1)},
\end{align}
$$
where $\mathbb{1}_{A}$ is the indicator function with the definition
$$\mathbb{1}_{A} = \begin{cases}1 &\text{if $A$ is true}\\0 &\text{otherwise}.\end{cases}$$


text:
Q: Como usar 2 idiomas en reconocimiento de voz en Python? Estoy haciendo un programa para detectar el idioma que hablas mediante un micrófono en python, pero quisiera usar dos idiomas, por ejemplo el español y francés.
Mi codigo:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
    print("Comienza a hablar....")
    audio = r.listen(source)
    try:
        text = r.recognize_google(audio,language="es-ES, fr-FR")
        print("Palabra: {}".format(text))
    except:
        print("No se reconoció la palabra")

En el código coloque las iniciales de es-ES y fr-FR, pero no funciona cuando intento hablar en francés, es posible tener dos lenguajes?

A: Aparentemente en una consulta no puedes preguntar por dos idiomas. La opción es realizar dos consultas, utilizar show_all=True para ver el porcentaje de acierto de la mejor alternativa y compararlas para determinar el idioma.
import speech_recognition as sr

def transcripcion(audio,lang,prob):
    try:
        text = r.recognize_google(audio,language=lang,show_all=True)
        if len(text)!=0:
            print(f"Palabra: {text['alternative'][0]['transcript']}")
            prob[lang]=text['alternative'][0]['confidence']
        else:
            print(f"No se reconoció la palabra en {lang}")
    except:
        print(f"Ocurrió un problema usando el idioma {lang}")

r = sr.Recognizer()
langs=["es-ES","fr-FR"]
probabilidad={}

with sr.Microphone() as source:
    print("Comienza a hablar....")
    audio = r.listen(source)
    for lang in langs:
        probabilidad[lang]=0
        transcripcion(audio,lang,probabilidad)

ordenados={k: v for k, v in sorted(probabilidad.items(), key=lambda item: item[1], reverse=True)}
for leng in ordenados:
    print(f"La probabilidad de que sea {leng} es de {ordenados[leng]}")


text:
Q: Can't enable my smart home test application in googe home I have a problem with unlocking the test smart home application on the account mobilus.assistant@gmail.com. Id of my project is: mobilus-d9412. After correct linking account with the oAuth2 service in the google home application, the message appears "could not update the setting. Check internet connection". I use the smart home provider nodejs service to handle the action.
From the account piotrmackus@gmail.com through which tests were carried out there is no such problem - it is possible to correctly unlock the application and get the list of devices in the google home application. The project I used for testing is: zxxz-71eee.
I would like the application to work from the mobilus.assistant account from the mobilus-d9412 project, what is the problem? I will add that I use the same android device with google home for both cases, same WiFi network and Google Home mini device.

A: Apparently you have used the Account Linking from Dialogflow / Assistant Actions to build your Smart Home project. This kind of flow is not supported anymore, and you should create a new Smart Home project similar to starter codelab, and implement account linking according to the documentation. Once you start testing your project, go to Actions on Google Console and enable testing (which is not available for Dialgflow projects).


text:
Q: How to edit and update json data via html input fields?
*

*I am trying to update data via html input fields.
       I have 4 input fields where
       1st one is id,
       2nd one text and
       3rd and 4th blank input fields.
3rd and 4th input should update data.

Below is my json data and script
[
    {"id": 1, "testdata": "Exxon Mobil", "toBe_1": " ", "toBe_2": " " },

    {"id": 2, "testdata": "Wal-Mart Stores", "toBe_1": " ", "toBe_2": " "},

    {"id": 3, "testdata": "Royal Dutch Shell", "toBe_1": " ", "toBe_2": " "},

    {"id": 4, "testdata": "BP", "toBe_1": " ", "toBe_2": " " },

    {"id": 5, "testdata": "General Motors", "toBe_1": " ", "toBe_2": " " }
]

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
     var data = JSON.parse(xmlhttp.responseText);
        var dataArray = [];
        data.forEach(function (d) {
          dataArray.push(d);
        });
        console.log(dataArray);
      }
    };
    xmlhttp.open("GET", "data/dummyData.json", true);
    xmlhttp.send();

    2


text:
Q: How to create a custom JSON layout from MySQL in PHP I have a MySQL query in PHP that pulls back two columns of results
Column One is Label
Column Two is Value
I have read http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP but im struggling to understand how I can do the following JSON in PHP from MySQL
[
  {
    key: "Cumulative Return",
    values: [
      {
        "label": "One",
        "value" : 29.765957771107
      } ,
      {
        "label": "Two",
        "value" : 0
      } ,
      {
        "label": "Three",
        "value" : 32.807804682612
      } ,
      {
        "label": "Four",
        "value" : 196.45946739256
      } ,
      {
        "label": "Five",
        "value" : 0.19434030906893
      } ,
      {
        "label": "Six",
        "value" : 98.079782601442
      } ,
      {
        "label": "Seven",
        "value" : 13.925743130903
      } ,
      {
        "label": "Eight",
        "value" : 5.1387322875705
      }
    ]
  }
]

I can manually write a loop to output the raw text to form a JSON like above but I really want to use json_encode
<?php
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);

    $query = "select label, value from table";

    $stmt = $dbh->prepare($query);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($result)) {
        echo '[
        {
          key: "Cumulative Return",
          values: [';

        for ($row = 0; $row < count($result); $row++) {
            echo "{";
            echo '"label": "' . $result[$row]['Label'] . '",';
            echo '"Value": ' . $result[$row]['Value'];
            echo "},";
            echo '       ]
      }
    ]';
        }

    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

?>

Can this be done? if so how?

A: Use json_encode()
$jsonArr = array( 'key' => 'Cumulative Return' , 'values' => array() );

foreach ($result as $res)
{
   $jsonArr['values'][] = array('label'=>$res['Label'],'value'=>$res['value']);

}

echo json_encode($jsonArr);

A: Try this:
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);

    $query = "select label, value from table";

    $stmt = $dbh->prepare($query);
    $stmt->execute();

    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $values = array();

    for($row = 0; $row < count($result); $row++)
    {
        $values[] = array('label' => $result[$row]['Label'], 'value' => $result[$row]['Value']);
    }

    $to_encode = array(
                        array('key' => 'Cumulative Return',
                              'values' => $values;
                              )
                        );
    echo json_encode($to_encode);

} catch (PDOException $e) {
    echo $e->getMessage();
}

A: You just need to create the array in the way you want it to be converted to json:
$encode = array(
    'key' => 'Cumulative Return',
    'values' => $result->fetchAll(PDO::FETCH_ASSOC)
);
echo json_encode($encode);

This should be what you are asking for.

A: That's the usefulness of JSON - that you don't need to bother to encode it manually.
$json = array();
$results = array();
$json['key'] = 'Cumulative return';

foreach ($row as $entry) {
    $results['label'] = $entry['Label'];
    $results['value'] = $entry['Value'];
    $json['value'][] = $results;
}

echo json_encode($json);

And that's it. Enjoy!

A: Iam using code igniter
this is how i created custom json from the values from the data base hope it helps

function getData() {

  $query = $this -> db -> get('gcm_users');

  $result_array=array();

  if ($query -> num_rows() > 0) {

   $results=$query->result();

   foreach ( $results as $row) {

    $data=array();

    $data['name']=$row->name;
    $data['email']=$row->email;

    array_push($result_array,$data) ;
   }

   return json_encode($result_array);

  } else {

   echo "something went wrong";

  }
 }

this my function for retriving data from db since im using a frame work such as Code igniter i dont have to worry about my other sql operation hope you can extract what you need from this code..
output is like this

[{"name":"allu","email":"allu@gmail.com"},{"name":"ameeen","email":"cdfdfd@gmail.com"}]

A: I build a simple function (I prefer to use it then json_encode - because I have full control of the fetched data):
    public function mysqlToJoson($mysqlarray)
    {
        $json_string = "[";

        while ($array = $mysqlarray->fetch()) {
            $i = 1;
            if ($json_string != "["){$json_string .= ",";}
            foreach ($array as $key => $value) {
                if ($i == 1) {
                    $json_string .= '{"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
                } else $json_string .= ',"' . $key . '":' . '"' . htmlentities($value,ENT_QUOTES, 'UTF-8') . '"';
                $i++;
            }
            $json_string .= '}';
        }
        $json_string .= ']';
        return $json_string;
    }


text:
Q: Save the session from a working thread when closing I have a multi-thread VB.net program. and I want to loop through each thread and get the session from each one.
here's the code that creates the threads.
Sub Run():
    Timer1.Enabled = True
    AddHandler LoginTimer.Elapsed, AddressOf doWork
    LoginTimer.Interval = 500
    LoginTimer.Enabled = True
End Sub

and here's the doWork() sub:
sub doWork()
    For id = 0 to val(textbox1.text) ' get how many thread should we run
                Dim th As New Thread(AddressOf Work) ' what the threads should do.
                th.IsBackground = True
                th.Start()
    Next id

Now every time I close the program, the threads became aborted and I lost all the stuff that those threads have been working on. So, I want to save the sessions. and the Next time when I run I'd just 'resume' it by loading back the sessions. Something like:
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    Dim sessions As New List(Of String)
    For Each thread In xxxx ' here where should I do a loop through the running threads
       sessions.Add(thread.session) ' get the session from the thread
    Next thread
End Sub

Thanks in advance
EDIT: I've managed to fix my problem by creating a "Public Shared ShoulIupadteNow as Boolean", since the threads i have are running in continuous loop they all the time check if the Boolean set to true. and when it is ( i usually click on a button that set it to true on my form ) it starts updating by having a public shared lstsessions as new hashset(of string) this way I won't have duplicate sessions and once all threads finished updating I loop through all the content in the hashset and then store it in txt files.

A: If your problem is saving stuff from each thread you may save the data you want in public variables inside a top class that calls each thread. For instance, i have a class called controlador inside a class GUI. This class handle other threads. When there is information of other threads i want to pass to class GUI i save the info inside controlador attributes and then call the attributes through class GUI. I do not know if i made my self clear. The only problem is if you want to update a control inside class GUI from one of the other threads. If this is your case you should have methods like this in GUI class:
Delegate Sub SetDebugLabel_Delegate(ByVal lbl As Label, ByVal text As String)

Public Sub SetDebugLabel_ThreadSafe(ByVal lbl As Label, ByVal text As String)
    If lbl.InvokeRequired Then
            Dim MyDelegate As New SetDebugLabel_Delegate(AddressOf SetDebugLabel_ThreadSafe)
            Me.Invoke(MyDelegate, New Object() {lbl, text})
    Else
        lbl.Text = text
    End If
End Sub

Then you should use inside the do work sub something like this:
 SetDebugLabel_ThreadSafe(Me.lblDataServer, ctrl.dTempo)

Where ctrl is the controlador class instantiated.
If you like the XML approach you could save the data you want into a datatable and then export to XML.
One way can be seen in https://msdn.microsoft.com/en-us/library/system.data.datatable.writexml(v=vs.110).aspx or you can do it like this:
    Dim settings As XmlWriterSettings = New XmlWriterSettings()
    settings.Indent = True

Using writer As XmlWriter = XmlWriter.Create(caminho & "alarmes.xml", settings)

   ' Begin writing.
     writer.WriteStartDocument()
     writer.WriteStartElement("CNCO") ' Root.

     With Login.user.DB1.dsDados.Tables("Lista")
         For i As Integer = 0 To .Rows.Count - 1
              writer.WriteStartElement("Duto")
              writer.WriteElementString("Nome", "Alarmes")
              writer.WriteElementString("TAG", .Rows(i)("TAG"))
              writer.WriteEndElement()
         Next

         ' End document.
         writer.WriteEndElement()
         writer.WriteEndDocument()

    End With
 End Using

To read the XML, simply read the path (arquivo is the path string) and restore the data into a datatable. One way could be done like this:
 With Login.user.DB1.dsDados
          .Tables("Lista").Clear()
          .ReadXml(arquivo)
          .Tables(0).DefaultView.Sort = "TAG DESC"
 End With


text:
Q: React Component : "if else" statement not updating inside return statement I am noob in React and pretty new in front.
I am trying to change the color of the property "fill" (in polygon) in React.
If perc > 50 i want the result to be green, and otherwise red.
I have written an "if else" statement but no color is rendering.
I have checked this Is it possible to use if...else... statement in React render function? and other sources online/ What i want to do seems possible and i don't know why its not rendering.
import React, { Component } from 'react';

class SvgStationIconGauge extends Component {
  render() {
    const { perc } = this.props || 0;
    const color_fill = 0;
    if (perc >50) {
      color_fill = "#ff0000";
    } else {
      color_fill = "#00ff00";
    }
    return (
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 50 120" className="icon-station">
        <title>Station name</title>
        <desc>Marker with gauge to display availability </desc>
     //#Here is what i am trying to render!!
        <polygon points="2 2 48 2 48 80 25 118 2 80" stroke="#333333" strokeWidth="4" fill= {color_fill} />
        <clipPath id="fill-icon">
          <polygon points="4 4 46 4 46 80 25 116 4 80 " strokeWidth="1" />
        </clipPath>
        <g clipPath="url(#fill-icon)">
          <rect width="100%" height={perc} fill="white" />
        </g>
      </svg>
    );
  }
}

export default SvgStationIconGauge;

As mentionned, i am a noob in React and any observation or suggestion would be welcomed!

A: you can't ressign const. use let
let color_fill = 0;
    if (perc >50) {
      color_fill = "#ff0000";
    } else {
      color_fill = "#00ff00";
    }

A: You can't reassign a const value. Either make colour_fill a let or try:
const color_fill = perc >50 ? "#ff0000" : "#00ff00";


text:
Q: Finding the numbers of primes $I start by considering Fermats theorem that $4n+1$ primes are the sum of two primes.
I then consider all such sums of positive integers $x$ and $y$ such that $x^2+y^2<n$
These can be found in in a circle segment between y=0 and x=y with radius $ \sqrt{n} $   and the numbers in this segment is approximately $\sqrt{n}^2\pi/8=n\pi/8$ representing the number of pairs.
Such a segment containing the x- or y axis will contain more numbers than if otherwise oriented, but I assume this discrepancy will diminish - relatively - for large n, and therefore the segment formula will represent the numbers in the segment in a reasonable way.
I now proceed but rather than trying to count the primes I list the challenges ahead. I note that the expression $\sqrt{n}^2\pi/8=n\pi/8$ is very far from  what is usually seen as the numbers of primes below a certain number n, and I therefore assume the challenges are formidable.

*

*I first assume (without proof or complete knowledge) that the number of 4n+3 and 4n+1 primes are - relatively - the same, i.e. the limit of their ratio is one as n goes to infinity.

*I only count half the numbers in the segment, disregarding pairs with even-even or odd-odd squares (since their sums cannot be of the type 4n+1). This is evened out by the 4n+3 numbers so the number $n\pi/8$ is still a valid estimate, using proper corrections below. (I note that the prime 2 is also missing in my formalism).

*I must also disregard the sums of squares made by pairs, which are not primes. These are usually sums which can be represented 2 ways and therefore appear in pair of pairs. I consider also the Pythagorean number which can be considered doubles if 0 is included such as $3^2+4^2=5^2+0^2$.

*I must also disregard pairs of multiples of pairs which originally contributed to the prime count. We have for example $2^2+1^2=5$ with the multiple $ (2*3)^2+(1*3)^2=45$ (multiples of even numbers are already disregarded by my  decision to disregard sums of squares made up by even-even pairs).

*As numbers progress to higher n there will be numbers who can be represented as sums of squares in three different ways such as for 325, $325=18^2+1=15^2+10^2=6^2+17^2$. Similarly some larger numbers may be represented in an arbitrary number of different ways.
This last phenomenon makes me uneasy. My question is: do you believe these numbers will be significant or will the ratio between these numbers and the prime numbers go to 0 as n goes to infinity?
(Plus: have I forgotten some other necessary corrections?)

A: Greg Martin indicates that this may be off target. It is, however, not widely known, and may help anyway.
The number of positive integers (that are sums of two squares) up to some large $x$ is asymptotically
$$  \frac{0.7642 \; x}{\sqrt{\log x}}.  $$
This is the final few pages in Volume II of LeVeque, where the infinite product that gives $0.7642...$ is specified and an error bound is given. Theorem 7-28 on page 261 of Volume II, they put two volumes into one and kept each set of page numbers.
This is larger than the number of primes up to $x$ by a factor of $0.7642 \sqrt{\log x}.$


text:
Q: Why isn't OAuth2 client refreshing expired access_token? I've got a client app configured with @EnableOAuth2Sso and @EnableZuulProxy, and a resource server (separate app) configured with @EnableOAuth2Resource. I can see that the client correctly authenticates to the resource server with Authorization: Bearer {access_token here}, but when once the access token expires, the proxied resource server request fails permanently.
[Edited]
I've modified my resource server by providing a custom RemoteTokenServices bean that uses OpenAM's /tokeninfo endpoint to decide whether an access_token remains valid. (The Spring-provided RemoteTokenServices bean attempts to POST, which gets a 405 from OpenAM). When I detect the access_token is invalid, I throw InvalidTokenException from my.spring.oauth2.OpenAMRemoteTokenServices#loadAuthentication. Now, my resource server is (I think correctly) sending HTTP 401 on the response to the client, in the case where the access_token has expired.
Still, the client is not attempting to refresh the token.
Maybe my mental model is wrong. I expect the client, in the case of expired access_token, to automatically use the refresh_token to obtain a new one. I don't know whether I think it should proactively refresh an access_token (within some epsilon before expiry time), or wait for a downstream request to fail and try refreshing then. But my client appears to be doing neither, and I can't tell why not.

A: As stated in this git issue: https://github.com/spring-guides/tut-spring-security-and-angular-js/issues/140, the problem might be related to the fact that with versions 1.4 and above of spring boot the Zuul filter that handles the downstream of access tokens to services (org.springframework.cloud.security.oauth2.proxy.OAuth2TokenRelayFilter)  is missing a bean of type OAuth2RestTemplate, which is used by the filter itself to automatically handle the refresh_token grant when access tokens expire.
I had the same issue and I solved it by adding in a configuration class the following bean:
@Configuration
public class ZuulConfiguration {
    @Bean
    protected OAuth2RestTemplate oauth2RestTemplate(OAuth2ProtectedResourceDetails resource,
        OAuth2ClientContext context) {

        return new OAuth2RestTemplate(resource, context);
    }
}