text:
Q: How to add ImageButton in Map Fragment? I try add ImageButton in Map Fragment. My activity_maps.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.myMaps.MapsActivity" >

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="info.myMaps.MapsActivity" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/buttonAdd" />

<ImageButton
    android:contentDescription="@string/imageButtonDel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/common_google_signin_btn_icon_dark_focused"
    android:id="@+id/imageButton"
    android:layout_below="@+id/buttonAdd"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="20dp" />
   </RelativeLayout>

Button add perfect but ImageButton I don`t see image, although the picture appears and I see it in the preview.

A: You're using app:srcCompat, you should also add vectorDrawables.useSupportLibrary = true to your gradle file

A: Try this :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:orientation="vertical"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#2196F3"
        android:orientation="horizontal"
        android:weightSum="1">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="#2196F3"
            android:text="text1"
            android:textColor="#ffffff"
            android:textStyle="bold" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="#2196F3"
            android:text="text2"
            android:textColor="#ffffff"
            android:textStyle="bold"

            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/cam"/>
    </LinearLayout>
</LinearLayout>
</FrameLayout>


text:
Q: MySQL left join subquery fail Following query runs well in MySQL 5.x
SELECT
  m_area.id, m_area.cn_areaName, m_area.de_areaName,
  m_area.en_areaName,m_area.jp_areaName,t_shop.count
FROM
  m_area left join
(
select t_shop.areaID, count(areaID) AS count
from t_shop
group by t_shop.areaID
) t_shop
on m_area.id = t_shop.areaID

However, when I have to run it in a 4.0.23 MySQL DB with same DB structure and data it just return following message:

1064 - You have an error in your SQL syntax.  Check the manual that corresponds to your MySQL server version for the right syntax to use near '[
            select t_shop.areaID, count(areaID) AS count
            from t_s

I tried many times but still failed. Is left join to subquery not allowed in MySQL 4.x ? Then that mean I have to do it with a temp table?
Thanks in advance!

A: Subqueries were quite not well supported with MySQL 4.0 : it became possible to use them (at least, in some real, useful way) with MySQL 4.1 -- and MySQL 4.0 is really old, now...

See for instance this page of the MySQL manual : 12.2.8. Subquery Syntax (quoting, emphasis mine) :

Starting with MySQL 4.1, all subquery forms and operations that the
  SQL standard requires are supported,
  as well as a few features that are
  MySQL-specific.
With MySQL versions prior to 4.1, it
  was necessary to work around or
  avoid the use of subqueries. In
  many cases, subqueries can
  successfully be rewritten using joins
  and other methods. See Section
  12.2.8.11, "Rewriting Subqueries as Joins for Earlier MySQL Versions".

A: Only thing I could think of is adding the tablename to your areaID in the subquery or renaming the reserved word count to cnt.
SELECT  m_area.id
        , m_area.cn_areaName
        , m_area.de_areaName
        , m_area.en_areaName
        ,m_area.jp_areaName
        ,t_shop.cnt
FROM     m_area
        left join (
          select     t_shop.areaID
                    , count(t_shop.areaID) AS cnt
          from       t_shop
          group by   t_shop.areaID
        ) t_shop on m_area.id = t_shop.areaID

A: take out ", count(areaID) AS count"
The multiple columns in the subquery is messing up the join.
A temp table should work fine ....
Have fun!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the current time in Y-m-d H:i:s.Millisecond format in PHP if I use date('Y-m-d H:i:s.u') the output will be some thing like 2015-11-03 13:25:25.253000. But i need  2015-11-03 13:25:25.253 how I can do it?

A: Try this date('Y-m-d H:i:s'.substr((string)microtime(), 1, 4))
or what Daniel suggests in the comment down below.


text:
Q: Script task not run after first loop in the loop container Script task not run after first loop in the  loop container.
Tried adjusting expression as well, same result.
Attached is the screenshot after first run:

A: if you are trying to run it multiple times then you should use For Each Loop conatiner


text:
Q: Is it necessary to enable CONFIG_USB_OHCI_HCD , when there's only USB 2.0 ports Is it necessary to enable CONFIG_USB_OHCI_HCD on a system that has USB 2.0 port only ?
I'm not sure those devices present , e.g bluetooth , camera use that driver ?
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 003: ID 147e:2016 Upek Biometric Touchchip/Touchstrip Fingerprint Sensor
Bus 001 Device 004: ID 0a5c:217f Broadcom Corp. Bluetooth Controller
Bus 001 Device 005: ID 04f2:b217 Chicony Electronics Co., Ltd Lenovo Integrated Camera (0.3MP)
Bus 001 Device 006: ID 046d:c058 Logitech, Inc. M115 Mouse

A: Yes, is is needed to have one of OHCI_HCD (Open Host Controller Interface) or UHCI_HCD (Universal Host Controller Driver) depending on your USB controller hardware.
The driver responsible for USB 2.0 communication is EHCI_HCD (Enhanced Host Controller Interface); but EHCI controllers are packaged with "companion" host controllers (OHCI or UHCI) to handle USB 1.1 devices connected to root hub ports. Ports will connect to EHCI if the device is high speed, otherwise they connect to a companion controller. If you configure EHCI, you should probably configure the OHCI (for NEC and some other vendors) USB Host Controller Driver or UHCI (for Via motherboards) Host Controller Driver too.
So, even if all your integrated USB peripherals are 2.0 (using EHCI), it is still needed to have a USB 1.1 driver (OHCI or UHCI) in case you attach a device that does not support High Speed.
You can see what controller type your attached devices are using, by running:
lspci -v

example output:
00:1a.0 USB Controller: Intel Corporation 6 Series/C200 Series Chipset Family USB Enhanced Host Controller #2 (rev 05) (**prog-if 20 [EHCI]**)
00:1d.7 USB Controller: Intel Corporation 82801H (ICH8 Family) USB2 EHCI Controller #1 (rev 02) (**prog-if 20 [EHCI]**)
04:00.0 USB Controller: ASMedia Technology Inc. ASM1042 SuperSpeed USB Host Controller (**prog-if 30 [XHCI]**)

In the sample XHCI (Extensible Host Controller Interface) is the driver for USB 3.0 support.


text:
Q: OpenMP reductions inside subgrograms The following Fortran code fails (random result), but replacing the call to mysum by abc=abc+1
gives the correct result. How to make OpenMP recognizing the reduction in a subprogram?
  program reduc

    use omp_lib
    implicit none

    integer :: abc=0, icount
    call OMP_set_num_threads(8)

    !$omp parallel private (icount) reduction(+:abc)
    !$omp do

    do icount = 1,8
      !abc = abc + 1
      call mysum(OMP_get_thread_num())
    end do

    !$omp end do
    !$omp end parallel
    print*,"abc at end: ",abc

    contains

    subroutine mysum(omp_rank)

    integer :: omp_rank

      abc = abc + 1
      print*,"OMP rank: ", omp_rank, " abc: ", abc

    endsubroutine mysum

  end program reduc

I also tried to put !$omp threadprivate (abc) into mysum, which was rejected with
"Error: Symbol 'abc' at (1) has no IMPLICIT type.", which is of course not true.

A: Because of the reduction, the original variable abc is privatised in each thread, but abc in the contained subroutine always refers to the original, non privatised variable.
The solution is to pass it as an argument:
subroutine mysum(omp_rank,abc)
    integer, intent(in) :: omp_rank
    integer, intent(inout) :: abc

    abc = abc + 1
    print*,"OMP rank: ", omp_rank, " abc: ", abc
endsubroutine mysum


text:
Q: Ayuda con un programa Se me pide hacer un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces que aparece la letra en la frase. Gracias

A: Deberías mostrar lo que has intentado para poder ayudarte mejor. A continuación te muestro un ejemplo que puedes implementar en tu caso.
entrada_frase = str(input("Introduce una frase: "))
entrada_letra = str(input("Introduce una letra: "))

contador = 0
for i in entrada_frase:
  if i == entrada_letra:
    contador += 1
  print("La letra '%s' aparece %2i veces en la frase '%s'." % (entrada_letra, contador, entrada_frase))


text:
Q: Extjs, define scope of column's renderer function I think that, bydefault renderer always refer to its calling object as scope. and we do not have to define anything but in my grid i have different behaviour.
I have to define rendere function runtime.
I make column object and for each column i assign renderer.
for (var i = 0; i < columns.length; i++) {
      newRenderer = function (v, m, r, rI, cI, s)
      {
           if(this.originalRend)  <<<<<-----------------
           // "this" is not object of column but whole page.
           {
                 //then call original}
           else {
                 // call new renderer
           }
      }
      columns[i].originalRend = columns[i].renderer;
      columns[i].renderer = newRenderer;
}

In my newRenderer function "THIS" does not refer to column object. WHY?????
and how to do that????

A: You should be able to use scope as a config option of the column, and that will be used by the renderer:
{
    renderer: function(val){
        return val.trim();
    },
    scope: this
}

Or, in the case of your code:
for (var i = 0; i < columns.length; i++) {
    newRenderer = function (v, m, r, rI, cI, s)
    {
         if(this.originalRend)  <<<<<-----------------
         // "this" is not object of column but whole page.
         {
             //then call original}
         else {
             // call new renderer
         }
    }
    //THIS LINE ADDED:
    columns[i].scope = columns[i];
    columns[i].originalRend = columns[i].renderer;
    columns[i].renderer = newRenderer;
}

See docs here: http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.grid.column.Column-cfg-scope

A: Scope does not work as column or this.
The best way is to overrite prepareData method of header container.
Ext.override(Ext.grid.header.Container, {
prepareData: function(data, rowIdx, record, view, panel) {
        //console.log("we r in prepare Data");
        var me        = this,
            obj       = {},
            headers   = me.gridDataColumns || me.getGridColumns(),
            headersLn = headers.length,
            dirtyCls = me.dirtyCls,
            colIdx    = 0,
            header,
            headerId,
            renderer,
            value,
            metaData,
            store = panel.store;

        for (; colIdx < headersLn; colIdx++) {
            metaData = {
                tdCls: '',
                style: ''
            };
            header = headers[colIdx];
            headerId = header.id;
            renderer = header.renderer;
            value = data[header.dataIndex];

            if (typeof renderer == "function") {
                value = renderer.call(
                    //--------change made below.------------------
                    header.scope || header || me.ownerCt,
                    //----------------end-------------------------
                    value,
                    // metadata per cell passing an obj by reference so that
                    // it can be manipulated inside the renderer
                    metaData,
                    record,
                    rowIdx,
                    colIdx,
                    store,
                    view
                );
            }

            // <debug>
            if (metaData.css) {
                // This warning attribute is used by the compat layer
                obj.cssWarning = true;
                metaData.tdCls = metaData.css;
                delete metaData.css;
            }
            // </debug>
            if (me.markDirty) {
                obj[headerId + '-modified'] = record.isModified(header.dataIndex) ? dirtyCls : '';
            }
            obj[headerId+'-tdCls'] = metaData.tdCls;
            obj[headerId+'-tdAttr'] = metaData.tdAttr;
            obj[headerId+'-style'] = metaData.style;
            if (typeof value === 'undefined' || value === null || value === '') {
                value = header.emptyCellText;
            }
            obj[headerId] = value;
        }
        return obj;
    },

}


text:
Q: Ways to fill up a $4 \times 4$ matrix with numbers $1$ to $16$, s.t its rank is $1$ under modulo $17$ As the title suggest. How many ways are there to fill up a $4 \times 4$ matrix with numbers $1$ to $16$, so that its rank is $1$ under modulo $17$ (i.e. consider elements of the matrix under $Z_{17}$)
Rank being 1 basically means all rows or columns are linearly dependent. If we look at a simple case, $2 \times 2$ matrix with numbers $1$ to $4$, under modulo $5$, all I can find is
\begin{matrix}
1 & 4\\
3 & 2
\end{matrix}
and its rotations. But I am not sure how to generalize this to higher orders..

A: I wrote a python script to find them by brute force.  The matrices all have $1$ in the first row and first column, and the entries in both the first row and first column are in increasing order (viewing them temporarily as elements of $\mathbb{Z}$.)  I found $256$ such matrices.  Of course, the rows and columns can each be permuted without changing the rank, so each matrix represents $24^2$ matrices.
I don't see any patterns at all.  $256=16^2$ gives one hope, but for me, at least, it's an empty promise.  Because of that, I'm appending a list of all $256$ matrices.  Maybe you'll see something I don't.
In the listing below, the matrices have been flattened for typographical considerations, so the first line represents the matrix, $$\begin{bmatrix}
1  &2  &3  &6\\
4  &8 &12  &7\\
13 &9  &5 &10\\
16 &15 &14 &11\end{bmatrix}$$
[ 1  2  3  6  4  8 12  7 13  9  5 10 16 15 14 11]
[ 1  2  3  7  4  8 12 11 13  9  5  6 16 15 14 10]
[ 1  2  3 10  4  8 12  6 13  9  5 11 16 15 14  7]
[ 1  2  3 11  4  8 12 10 13  9  5  7 16 15 14  6]
[ 1  2  4  8  3  6 12  7 14 11  5 10 16 15 13  9]
[ 1  2  4  8  5 10  3  6 12  7 14 11 16 15 13  9]
[ 1  2  4  8  6 12  7 14 11  5 10  3 16 15 13  9]
[ 1  2  4  8  7 14 11  5 10  3  6 12 16 15 13  9]
[ 1  2  4  9  3  6 12 10 14 11  5  7 16 15 13  8]
[ 1  2  4  9  5 10  3 11 12  7 14  6 16 15 13  8]
[ 1  2  4  9  6 12  7  3 11  5 10 14 16 15 13  8]
[ 1  2  4  9  7 14 11 12 10  3  6  5 16 15 13  8]
[ 1  2  5  6  4  8  3  7 13  9 14 10 16 15 12 11]
[ 1  2  5  7  4  8  3 11 13  9 14  6 16 15 12 10]
[ 1  2  5 10  4  8  3  6 13  9 14 11 16 15 12  7]
[ 1  2  5 11  4  8  3 10 13  9 14  7 16 15 12  6]

[ 1  2  6 12  4  8  7 14 13  9 10  3 16 15 11  5]
[ 1  2  6 14  4  8  7  5 13  9 10 12 16 15 11  3]
[ 1  2  7 12  4  8 11 14 13  9  6  3 16 15 10  5]
[ 1  2  7 14  4  8 11  5 13  9  6 12 16 15 10  3]
[ 1  2  8 13  3  6  7  5 14 11 10 12 16 15  9  4]
[ 1  2  8 13  5 10  6 14 12  7 11  3 16 15  9  4]
[ 1  2  8 13  6 12 14 10 11  5  3  7 16 15  9  4]
[ 1  2  8 13  7 14  5  6 10  3 12 11 16 15  9  4]
[ 1  2  9 13  3  6 10  5 14 11  7 12 16 15  8  4]
[ 1  2  9 13  5 10 11 14 12  7  6  3 16 15  8  4]
[ 1  2  9 13  6 12  3 10 11  5 14  7 16 15  8  4]
[ 1  2  9 13  7 14 12  6 10  3  5 11 16 15  8  4]
[ 1  2 10 12  4  8  6 14 13  9 11  3 16 15  7  5]
[ 1  2 10 14  4  8  6  5 13  9 11 12 16 15  7  3]
[ 1  2 11 12  4  8 10 14 13  9  7  3 16 15  6  5]
[ 1  2 11 14  4  8 10  5 13  9  7 12 16 15  6  3]

[ 1  2 15 16  3  6 11 14  4  8  9 13  5 10  7 12]
[ 1  2 15 16  3  6 11 14  4  8  9 13 12  7 10  5]
[ 1  2 15 16  3  6 11 14  5 10  7 12 13  9  8  4]
[ 1  2 15 16  3  6 11 14 12  7 10  5 13  9  8  4]
[ 1  2 15 16  4  8  9 13  5 10  7 12 14 11  6  3]
[ 1  2 15 16  4  8  9 13  6 12  5 11  7 14  3 10]
[ 1  2 15 16  4  8  9 13  6 12  5 11 10  3 14  7]
[ 1  2 15 16  4  8  9 13  7 14  3 10 11  5 12  6]
[ 1  2 15 16  4  8  9 13 10  3 14  7 11  5 12  6]
[ 1  2 15 16  4  8  9 13 12  7 10  5 14 11  6  3]
[ 1  2 15 16  5 10  7 12 13  9  8  4 14 11  6  3]
[ 1  2 15 16  6 12  5 11  7 14  3 10 13  9  8  4]
[ 1  2 15 16  6 12  5 11 10  3 14  7 13  9  8  4]
[ 1  2 15 16  7 14  3 10 11  5 12  6 13  9  8  4]
[ 1  2 15 16 10  3 14  7 11  5 12  6 13  9  8  4]
[ 1  2 15 16 12  7 10  5 13  9  8  4 14 11  6  3]

[ 1  3  4  5  2  6  8 10 15 11  9  7 16 14 13 12]
[ 1  3  4  5  8  7 15  6  9 10  2 11 16 14 13 12]
[ 1  3  4 12  2  6  8  7 15 11  9 10 16 14 13  5]
[ 1  3  4 12  8  7 15 11  9 10  2  6 16 14 13  5]
[ 1  3  5 13  2  6 10  9 15 11  7  8 16 14 12  4]
[ 1  3  5 13  8  7  6  2  9 10 11 15 16 14 12  4]
[ 1  3  6  8  4 12  7 15 13  5 10  2 16 14 11  9]
[ 1  3  6  9  4 12  7  2 13  5 10 15 16 14 11  8]
[ 1  3  6 15  4 12  7  9 13  5 10  8 16 14 11  2]
[ 1  3  7  8  4 12 11 15 13  5  6  2 16 14 10  9]
[ 1  3  7  9  4 12 11  2 13  5  6 15 16 14 10  8]
[ 1  3  7 15  4 12 11  9 13  5  6  8 16 14 10  2]
[ 1  3  8 10  4 12 15  6 13  5  2 11 16 14  9  7]
[ 1  3  8 11  4 12 15 10 13  5  2  7 16 14  9  6]
[ 1  3  9 10  4 12  2  6 13  5 15 11 16 14  8  7]
[ 1  3  9 11  4 12  2 10 13  5 15  7 16 14  8  6]

[ 1  3 10 15  4 12  6  9 13  5 11  8 16 14  7  2]
[ 1  3 11 15  4 12 10  9 13  5  7  8 16 14  6  2]
[ 1  3 12 13  2  6  7  9 15 11 10  8 16 14  5  4]
[ 1  3 12 13  8  7 11  2  9 10  6 15 16 14  5  4]
[ 1  3 14 16  2  6 11 15  4 12  5 13  8  7 10  9]
[ 1  3 14 16  2  6 11 15  4 12  5 13  9 10  7  8]
[ 1  3 14 16  2  6 11 15  8  7 10  9 13  5 12  4]
[ 1  3 14 16  2  6 11 15  9 10  7  8 13  5 12  4]
[ 1  3 14 16  4 12  5 13  8  7 10  9 15 11  6  2]
[ 1  3 14 16  4 12  5 13  9 10  7  8 15 11  6  2]
[ 1  3 14 16  8  7 10  9 13  5 12  4 15 11  6  2]
[ 1  3 14 16  9 10  7  8 13  5 12  4 15 11  6  2]
[ 1  4  5 14  2  8 10 11 15  9  7  6 16 13 12  3]
[ 1  4  5 14  8 15  6 10  9  2 11  7 16 13 12  3]
[ 1  4  6  7  2  8 12 14 15  9  5  3 16 13 11 10]
[ 1  4  6  7  8 15 14  5  9  2  3 12 16 13 11 10]

[ 1  4  6 10  2  8 12  3 15  9  5 14 16 13 11  7]
[ 1  4  6 10  8 15 14 12  9  2  3  5 16 13 11  7]
[ 1  4  7 11  2  8 14  5 15  9  3 12 16 13 10  6]
[ 1  4  7 11  8 15  5  3  9  2 12 14 16 13 10  6]
[ 1  4  8 15  3 12  7 11 14  5 10  6 16 13  9  2]
[ 1  4  8 15  5  3  6  7 12 14 11 10 16 13  9  2]
[ 1  4  8 15  6  7 14  5 11 10  3 12 16 13  9  2]
[ 1  4  8 15  7 11  5  3 10  6 12 14 16 13  9  2]
[ 1  4  9 15  3 12 10 11 14  5  7  6 16 13  8  2]
[ 1  4  9 15  5  3 11  7 12 14  6 10 16 13  8  2]
[ 1  4  9 15  6  7  3  5 11 10 14 12 16 13  8  2]
[ 1  4  9 15  7 11 12  3 10  6  5 14 16 13  8  2]
[ 1  4 10 11  2  8  3  5 15  9 14 12 16 13  7  6]
[ 1  4 10 11  8 15 12  3  9  2  5 14 16 13  7  6]
[ 1  4 12 14  2  8  7 11 15  9 10  6 16 13  5  3]
[ 1  4 12 14  8 15 11 10  9  2  6  7 16 13  5  3]

[ 1  4 13 16  2  8  9 15  3 12  5 14  6  7 10 11]
[ 1  4 13 16  2  8  9 15  3 12  5 14  7 11  6 10]
[ 1  4 13 16  2  8  9 15  3 12  5 14 10  6 11  7]
[ 1  4 13 16  2  8  9 15  3 12  5 14 11 10  7  6]
[ 1  4 13 16  2  8  9 15  5  3 14 12  6  7 10 11]
[ 1  4 13 16  2  8  9 15  5  3 14 12  7 11  6 10]
[ 1  4 13 16  2  8  9 15  5  3 14 12 10  6 11  7]
[ 1  4 13 16  2  8  9 15  5  3 14 12 11 10  7  6]
[ 1  4 13 16  2  8  9 15  6  7 10 11 12 14  3  5]
[ 1  4 13 16  2  8  9 15  6  7 10 11 14  5 12  3]
[ 1  4 13 16  2  8  9 15  7 11  6 10 12 14  3  5]
[ 1  4 13 16  2  8  9 15  7 11  6 10 14  5 12  3]
[ 1  4 13 16  2  8  9 15 10  6 11  7 12 14  3  5]
[ 1  4 13 16  2  8  9 15 10  6 11  7 14  5 12  3]
[ 1  4 13 16  2  8  9 15 11 10  7  6 12 14  3  5]
[ 1  4 13 16  2  8  9 15 11 10  7  6 14  5 12  3]

[ 1  4 13 16  3 12  5 14  6  7 10 11  8 15  2  9]
[ 1  4 13 16  3 12  5 14  6  7 10 11  9  2 15  8]
[ 1  4 13 16  3 12  5 14  6  7 10 11 15  9  8  2]
[ 1  4 13 16  3 12  5 14  7 11  6 10  8 15  2  9]
[ 1  4 13 16  3 12  5 14  7 11  6 10  9  2 15  8]
[ 1  4 13 16  3 12  5 14  7 11  6 10 15  9  8  2]
[ 1  4 13 16  3 12  5 14  8 15  2  9 10  6 11  7]
[ 1  4 13 16  3 12  5 14  8 15  2  9 11 10  7  6]
[ 1  4 13 16  3 12  5 14  9  2 15  8 10  6 11  7]
[ 1  4 13 16  3 12  5 14  9  2 15  8 11 10  7  6]
[ 1  4 13 16  3 12  5 14 10  6 11  7 15  9  8  2]
[ 1  4 13 16  3 12  5 14 11 10  7  6 15  9  8  2]
[ 1  4 13 16  5  3 14 12  6  7 10 11  8 15  2  9]
[ 1  4 13 16  5  3 14 12  6  7 10 11  9  2 15  8]
[ 1  4 13 16  5  3 14 12  6  7 10 11 15  9  8  2]
[ 1  4 13 16  5  3 14 12  7 11  6 10  8 15  2  9]

[ 1  4 13 16  5  3 14 12  7 11  6 10  9  2 15  8]
[ 1  4 13 16  5  3 14 12  7 11  6 10 15  9  8  2]
[ 1  4 13 16  5  3 14 12  8 15  2  9 10  6 11  7]
[ 1  4 13 16  5  3 14 12  8 15  2  9 11 10  7  6]
[ 1  4 13 16  5  3 14 12  9  2 15  8 10  6 11  7]
[ 1  4 13 16  5  3 14 12  9  2 15  8 11 10  7  6]
[ 1  4 13 16  5  3 14 12 10  6 11  7 15  9  8  2]
[ 1  4 13 16  5  3 14 12 11 10  7  6 15  9  8  2]
[ 1  4 13 16  6  7 10 11  8 15  2  9 12 14  3  5]
[ 1  4 13 16  6  7 10 11  8 15  2  9 14  5 12  3]
[ 1  4 13 16  6  7 10 11  9  2 15  8 12 14  3  5]
[ 1  4 13 16  6  7 10 11  9  2 15  8 14  5 12  3]
[ 1  4 13 16  6  7 10 11 12 14  3  5 15  9  8  2]
[ 1  4 13 16  6  7 10 11 14  5 12  3 15  9  8  2]
[ 1  4 13 16  7 11  6 10  8 15  2  9 12 14  3  5]
[ 1  4 13 16  7 11  6 10  8 15  2  9 14  5 12  3]

[ 1  4 13 16  7 11  6 10  9  2 15  8 12 14  3  5]
[ 1  4 13 16  7 11  6 10  9  2 15  8 14  5 12  3]
[ 1  4 13 16  7 11  6 10 12 14  3  5 15  9  8  2]
[ 1  4 13 16  7 11  6 10 14  5 12  3 15  9  8  2]
[ 1  4 13 16  8 15  2  9 10  6 11  7 12 14  3  5]
[ 1  4 13 16  8 15  2  9 10  6 11  7 14  5 12  3]
[ 1  4 13 16  8 15  2  9 11 10  7  6 12 14  3  5]
[ 1  4 13 16  8 15  2  9 11 10  7  6 14  5 12  3]
[ 1  4 13 16  9  2 15  8 10  6 11  7 12 14  3  5]
[ 1  4 13 16  9  2 15  8 10  6 11  7 14  5 12  3]
[ 1  4 13 16  9  2 15  8 11 10  7  6 12 14  3  5]
[ 1  4 13 16  9  2 15  8 11 10  7  6 14  5 12  3]
[ 1  4 13 16 10  6 11  7 12 14  3  5 15  9  8  2]
[ 1  4 13 16 10  6 11  7 14  5 12  3 15  9  8  2]
[ 1  4 13 16 11 10  7  6 12 14  3  5 15  9  8  2]
[ 1  4 13 16 11 10  7  6 14  5 12  3 15  9  8  2]

[ 1  5  6  8  4  3  7 15 13 14 10  2 16 12 11  9]
[ 1  5  6  9  4  3  7  2 13 14 10 15 16 12 11  8]
[ 1  5  6 15  4  3  7  9 13 14 10  8 16 12 11  2]
[ 1  5  7  8  4  3 11 15 13 14  6  2 16 12 10  9]
[ 1  5  7  9  4  3 11  2 13 14  6 15 16 12 10  8]
[ 1  5  7 15  4  3 11  9 13 14  6  8 16 12 10  2]
[ 1  5  8 10  4  3 15  6 13 14  2 11 16 12  9  7]
[ 1  5  8 11  4  3 15 10 13 14  2  7 16 12  9  6]
[ 1  5  9 10  4  3  2  6 13 14 15 11 16 12  8  7]
[ 1  5  9 11  4  3  2 10 13 14 15  7 16 12  8  6]
[ 1  5 10 15  4  3  6  9 13 14 11  8 16 12  7  2]
[ 1  5 11 15  4  3 10  9 13 14  7  8 16 12  6  2]
[ 1  5 12 16  2 10  7 15  4  3 14 13  8  6 11  9]
[ 1  5 12 16  2 10  7 15  4  3 14 13  9 11  6  8]
[ 1  5 12 16  2 10  7 15  8  6 11  9 13 14  3  4]
[ 1  5 12 16  2 10  7 15  9 11  6  8 13 14  3  4]

[ 1  5 12 16  4  3 14 13  8  6 11  9 15  7 10  2]
[ 1  5 12 16  4  3 14 13  9 11  6  8 15  7 10  2]
[ 1  5 12 16  8  6 11  9 13 14  3  4 15  7 10  2]
[ 1  5 12 16  9 11  6  8 13 14  3  4 15  7 10  2]
[ 1  5 13 14  2 10  9 11 15  7  8  6 16 12  4  3]
[ 1  5 13 14  8  6  2 10  9 11 15  7 16 12  4  3]
[ 1  6  7 13  2 12 14  9 15  5  3  8 16 11 10  4]
[ 1  6  7 13  8 14  5  2  9  3 12 15 16 11 10  4]
[ 1  6  8 12  4  7 15 14 13 10  2  3 16 11  9  5]
[ 1  6  8 14  4  7 15  5 13 10  2 12 16 11  9  3]
[ 1  6  9 12  4  7  2 14 13 10 15  3 16 11  8  5]
[ 1  6  9 14  4  7  2  5 13 10 15 12 16 11  8  3]
[ 1  6 10 13  2 12  3  9 15  5 14  8 16 11  7  4]
[ 1  6 10 13  8 14 12  2  9  3  5 15 16 11  7  4]
[ 1  6 11 16  2 12  5 15  4  7 10 13  8 14  3  9]
[ 1  6 11 16  2 12  5 15  4  7 10 13  9  3 14  8]

[ 1  6 11 16  2 12  5 15  8 14  3  9 13 10  7  4]
[ 1  6 11 16  2 12  5 15  9  3 14  8 13 10  7  4]
[ 1  6 11 16  4  7 10 13  8 14  3  9 15  5 12  2]
[ 1  6 11 16  4  7 10 13  9  3 14  8 15  5 12  2]
[ 1  6 11 16  8 14  3  9 13 10  7  4 15  5 12  2]
[ 1  6 11 16  9  3 14  8 13 10  7  4 15  5 12  2]
[ 1  6 12 15  4  7 14  9 13 10  3  8 16 11  5  2]
[ 1  6 14 15  4  7  5  9 13 10 12  8 16 11  3  2]
[ 1  7  8 12  4 11 15 14 13  6  2  3 16 10  9  5]
[ 1  7  8 14  4 11 15  5 13  6  2 12 16 10  9  3]
[ 1  7  9 12  4 11  2 14 13  6 15  3 16 10  8  5]
[ 1  7  9 14  4 11  2  5 13  6 15 12 16 10  8  3]
[ 1  7 10 16  2 14  3 15  4 11  6 13  8  5 12  9]
[ 1  7 10 16  2 14  3 15  4 11  6 13  9 12  5  8]
[ 1  7 10 16  2 14  3 15  8  5 12  9 13  6 11  4]
[ 1  7 10 16  2 14  3 15  9 12  5  8 13  6 11  4]

[ 1  7 10 16  4 11  6 13  8  5 12  9 15  3 14  2]
[ 1  7 10 16  4 11  6 13  9 12  5  8 15  3 14  2]
[ 1  7 10 16  8  5 12  9 13  6 11  4 15  3 14  2]
[ 1  7 10 16  9 12  5  8 13  6 11  4 15  3 14  2]
[ 1  7 11 13  2 14  5  9 15  3 12  8 16 10  6  4]
[ 1  7 11 13  8  5  3  2  9 12 14 15 16 10  6  4]
[ 1  7 12 15  4 11 14  9 13  6  3  8 16 10  5  2]
[ 1  7 14 15  4 11  5  9 13  6 12  8 16 10  3  2]
[ 1  8  9 16  3  7 10 14  4 15  2 13  5  6 11 12]
[ 1  8  9 16  3  7 10 14  4 15  2 13 12 11  6  5]
[ 1  8  9 16  3  7 10 14  5  6 11 12 13  2 15  4]
[ 1  8  9 16  3  7 10 14 12 11  6  5 13  2 15  4]
[ 1  8  9 16  4 15  2 13  5  6 11 12 14 10  7  3]
[ 1  8  9 16  4 15  2 13  6 14  3 11  7  5 12 10]
[ 1  8  9 16  4 15  2 13  6 14  3 11 10 12  5  7]
[ 1  8  9 16  4 15  2 13  7  5 12 10 11  3 14  6]

[ 1  8  9 16  4 15  2 13 10 12  5  7 11  3 14  6]
[ 1  8  9 16  4 15  2 13 12 11  6  5 14 10  7  3]
[ 1  8  9 16  5  6 11 12 13  2 15  4 14 10  7  3]
[ 1  8  9 16  6 14  3 11  7  5 12 10 13  2 15  4]
[ 1  8  9 16  6 14  3 11 10 12  5  7 13  2 15  4]
[ 1  8  9 16  7  5 12 10 11  3 14  6 13  2 15  4]
[ 1  8  9 16 10 12  5  7 11  3 14  6 13  2 15  4]
[ 1  8  9 16 12 11  6  5 13  2 15  4 14 10  7  3]
[ 1  8 10 12  4 15  6 14 13  2 11  3 16  9  7  5]
[ 1  8 10 14  4 15  6  5 13  2 11 12 16  9  7  3]
[ 1  8 11 12  4 15 10 14 13  2  7  3 16  9  6  5]
[ 1  8 11 14  4 15 10  5 13  2  7 12 16  9  6  3]
[ 1  8 13 15  3  7  5 11 14 10 12  6 16  9  4  2]
[ 1  8 13 15  5  6 14  7 12 11  3 10 16  9  4  2]
[ 1  8 13 15  6 14 10  5 11  3  7 12 16  9  4  2]
[ 1  8 13 15  7  5  6  3 10 12 11 14 16  9  4  2]

[ 1  9 10 12  4  2  6 14 13 15 11  3 16  8  7  5]
[ 1  9 10 14  4  2  6  5 13 15 11 12 16  8  7  3]
[ 1  9 11 12  4  2 10 14 13 15  7  3 16  8  6  5]
[ 1  9 11 14  4  2 10  5 13 15  7 12 16  8  6  3]
[ 1  9 13 15  3 10  5 11 14  7 12  6 16  8  4  2]
[ 1  9 13 15  5 11 14  7 12  6  3 10 16  8  4  2]
[ 1  9 13 15  6  3 10  5 11 14  7 12 16  8  4  2]
[ 1  9 13 15  7 12  6  3 10  5 11 14 16  8  4  2]
[ 1 10 11 13  2  3  5  9 15 14 12  8 16  7  6  4]
[ 1 10 11 13  8 12  3  2  9  5 14 15 16  7  6  4]
[ 1 10 12 15  4  6 14  9 13 11  3  8 16  7  5  2]
[ 1 10 14 15  4  6  5  9 13 11 12  8 16  7  3  2]
[ 1 11 12 15  4 10 14  9 13  7  3  8 16  6  5  2]
[ 1 11 14 15  4 10  5  9 13  7 12  8 16  6  3  2]
[ 1 12 13 14  2  7  9 11 15 10  8  6 16  5  4  3]
[ 1 12 13 14  8 11  2 10  9  6 15  7 16  5  4  3]


text:
Q: How to change the finder services submenu threshold? In the finder context menu, there is a list of services at the very bottom. Once this list grows beyond 4, it becomes a submenu instead.
Is there a way to affect this threshold, i. e. have five services showing on the first menu level?

A: In Terminal, paste the following line and hit return:
defaults write -g NSServicesMinimumItemCountForContextSubmenu -int 99; killall Finder

You can change 99 to whatever number you prefer – when there are 99 items or more, Finder will place them in a submenu instead of appending them to the context menu. The default is 5.


text:
Q: UNION DISTINCT in laravel query builder When i use $query2->union($query1) this is the result sql in laravel:
query one ...
union
query two ...

How can i have this query:
query one ...
union distinct
query two ...

In laravel documentation i saw only union() and unionAll() methods.

A: As per this answer, a UNION query by definition is a distinct query (assuming the columns in the two results are the same). A UNION ALL returns duplicates if they exist.
So, in Laravel 5.1 (at least), running a union as per the example in the documentation is, by default, distinct:
$first = DB::table('users')
    ->whereNull('first_name');

$users = DB::table('users')
    ->whereNull('last_name')
    ->union($first)
    ->get();

I'm not going to repeat what has been said well in that answer regarding performance (it's worth reading) but in summary a DISTINCT is slower than a DISTINCT ALL.


text:
Q: The type or namespace name could not be found, Beginner in C# Hello I'm a beginner in C# and I'm trying an online example to use the Kinect for Windows device.
I think the problem is in my referencing but don't know what to do
I think it has something to do with the .Net framework as the example seems to be based on an older version of the framework
PS: I did reference the kinect dll using "Add References"
and the project references are:
Microsoft.CSharp
Microsoft.Kinect
System
System.ComponentModel.Composition
System.ComponentModel.DataAnnotations
System.Core
System.Data
System.Data.DataSetExtensions
System.Deployment
System.Drawing
System.Runtime.DurableInstancing
System.Runtime.Remoting
System.Runtime.Serialization
System.Windows.Forms
System.Runtime.Serialization.Formatters.Soap
System.Xml
System.Xml.Linq

The errors I'm getting are:

Error 1: the type or namespace name 'Runtime' Could not be found line
  20
Error 2: the type or namespace name 'ImageFrameReadyEventArgs' Could
  not be found line 43
Error 2: the type or namespace name 'PlanarImage' Could not be found
  line 50

here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Imaging;
using System.Runtime.InteropServices;

using Microsoft.Kinect;

namespace HelloKinectWorld
{
    public partial class Form1 : Form
    {

        Runtime nui = Runtime.Kinects[0];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(
        object sender, EventArgs e)
        {
            nui.Initialize(RuntimeOptions.UseColor);
            nui.VideoStream.Open(
            ImageStreamType.Video,
            2,
            ImageResolution.Resolution640x480,
             ImageType.Color);
            nui.VideoFrameReady +=
            new EventHandler<ImageFrameReadyEventArgs>(
            FrameReady);
        }

        void FrameReady(object sender,
        ImageFrameReadyEventArgs e)
        {
            PlanarImage Image = e.ImageFrame.Image;
            Bitmap bmap = PImageToBitmap(Image);
            pictureBox1.Image = bmap;
        }

        Bitmap PImageToBitmap(PlanarImage PImage)
        {
            Bitmap bmap = new Bitmap(
            PImage.Width,
            PImage.Height,
            PixelFormat.Format32bppRgb);
            BitmapData bmapdata = bmap.LockBits(
            new Rectangle(0, 0, PImage.Width,
            PImage.Height),
             ImageLockMode.WriteOnly,
            bmap.PixelFormat);
            IntPtr ptr = bmapdata.Scan0;
            Marshal.Copy(PImage.Bits,
            0,
            ptr,
            PImage.Width *
            PImage.BytesPerPixel *
             PImage.Height);
            bmap.UnlockBits(bmapdata);
            return bmap;
        }

        private void button1_Click(
        object sender, EventArgs e)
        {
            nui.NuiCamera.ElevationAngle += 4;
        }

        private void button2_Click(
        object sender,
        EventArgs e)
        {
            nui.NuiCamera.ElevationAngle -= 4;
        }

        private void Form1_FormClosing(
                     object sender,
                     FormClosingEventArgs e)
        {
            nui.Uninitialize();
        }
    }
}

A: Which version of the Kinect SDK are you using? In the most recent version (1.8), Runtime would most likely be KinectSensor, ImageFrameReadyEventArgs would be ColorFrameReadyEventArgs (or AllFramesReadyEventArgs) and PlanarImage would be ColorImage.

A: This usually means you need to add some references to assemblies. You are importing Microsoft.Kinect, but you should check that you're actually referencing the microsoft.kinect dlls from your visual studio project.
You can check it on the references folder in your visual studio project. If you haven't added the required kinect dlls as part of the project, do so by using context menu and "add reference".


text:
Q: MATLAB: textscan to parse irregular text, trouble debugging format specifier I've been browsing stack overflow and the mathworks website trying to come up with a solution for reading an irregularly formatted text file into MATLAB using textscan but have yet to figure out a good solution.
The format of the text file looks as such:

// Reference=MNI
// Citation=Beauregard M, 1998
// Condition=Primed - Unprimed Semantic Category Decision
// Domain=Semantics
// Modality=Visual
// Subjects=13
-55   -25 -23
33    -9  -20
// Citation=Beauregard M, 1998
// Condition=Unprimed Semantic Category Decision - Baseline
// Domain=Semantics
// Modality=Visual
// Subjects=13
0 -73 9
-25   -59 47
0 -14 59
8 -18 63
-21   -90 -11
-24   -4  62
24    -93 -6
-21   15  47
-35   -26 -21
9 13  44
// Citation=Binder J R, 1996
// Condition=Words > Tones - Passive
// Domain=Language Perception
// Modality=Auditory
// Subjects=12
-58.73    -12.05  -4.61

I would like to end up with a cell array that looks like this
{nx3 double}  {nx1 cellstr} {nx1 cellstr} {nx1 cellstr} {nx1 double}
Where the first element in the array are the 3d coordinates, the second element the citation, the third element the condition, the fourth element the domain, the fifth element the modality and the sixth element the number of subjects.
I would then like to use these cell array to organize the data into a structure to allow for easy indexing of the coordinates by each of the features I extracted from the text file.
I've tried a bunch of things but have only been able to extract out the coordinates as a string and the feature as a single cell array.
Here is how far I have gotten after searching through stack overflow and the mathworks website:
fid = fopen(fullfile(path2proj,path2loc),'r');
data = textscan(fid,'%s %s %s','HeaderLines',1,...
    'delimiter',{...
        sprintf('// '),...
        'Citation=',...
        'Condition=',...
        'Domain=',...
        'Modality=',...
        'Subjects='});

I get the following output with this code:

data =
{16470x1 cell}    {16470x1 cell}    {16470x1 cell}

data{1}(1:20)

ans =
''
''
''
''
''
'-55  -25 -23'
'33   -9  -20'
''
''
''
''
''
'0    -73 9'
'-25  -59 47'
'0    -14 59'
'8    -18 63'
'-21  -90 -11'
'-24  -4  62'
'24   -93 -6'
'-21  15  47'

data{2}(1:20)

ans =
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''
''

data{3}(1:20)
      ans =

'Beauregard M, 1998'
'Primed - Unprimed Semantic Category Decision'
'Semantics'
'Visual'
'13'
''
''
'Beauregard M, 1998'
'Unprimed Semantic Category Decision - Baseline'
'Semantics'
'Visual'
'13'
''
''
''
''
''
''
''
''

Although I can work with the data in this format, it would be nice to understand how to correctly right a format specifier to extract out piece of data into it's own cell array.  Does anyone have any dieas?

A: Assuming that Reference is only in the first line, you could do the following to obtained the values you want from each section Citation section.
% read the file and split it into sections based on Citation
filecontents = strsplit(fileread('data.txt'), '// Citation');

% iterate through section and extract desired info from each
% section. We start from i=2, as for i=1 we have 'Reference' line.
for i = 2:numel(filecontents)

    lines = regexp(filecontents{i}, '\n', 'split');

    % remove empty lines
    lines(find(strcmp(lines, ''))) = [];

    % get values of the fields
    citation  = lines{1};
    condition = get_value(lines{2}, 'Condition');
    domain = get_value(lines{3}, 'Domain');
    modality = get_value(lines{4}, 'Modality');
    subjects = get_value(lines{5}, 'Subjects');

    coordinates = cellfun(@str2num, lines(6:end), 'UniformOutput', 0)';

    % now you can save in some global cell,
    % display or process the extracted values as you please.

end

where get_value is:
function value = get_value(line, search_for)
     [tokens, ~] = regexp(line, [search_for, '=(.+)'],'tokens','match');
     value = tokens{1};

Hope this helps.


text:
Q: Convert string element to integer (C++11) I am trying to convert string element to integer using stoi function in C++11 and using it as parameter to pow function, like this:
#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";

    //Print the number's square
    for(int i = 0; i < s.length(); i += 2)
    {
        cout << pow(stoi(s[i])) << endl;
    }
}

But, i got an error like this:
error: no matching function for call to
'stoi(__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type&)'
cout << pow(stoi(s[i])) << endl;

Anyone know what is the problem with my code?

A: The problem is that stoi() will not work with char. Alternatively you can use std::istringstream to do this. Also std::pow() takes two arguments the first being the base and the second being the exponent. Your comment says the number's square so...
#include <sstream>

string s = "1 2 3 4 5 9 10 121";

//Print the number's square
istringstream iss(s);
string num;
while (iss >> num) // tokenized by spaces in s
{
    cout << pow(stoi(num), 2) << endl;
}

Edited to account for numbers larger than single digit in the original string s, since the for loop approach breaks for numbers larger than 9.

A: stoi() works fine if you use std::string.
So,
string a = "12345";
int b = 1;
cout << stoi(a) + b << "\n";

Would output:
12346

Since, here you are passing a char you can use the following line of code in place of the one you are using in the for loop:
std::cout << std::pow(s[i]-'0', 2) << "\n";

A: Something like:
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "1 2 3 4 5";
    istringstream iss(s);
    while (iss)
    {
        string t;
        iss >> t;
        if (!t.empty())
        {
            cout << pow(stoi(t), 2) << endl;
        }
    }
}


text:
Q: How to send ACK message to client from server using NetMQ I am using NetMQ to send messages from many clients to a server which receives the messages and processes them. If I use the pub/sub pattern, I can (ab)use the subscriber socket and use it for the server and clients will be the publishers (the opposite flow, isn't it?). However, I cannot send an acknowledge message to the clients.
If I use the REQ/RESP pattern, I can use the response socket for the server and even send an acknowledge message which can be received by the client. However, if the server misses the message from client, I cannot resend the message (after waiting for a timespan), because I receive an exception

Req.XSend - cannot send another request

-- even after disconnecting the client socket and closing it (it seams that the server socket keeps track of it).
And finally, based on the documentation, I'm not sure if the Dealer/Router is the right pattern to use. As I'm pretty sure that I'm stuck in a very common situation, is there any pattern to implement this scenario using NetMQ?

A: You are stuck in a very common problem, typically called "Reliable Request-Reply" in 0MQ parlance.
There are several approaches described in the guide, the first is the "lazy pirate". In it you use a REQ/RESP socket pair as described (though REQ/ROUTER would work just as well, and probably better for more than one client). The solution is to dispose of the socket if your ACK times out and create a new one.
The guide does note that swapping a DEALER for the REQ would solve the problem, but adds having to keep track of the envelope yourself. Unless you need async send/receive on the client side for some other reason, I would follow their advice and stick with REQ/ROUTER.
A sample implementation of this pattern can be found on GitHub: https://github.com/NetMQ/Samples/tree/master/src/Pirate%20Pattern


text:
Q: Azure AD B2C change password on migration I am moving from an Asp.Net identity management to Azure AD B2C. I added the existing user through Graph API and gave the user some random password as of now in stage. Is it possible to use the old password of the user (I cannot get the existing password from my database). I remember in one of the talks of Azure AD B2C, they get the password by back tracking the request though I am not clear about it.
What is the best strategy to move to Azure AD B2C with minimum password friction?

A: I used the approach described here (Just-In-Time migration source code)

*

*pre-migrate users with auto-generated password

*create an API to check user credentials from the old user store (Microsoft Docs)

*add the API call to the Technical Profile in the SignIn Policy so every time a user tries to sign in, the credentials will be checked against the old user store (Microsoft Docs)

*add the API the privilege to change the password if the old credentials are verified (see my response to this post) or impersonate the user (if you safely stored the auto-generated passwords in somewhere secure place)

*you user credentials were updated 'just-in-time' so your user will not notice this change on the fly

A: I don't think you can get the password out from ASP.NET identity management, since the password is hashed.
As a migration strategy, you could create the Azure B2C users, from your existing authentication logic backend in ASP.NET identity management, upon successful login, since users are sending their usernames and passwords for authentication. Once all the users are moved, you can shift to Azure B2C login.


text:
Q: C - create 3D array of ints and initialize it to zeros I'm trying to create a 3D array of ints initialized to zeros each of fixed size denoted as "dim".
For example, for dim=3, it will have 27 cells for ints.
I tried this:
int ***board;
int **rows;
int *tried;
board = calloc(dim,sizeof(int**));
rows = calloc(dim*dim, sizeof(int*));
tried = calloc(dim*dim*dim, sizeof(int));
int i;
int j;
int k;
for (i=0 ; i<dim ; i++) {
    board[i] = rows + i*dim*dim;
    for (j=0 ; j<dim ; j++) {
        board[i][j] = tried + j*dim + i*dim*dim;
        }
}
for (i=0 ; i<dim ; i++) {
    for (j=0 ; j<dim ; j++) {
        for (k=0 ; k<dim ; k++) {
            board[i][j][k] = 0;
        }
    }
}

Trying to debug it, I found that it works until:
board[1][1][0] = 0

And then the program gets stuck and i just can't find the reason.
Can someone explain this please?
Thanks!

A: First about the error in your code. Compare this:
rows = calloc(dim*dim, sizeof(int*));

to this:
for (i=0 ; i<dim ; i++) {
    board[i] = rows + i*dim*dim;

The entire size of the array allocated to rows is dim*dim elements. So, already in the second iteration of this loop, you access it out of bounds. You probably meant:
for (i=0 ; i<dim ; i++) {
    board[i] = rows + i*dim;

As I already mentioned in the comment, this is not a 3D array. It mimics the usage in code by using pointers and you're using a kind-of clever trick here, so you only need 3 allocations in total. This might be a good idea under the following conditions:

*

*your dim is variable at runtime, so you can't know it in advance, and

*you have to write code for compilers that don't support VLAs1) (variable-length-arrays).

If one of this conditions is not true, it's much better to use a real 3D array. If the array doesn't have to live after leaving your function and the size isn't huge, just use a simple variable with automatic storage duration like
int board[3][3][3] = { 0 }; // possibly #define the dimension

or, for a variable dim, requiring a compiler supporting VLAs
int board[dim][dim][dim] = { 0 };

If on the other hand, the array will be huge and/or you need to return it from your function, you indeed have to allocate it dynamically. Then just use the following:
int (*board)[3][3] = calloc(3, sizeof *board); // static size
int (*board)[dim][dim] = calloc(dim, sizeof *board); // dynamic case, with VLA suppport

Also note that calloc() already sets your allocated memory to 0, so no need for looping all over it.

Side notes:

*

*with sizeof, prefer the expression form, so instead of writing
int *a = calloc(5, sizeof(int));

better write
int *a = calloc(5, sizeof *a);

this avoids errors when you later change the type of a.

*always check the return value of malloc() and friends -- they might return a null pointer (e.g. when you're running out of memory).

1) VLAs don't exist in the oldest standards C89/C90 -- they were introduced in C99 as a mandatory feature, but later made optional in C11. This allows C11 compilers to omit them, which might make sense when e.g. targeting embedded systems. In practice, you can safely assume a C11 compliant compiler supports them if it isn't special purpose.

A: I rewrote your code to show how allocation of a 3D array could look like. And as pointed out in the comments, there's no need to initialize the array to 0 since calloc does that for you. Had you used malloc the array would not have been initialized.
#include <stdlib.h>
#include <stdio.h>

#define dim (3u)

int main() {

    int x;
    int y;
    int z;

    int ***cube;
    cube = calloc(dim, sizeof(int**));

    for (z = 0; z < dim; z++) {
        cube[z] = calloc(dim, sizeof(int*));
        for (y = 0; y < dim; y++) {
            cube[z][y] = calloc(dim, sizeof(int));
        }
    }

    for (z = 0; z < dim; z++) {
        for (y = 0; y < dim; y++) {
            for (x = 0; x < dim; x++) {
                cube[z][y][x] = z + y + x;
            }
        }
    }

    for (z = 0; z < dim; z++) {
        for (y = 0; y < dim; y++) {
            for (x = 0; x < dim; x++) {
                printf("%d ", cube[z][y][x]);
            }
            printf("\n");
        }
        printf("\n");
    }

    return 0;
}

What you want to store in it is up to you, in my example I wrote the sum of the counter to each index.

A: Code below is Unlicense.
I will suggest something different. Just create a 1D array and set some boundaries to interpret it as 3D. I added some test cases for you to better visualize how it works. Do not forget to look at how easy 'calloc' call is. Here is the code:
#include <stdlib.h>
#include <stdio.h>

int getindex(int dim, int x, int y, int z) {
  return z * dim * dim + y * dim + x;
}

void printarray(int* tdarray, int dim) {
  printf("[\n");
    for (int i = 0; i < dim; i++) {
      printf("\t[\n");
      for (int j = 0; j < dim; j++) {
      printf("\t\t[");
      for (int k = 0; k < dim; k++) {
        if (k == 0) printf("%d", *(tdarray + getindex(dim, k, j, i)));
        else printf(",\t %d", *(tdarray + getindex(dim, k, j, i)));
      }
      printf("]\n");
    }
    printf("\n\t]\n");
  }
  printf("]\n");
}

int main() {
  int dim = 10;
  size_t arraysize = sizeof (int) * dim * dim * dim;

  int lookupindex = getindex(dim, 7, 5, 4); /* Numbers picked randomly */

  int* tdarray = (int*) malloc(arraysize);

  calloc(*tdarray, arraysize);

  /* Below is test code and visualizations, all magic happens above.*/

  if (*(tdarray + lookupindex) == 0) *(tdarray + lookupindex) = 7;

  printf("tdarray[x:%d, y:%d, z:%d]:\t%d\n\n", 7, 5, 4, *(tdarray + lookupindex));

  printarray(tdarray, dim);

  printf("\n\n\n\n\n\n\n\n\n\n");

  for (int i = 0; i < getindex(dim, 9, 9, 9) + 1; i++) *(tdarray + i) = i;

  printarray(tdarray, dim);

  free(tdarray);
}


text:
Q: creating an array with information contained in two other arrays  how can I buit an array using two arrays as follow:
 name = [a, b, c]
 how_many_of_each [3, 5, 2]
 to get
 my_array = [a, a, a, b, b, b, b, b, c, c]

A: name.zip(how_many_of_each).inject([]) do |memo, (x, y)|
  y.times { memo << x}
  memo
end

=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]

EDIT: Oh well, there's better, see @David Grayson.

A: This will do it in an easy to understand way:
my_array = []
name.count.times do |i|
    how_many_of_each[i].times { my_array << name[i] }
end

A: Use zip, flat_map, and array multiplication:
irb(main):001:0> value = [:a, :b, :c]
=> [:a, :b, :c]
irb(main):002:0> times = [3, 5, 2]
=> [3, 5, 2]
irb(main):003:0> value.zip(times).flat_map { |v, t| [v] * t }
=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]

A: array = ["a", "b", "c"]
how_many = [2, 2, 2]

result = []

array.each_with_index do |item, index|
  how_many[index].times { result << item }
end

print result # => ["a", "a", "b", "b", "c", "c"]

A: You can pick the one you want (just swap the comment #):
class Array
    def multiply_times(how_many)
        r = []
        #how_many.length.times { |i| how_many[i].times { r << self[i] } }
        self.each_with_index { |e, i| how_many[i].times { r << e } }
        r
    end
end

p ['a', 'b', 'c'].multiply_times([3, 5, 2])
#=> ["a", "a", "a", "b", "b", "b", "b", "b", "c", "c"]


text:
Q: Autodiscover for Windows 10 Mail not working I'm not sure if this question is best suited for here, or StackOverflow. I'm trying to get autodiscover working for Windows 10 mail (just a standard IMAP/SMTP type - not Exchange). According to the documents, I need a /autodiscover/autodiscover.xml file on autodiscover.ultranerds.co.uk. So I have:
https://autodiscover.ultranerds.co.uk/autodiscover/autodiscover.xml
Which is:
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/responseschema/2006">
<Response xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a">
<Account>
<AccountType>email</AccountType>
<Action>settings</Action>
<Protocol>
<Type>IMAP</Type>
<Server>mail.ultranerds.co.uk</Server>
<Port>993</Port>
<SSL>on</SSL>
<AuthRequired>on</AuthRequired>
</Protocol>
<Protocol>
<Type>POP3</Type>
<Server>mail.ultranerds.co.uk</Server>
<Port>995</Port>
<SSL>on</SSL>
<AuthRequired>on</AuthRequired>
</Protocol>
<Protocol>
<Type>SMTP</Type>
<Server>mail.ultranerds.co.uk</Server>
<Port>465</Port>
<SSL>on</SSL>
<AuthRequired>on</AuthRequired>
</Protocol>
</Account>
</Response>
</Autodiscover>

I can see the requests coming in on the log file:
52.125.138.6 - - [05/Jan/2023:07:03:16 +0000] "GET /autodiscover/autodiscover.json?Email=test%40ultranerds.co.uk&Protocol=ActiveSync&RedirectCount=1 HTTP/1.1" 404 1434 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:03:16 +0000] "POST /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:03:16 +0000] "POST /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:03:16 +0000] "GET /autodiscover/autodiscover.xml HTTP/1.1" 301 162 "-" "-"
52.125.138.6 - - [05/Jan/2023:07:03:16 +0000] "GET /autodiscover/autodiscover.xml HTTP/1.1" 301 162 "-" "-"

When I try and add the account in Windows Mail, I just get:

What am I missing? I've even tried adding DNS SRV records, as apparently that works in some programs? (I wish they all just had a fixed standard they all used!)
UPDATE: After disabling auto-https redirection, I get:
52.125.138.6 - - [05/Jan/2023:07:37:44 +0000] "GET /autodiscover/autodiscover.json?Email=test%40ultranerds.co.uk&Protocol=ActiveSync&RedirectCount=1 HTTP/1.1" 404 1434 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:37:44 +0000] "POST /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:37:44 +0000] "POST /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "OutlookMobileCloudService-Autodetect/1.0.0"
52.125.138.6 - - [05/Jan/2023:07:37:44 +0000] "GET /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "-"
52.125.138.6 - - [05/Jan/2023:07:37:44 +0000] "GET /autodiscover/autodiscover.xml HTTP/1.1" 200 305 "-" "-"

I guess the 2 versions are http:// and https:// calls - but it still doesn't accept the autodiscover params :(
UPDATE 3: Still no joy. I'm even trying it via the DNS SRV records - but it still doesn't seem to take the values:

So infuriating!


text:
Q: Windows C++ delegation with design implications I have a multithreading C++ design question for Windows. Suppose I have a   C++ class as follows:
class CCamera_AxisNew : public CCamera_IPBase64 and suppose in the base class, CCamera_IPBase64, implementation of PTZThreadProc(..) , I read commands from a queue and asynchronously send PTZ commands only through either

*

*the object pointer indirectly, IPTZControl->SetProperty(..) where the object pointer IPTZControl = new CCamera_AxisNew  or other similar constructors or

*directly through this->SetProperty()
The method PTZThreadProc(..) is spawned on a separate thread.
Also, in the class CCamera_IPBase64, I can bypass the PTZThreadProc(..) which runs on a separate thread by synchronously sending non-PTZ commands through either

*

*the object pointer indirectly,  IPTZControl->WriteCamera(...), or

*directly through this->WriteCommand(..).

The client program sends requests through a REST endpoint to  an CCamera_IPBase64 object which uses a main thread to receive the request and places only PTZ commands on a queue.
My question is it better to use  delegation IPTZControl->SetProperty(..) or avoid delegation such as this->SetProperty()
Any help is greatly appreciated.

A: It is better to avoid delegation by using this->SetProperty() and taking advantage of inheritance since it avoids extra redundant code required by the delegation design pattern.


text:
Q: How to make MobX update the component when observable is not used in the render method? After switching from Redux to MobX for React I'm starting to extremely like MobX. It's pretty awesome.
MobX has a certain behavior where it won't update component if the provided store observable is not used in render. I think generally that's a pretty great behavior that makes components render only when something actually changed.
But... I do encountered couple of cases where I do not want or need to use MobX observable inside render method and in such cases my this.props.store with MobX store won't get updated.
And in such cases, as a workaround, I just reference the observable in the render method, but I don't think that's a very clean approach, and I'm wondering if there's a cleaner way to do that?
This component code should explain even more what I'm exactly asking about.
It's a component that changes body overflow style based on a MobX observable that I have in my store.
/*------------------------------------*\
  Imports
\*------------------------------------*/
import React from 'react';
import connectStore from 'script/connect-store';
import addClass from 'dom-helpers/class/addClass';
import removeClass from 'dom-helpers/class/removeClass';

/*------------------------------------*\
  Component
\*------------------------------------*/
class Component extends React.Component {

  constructor(props) {
    super(props);
    this.constructor.displayName = 'BodyClassSync';
  }

  componentDidMount() {
    this.checkAndUpdateMuiClass();
  }

  componentDidUpdate() {
    this.checkAndUpdateMuiClass();
  }

  checkAndUpdateMuiClass() {

    // This place is the only place I need latest MobX store...
    if (this.props.store.muiOverlay) {
      addClass(window.document.body, 'mod-mui-overlay');
    }

    else {
      removeClass(window.document.body, 'mod-mui-overlay');
    }

  }

  render() {

    // This is my workaround so the componentDidUpdate will actually fire
    // (with latest and updated store)
    // when the 'muiOverlay' observable changes in the MobX store
    // Is there any cleaner/better way to do this?
    this.props.store.muiOverlay;

    // This component doesn't and shouldn't render anything
    return null;

  }

}

/*------------------------------------*\
  Export
\*------------------------------------*/
const ComponentWithStore = connectStore(Component);
export default ComponentWithStore;

(Note: I don't use @decorators, I connect store using ES5 syntax in the connectStore function. And it would be awesome if solution to this would be also in ES5.)

A: You could use an autorun in componentDidMount and dispose the listener in componentWillUnmount so that you don't have to reference it in the render method.
class Component extends React.Component {
  constructor(props) {
    super(props);
    this.constructor.displayName = 'BodyClassSync';
  }

  componentDidMount() {
    this.dispose = autorun(() => {
      const { muiOverlay } = this.props.store;

      if (muiOverlay) {
        addClass(window.document.body, 'mod-mui-overlay');
      } else {
        removeClass(window.document.body, 'mod-mui-overlay');
      }
    });
  }

  componentWillUnmount() {
    this.dispose();
  }

  render() {
    return null;
  }
}

Since you are not really doing anything in this component, you could put this autorun directly in your store as well.

A: Not sure how I missed it, but thanks to @Tholle I've reread the "Reacting to observables" section in the MobX docs and found out the reaction helper was the most suitable solution for me.
While, the reaction was the most fitting for the exact problem I had. The autorun and when helpers are pretty similar in the function and I probably could use them for my use case too.
https://mobx.js.org/refguide/autorun.html
https://mobx.js.org/refguide/when.html
https://mobx.js.org/refguide/reaction.html

This is the code example that shows how to use reaction for anyone that just wants quick copy+paste:
componentDidMount(){
  this._notificationsReactionDispose = mobx.reaction(
    () => this.props.store.notifications,
    (notifications, reaction) => {
      ... the code that runs when "notifications" in my store change
    }
  );
}

componentWillUnmount() {
  this._notificationsReactionDispose();
}


text:
Q: UIDocumentPickerViewController allows selecting a file the first time the app is run, but not subsequently My app, when run, creates a json document (using a UIDocument subclass) in its document directory. And then, when opening up the UIDocumentPickerViewController to select a file, if the app has written a new file, the behaviour is as expected.
However, if I run the app again (and overwrite the last created file), the delegate method didPickDocumentsAt doesn't get called, unless I browse around for a few seconds.
What am I missing here?
@IBAction func showDocumentPicker() {
    let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeJSON as String], in: .import)
    documentPicker.allowsMultipleSelection = false
    documentPicker.delegate = self
    self.present(documentPicker, animated: true, completion: nil)
} //this function is in the initial definition of the class and is connected to a UIBarButton

extension BudgetExportViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print("selected document: \(urls.first)")
        print("555555555555555555555555555555")
        //document = BudgetExportDocument(fileURL: urls.first!)
//                CFURLStartAccessingSecurityScopedResource(urls.first! as CFURL)
//                let documentData = try? Data.init(contentsOf: urls.first!)
//                let json = try? JSONDecoder().decode(BudgetExportData.self, from: documentData!)
//                budgetThisMonth = json
//                print("Budgetthismonth")
//                print(budgetThisMonth)
//                CFURLStopAccessingSecurityScopedResource(urls.first! as CFURL)
    }
}

A: Apparently, the problem was the fact that I was overwriting the same file so many times. Now, if a file with the same name exists, it won't write over it and the UIDocumentPickerViewController behaviour is as expected.


text:
Q: unable to install jscodeshift Unable to install jscodeshift.
> npm i jscodeshift -g
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @babel/helper-string-parser@^7.19.4.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of '@babel/types'
npm ERR! notarget

any suggestions for getting past this?
I tried installing the @babel/helper-string-parser@^7.19.4 but to no avail. The package is not available.


text:
Q: The explanation for the need to compute (rather then optimize) the posterior of latent variables The most common usage of the variational inference looks like to be in computing the marginal distribution $P(X)$ in the denominator of the Bayes formula when computing the posterior probability of the hidden variables, $P(Z|X)$. This is likely a dumb question but I don't understand why we need to compute $P(Z|X)$. Why don't we just optimize $P(Z|X)$ instead (find $Z$ that maximizes $P(Z|X)$), in which case we don't need to exactly compute $P(X)$ since it does not depend on the value of $Z$. In that alternative way, we can just optimize the numerator $P(X|Z)P(Z)$ as in the regular MAP (maximum aposteriori) estimation of the parameters ($\theta$) when we don't have any hidden variables $Z$. What is the difference in those two problems (estimating parameters vs. hidden variables) such that one can go with optimizing through MAP while the other needs sophisticated tools for computing (or approximating) $P(Z|X)$?

Edit: After a little more search, I learned that the MAP is not really full Bayesian, since it does not learn the actual posterior distribution, but it instead gets a point estimate of the parameters through maximizing posterior probability. Then I think what variational inference does is real Bayesian. But still, I am not sure whether I understand the need for getting the distribution itself. Is it to get a better sense of the parameter space?

A: In many cases getting the distribution is more useful than a point estimation. Say I am an interviewer and I ask each candidate to do a list of questions, then $X$ (observed) could be the number of question the candidate answered correctly, and $Z$ (latent) is whether the candidate is qualified or not.
Candidate A has correctly answered 4 out of 5 questions, and B answered all 5 questions. If I just do a point estimation (MLE/MAP), the most probable value of $Z$ for A and B might be the same $$argmax_ZP(Z|X_A)=argmax_ZP(Z|X_B)=qualified$$
If I can know the full posterior distribution, then I get $$P(Z=qualified|X_A)<P(Z=qualified|X_B)$$

A more common situation would be there's another variable $Y$ that depends on $Z$, if we know the full distribution $p(Z|X)$ we get $$p(Y|X)=\int p(Y|Z)p(Z|X)d_Z$$
which we can't know given only a point estimation of $Z$.
For instance in the setting of recursive filtering algorithms, $Z$ is the state at time $t$, $X$ is the measurement at time $t$, and $Y$ is the state at time $t+1$.

Another example that might be interesting to illustrate the connection is the EM algorithm for Gaussian mixture models, in wich case $X$ is the observed data, $Z$ is the discrete latent variable that denotes which Gaussian component a data point belongs to.
EM itself is an optimization (point estimation) algorithm for the model parameters $\theta$. In the E step we assign each data point a probability of belonging to each component, which is to compute $p(Z|X)$. in the M step we optimize $\theta$ based on $p(Z|X)$.
If in the E step we do a point estimation (hard assignment) instead, then we are going from EM for GMM to K-means clustering (assuming the same identity covariance matrix).

I'm not much a statistics people, please correct me if I missed any important point. :]


text:
Q: What happens when we theta join or cross 2 relations with common attributes? Relation 1 (r1):
ID | Name
1    John
2    Doe
3    Foo

Relation 2 (r2):
ID | Name
4    Johnny
5    Doey
6    Fooey

What will r1 theta join(r1.ID = r2.ID) r2 result in?
What will r1 cross r2 result in?
I'm just asking whether the resulting relations should change the names of the attributes to something else because there are 2 of each.

A: In relational algebra, product (cross join) is usually understood to be a special case of natural join where the joined relations happen to have no attributes in common. So it doesn't make sense to say A x B if A and B have common attributes. If A and B have attributes in common then A x B either means A ⋈ B or it means a mistake has been made and your DBMS or interpreter probably ought to report an error.
Theta join is a shorthand for natural join followed by a restriction. It must be preceded by a rename of some attribute(s) if the attributes in the theta expression would otherwise have the same names.


text:
Q: coalesced read short integer cuda say I want to load an array of short from global memory to shared memory. I am not sure how coalescing works here. On best practice guide, it says on device of compute capability 1.0 or 1.1, the k-th thread in a half warp must access the k-th word in a segment aligned to 16 times the size of the elements being accessed.
If I understand it correctly, in case I break my data into 32bytes (16 shorts) segments, thread id 0, 16, 32 ... has to access first element of each segment? do i need to consider 64bytes alignment or 128 bytes alignment as well? I have a gts 250, so i guess this is important. Advices are welcomed. thanks.

A: According to Section G.3.2.1 of the CUDA Programming Guide short will not coalesce on Compute Capability 1.0 and 1.1 devices under any circumstances.  Specifically, it states:

The size of the words accessed by the
  threads must be 4, 8, or 16 bytes

You can however use vector types such as short2, short4, or even short8 to get coalesced access.  The coalescing rules for these types is spelled out in Section G.3.2.1 as well.  However, as far as coalescing is concerned a short2 is just like a 32-bit int.
FWIW, devices with Compute Capability 1.3 or greater handle types like char and short much better.  Reading chars on a 1.3 device might give you as much as ~60% of peak memory bandwidth vs. ~10% of peak memory bandwidth on a 1.0 or 1.1 device.


text:
Q: 2sxc - access url path id in razor code I know how to access url path id for some detail view in visual query designer.
But what is the right way to get this value in view razor script. I know that I can manualy parse path, but I am interested if there is already some function to do that?

A: Seems like you already found the answer :).
DNN will map all parameters after the page-url in the pattern /key/value/key/value/key/value
so it will then always be available in the Request.QueryString["key"]


text:
Q: Web pages download to desktop instead of load? I am in the middle of migrating a Magento site over to a new server. I followed instructions provided in this video to a T-
https://www.youtube.com/watch?v=OiWmZFxrZns
However, now when I try to access the transferred site, any pages just download to my desktop instead of displaying in browser.
I have never encountered this before. Have you? Does anyone know what this could be? I apologize if this is too broad, but I'm wondering if maybe it's something I have to change in a file like .htaccess or something
Help!

A: As I suspected- it was the .htaccess file. I fixed the issue by deleting the file altogether, though I'm sure I want only able to get away with that because I migrated everything into a subdirectory to begin with rather than the root. I am unsure if this will still be a viable solution for those experiencing the same problem in a root directory.


text:
Q: SNMP Trap receipt and processing on Windows Server 2003 Without installing any extra software or monitoring applications, can I configure Windows Server 2003 to receive SMNP Traps from our UPS and, based on the message, perform actions (send shutdown commands to non-key servers, initiate scripts, etc).
I've got the SNMP Service and the SNMP Trap Service running on the server. Port 123 is not listening (I've got to figure out if that is a GP security policy pushed from higher-up IT (is that supposed to be TCP or UDP?)). The Community Name is set. And our APC Symmetra system is ready for me to tell it where to send the SNMP Traps.
Using already on the system tools (small executables and plugins are usually OK depending on where they come from), is this possible?

A: You're going to need additional software.
The SNMP trap receiver in the "SNMP Trap Service" in Windows Server 2003 can receive traps from other machines but can only forward them to another destination. It's less of a "trap receiver" and more of a "trap proxy".

A: I'm using the Solar Winds "Kiwi Syslog" product Free version.  There is also a commercial version.
Details and downloads from:
http://www.kiwisyslog.com/kiwi-syslog-server-overview/
Collects SNMP traps in addition to Syslog type messages.
Easy to set up.  You can configure alerts etc.


text:
Q: terminology: Memory leak When I hear the term memory leak by that I mean a bug in a program that doesn't cause any problems except that it doesn't free memory resource and if it continuously does that it can eat a lot of memory, hurting system performance and in the worst case crash the program (or an other program, if the OS decides to choose to kill that one).
But now in this comments section of this question the upvotes made me think whether that's the whole meaning of the term. I previously always saw used it in that meaning.
https://stackoverflow.com/questions/7451437/is-this-a-mem-leak-in-main
So, would you call something a simple memory leak that crashes a program by some other side-effect or causing a dead-lock by not freeing a lock?
Update - Note: unfortunately some admin deleted the comment section there so I cannot refer to that discussion anymore :/
Basically I said that a memory leak is harmless except that it eats up memory (and consequently on the long term in that respect can be harmful, crashing the app/system). They said that's not true, with C++ RAII it can cause serious problems. - Yes, if you don't delete an object with some important code in the destructor that can cause problems, but in my vocabulary that's a major bug and not a memory leak.

A: The quintessential memory leak would be exactly what you described, the failure to free some memory the process had allocated. The consequences would normally be that the program gradually grows in size while it's running, with possible secondary effects due to that. Subsequent memory allocations might fail or the system might misbehave due to the wasted resources.
However, a problem can be accurately described as a memory leak so long as it does in fact leak memory. It can also do other things that are potentially more serious. For example, if you fail to close a standard I/O stream, that's a memory leak because memory associated with the stream will be leaked. However, it can also run the process out of file descriptors or perhaps cause a subsequent stream open to fail because of a limit on the number of standard I/O streams.

A: It depends.  Certainly the program could have crashed because of a memory leak. But I wouldn't call all crashes memory leaks.  A memory leak has a very clear definition.
An application crash could be caused many different things.

*

*Unhandled Exception

*Memory Leak

*Resource Leak

*Deadlock

*Other (bug in code)

At the time of the crash one would have to take a crash/memory dump and use something like Windbg to analyze the state of the code at the time of the crash to determine if it was a memory leak, deadlock, bug, etc.
A memory leak is simply not freeing memory after you are finished with it.  This can cause a crash if the resource limits are met as you have noted.
A resource leak is not freeing the resource after you are done with it.  An example could be opening a database connection and not closing it after you are finished.
Deadlocks are different than leaks, because leaks can go undetected and could be benign if system resources are not consumed. Deadlocks are a condition which do not build up over time.

A: A related meaning of "memory leak" applies to languages that use garbage collection.  There, memory is supposed to be leaked, but if you fail to do so, it's the same problem.

A: Memory Leaks happen If you fail to delete dynamically allocated memory. Tracking
down memory leaks is one of the most time-consuming (and tedious) aspects of programming in
unmanaged environments.
A simple example of memory leak can be following.
int main(void)
{
    /* this is an infinite loop calling the malloc function which
     * allocates the memory but without saving the address of the
     * allocated place */
   while (malloc(50)); /* malloc will return NULL sooner or later, due to lack of memory */
   return 0;  /* free the allocated memory by operating system itself after program exits */
}

A: http://en.wikipedia.org/wiki/Memory_leak#Consequences

would you call something a simple memory leak that crashes a program by some other side-effect

Memory leaks can cause random bugs since memory may be assigned unexpected values.

causing a dead-lock by not freeing a lock?

Dead locks can be caused by memory which has been assigned unexpected values.
Further reading on this topic:

*

*http://en.wikipedia.org/wiki/Memory_pool

*http://en.wikipedia.org/wiki/Stack_overflow


text:
Q: prism switch between views in the same region I have a region named "ActiveModule" and want to re-use it with different views, for example you press the search button and I show the search view in there, etc. etc.
The only way I can ATM do that is to deactivate all the active views in that region and then activate the view I like, this is a bit dirty, is there a "viewManager" or something similar I can use?

A: If your region is a ContentControl or derives from ContentControl, then there can only be one active view at a time, and you only need to activate the search view on the region.

A: Did you consider to use a type of contentControl that is able to show multiple views?
For example you can use a TabControl like this:
<TabControl Name="MainRegion" Regions:RegionManager.RegionName="MainRegion"/>

You can now add more than one view to the region. Use INavigationAware and IActiveAware interfaces from Prism to be able to do navigation on the views (activate them, find the correct view etc.).

A: If you are using a IRegionManager, you can remove all of the views whose types you recognize and then add your own.
    foreach (var view in _regionsManager.Regions["MyRegion"].Views.ToArray())
    {
        if (view is MyType ||
            view is MyOtherType)
            _regionsManager.Regions["MyRegion"].Remove(view);
    }

    _regionsManager.AddToRegion("MyRegion", typeof(MyView));

Its by no means ideal, but it works. :)

A: To my knowledge what you are doing is the only way, theoretically in SCSF the top most view was activated by the framework. You could create ur own ViewManager or a ShowViewService equivalent to get this done. MAtter of fact, thats what i have done!

A: Not sure how you laid out your framework but if you are using navigation related framework you can simply call
regionManager.RequestNavigate(RegionNames.MainContentRegion, new Uri("your target view" + parameters, UriKind.Relative));

the above line will take care of deactivating other views in the region.
Otherwise if you do view discovery or view injection you can use the approach here
region.Activate(view);


text:
Q: MySQL Search w/ Ordered Wildcards, and Extracting Their Values Is it possible to do a wildcard search, and extract the values of the wildcards and put them into a MySQL result? Preferably, I'd also like to label the wildcards. Continue reading to see what I mean.
EXAMPLE:
Consider a database table with the following structure.
+----+-------------------+
| id | content           |
+========================+
| 1  |  %1.%2.%3         |
+----+-------------------+
| 2  |  Hey %name.       |
+----+-------------------+

First, note that this is just an example. I am not storing multiple values in a single database field. See here: Is storing a delimited list in a database column really that bad?
Instead, I want to know if it is possible to have wildcards in a database, and then compare that with user input. In other words, I would like to take user input, such as 2.bla.^7 or similar, and then return that respective row--%.%.%. I would then like to take those wildcards, and return them as part of the MySQL result. Below is an example PHP mysql_fetch_assoc() result based on what I'm looking for. The result obviously doesn't need to be laid out exactly like this, but this is the sort of result that I'm looking for.
EXAMPLE:
/************************
 * Input:    2.bla.^7   *
 ************************/
Array
(
    [0] => Array
    (
        [id] => 1,
        [content] => %1.%2.%3
    ),

    [1] => Array
    (
        [1] => 2,
        [2] => bla,
        [3] => ^7
    )
)

/************************
 * Input:   Hey Matt.   *
 ************************/
Array
(
    [0] => Array
    (
        [id] => 2,
        [content] => Hey %1.
    ),

    [1] => Array
    (
        [name] => Matt
    )
)

I understand that what I'm looking for is likely fairly complicated, or specialized for my unique case. If you can point me in the right direction, I would hugely appreciate it! I don't even know if this is possible--if it's not, an alternative solution would be greatly appreciated! However, I want the database structure to stay as close to the same as possible.
Thank you so much!

A: Don't you just want to do:

SELECT * FROM patterns WHERE 'user input' LIKE content;

See it on sqlfiddle.

A: Indeed there is no ready-to-go solution. Here is what I would do:
1) Add 3 special columns like_pattern, regexp_pattern and placeholders. Their values are calculated from the column content either in PHP before loading data into the table, or in BEFORE INSERT/UPDATE TRIGGERs.

*

*like_pattern VARCHAR(N) - LIKE pattern for reverse search

*regexp_pattern VARCHAR(N) - Regexp pattern for extracting parts later in PHP

*placeholders VARCHAR(N) - Comma-separated list of placeholder names

Here is the example:
+----+-------------+--------------+--------------------+--------------+
| id | content     | like_pattern | regexp_pattern     | placeholders |
+====+=============+==============+====================+==============+
| 1  |  %1.%2.%3   | %.%.%        | ^(.*)\.(.*)\.(.*)$ | 1,2,3        |
+----+-------------+--------------+-+------------------+--------------+
| 2  |  Hey %name. | Hey %.       | ^Hey (.*)\.$       | name         |
+----+-------------+--------------+--------------------+--------------+

2) For a given string search record using like_pattern:
SELECT * FROM patterns WHERE 'Hey Nathanael.' LIKE like_pattern;

Be aware that simple index can not speed up this query because we perform a reverse search, so depending on how big your table is you probably will need a different solution.
3) Match the string 'Hey Nathanael.' against returned regexp_pattern using PHP's preg_match() or ereg(). You will get placeholder values.
4) Combine them with placeholder names from the column placeholders.
That's it.


text:
Q: How can you prove that a function has no closed form integral? In the past, I've come across statements  along the lines of "function $f(x)$ has no closed form integral", which I assume means that there is no combination of the operations:

*

*addition/subtraction

*multiplication/division

*raising to powers and roots

*trigonometric functions

*exponential functions

*logarithmic functions

which when differentiated gives the function $f(x)$. I've heard this said about the function $f(x) = x^x$, for example.
What sort of techniques are used to prove statements like this? What is this branch of mathematics called?

Merged with "How to prove that some functions don't have a primitive" by Ismael:
Sometimes we are told that some functions like $\dfrac{\sin(x)}{x}$ don't have an indefinite integral, or that it can't be expressed in term of other simple functions.
I wonder how we can prove that kind of assertion?

A: Have you ever heard of Galois theory? It is a theory that studies the solutions of equations over fields.
As it turns out, there is a special type of Galois theory called Differential Galois theory, which studies fields with a differential operator on them:
http://en.wikipedia.org/wiki/Differential_galois_theory
Using this theory, one can prove that functions like $\frac{\sin(x)}{x}$ and $x^x$ don't have an indefinite integral.

A: The techniques used for indefinite integration of elementary functions are actually quite simple in the transcendental (vs. algebraic) case, i.e. the case where the integrand lies in a purely transcendental extension of the field of rational functions $\rm\mathbb C(x)$. Informally this means that the integrand lies in some tower of fields $\rm\mathbb C(x) = F_0 < \cdots < F_n = \mathbb C(x,t_1,\ldots,t_n)$ which is built by adjoining an exponential or logarithm of an element from the prior field, i.e $\rm\  t_{i+1} =\: exp(f_i)\ $ or $\rm\ t_{i+1} =\: log(f_i)\ $ for $\rm\ f_i \in F_i$ where $\rm t_{i+1}$ is transcendental over $\rm F_i\:.\ $ For example $\rm\ exp(x),\ log(x)\ $ are transcendental over $\rm\mathbb C(x)$ but $\rm\ exp(2\ log(x)) = x^2\ $ is not. Now, because $\rm\ F_{i} = F_{i-1}(t_{i})$ is transcendental it has particularly simple structure, viz. it is isomorphic to the field of rational functions in one indeterminate $\rm\:t_i\:$ over $\rm\ F_{i-1}\ $. In particular, this means that one may employ well-known rational function integration, techniques such as expansions into partial fractions. This, combined with a simple analysis of the effect of differentiation on the degree of polynomials $\rm\  p(t_i)$, quickly leads to the fundamental result of Liouville on the structure of antiderivatives, namely they must lie in the same field $\rm F$ as the integrand except possibly for the addition of constant multiples of log's over $\rm F$. With this structure theorem in hand, the transcendental case reduces to elementary computations in rational function fields. This transcendental case of the algorithm is so simple that it may be  easily comprehended by anyone who has mastered a first course in abstract algebra.
On the other hand, the full-blown algebraic case of the algorithm requires nontrivial results from the theory of algebraic functions. Although there are some simple special case algorithms for sqrt's and cube-roots (Davenport, Trager) the general algorithm requires deep results about points of finite order on abelian varieties over finitely generated ground fields. This algebraic case of the integration algorithm was discovered by Robert Risch in 1969 - who did his Berkeley Ph.D. on this topic (under Max Rosenlicht).
For a very nice introduction to the theory see Max Rosenlicht's Monthly paper, available from JSTOR and also here. This exposition includes a complete proof of the Liouville structure theorem along with a derivation of Liouville's classic criterion for $\rm\int f(z)\: e^{g(z)}\: dz\ $ to be elementary, for $\rm\: f(z),\: g(z)\in \mathbb C(x)$. For algorithms see Barry Trager's 1984 MIT thesis and Manual Bronstein: Symbolic Integration I: Transcendental Functions.
Disclaimer: I implemented the integration algorithm in Macsyma (not the much older Maxima) so, perhaps due to this experience,  my judgment of simplicity might be slightly biased. However, the fact that the basic results are derived in a handful of pages in Rosenlicht's paper yields independent evidence for such claims.

A: Surprisingly, there is a procedure for determining this, called the Risch Algorithm. However, it is apparently very complicated to implement, and furthermore it is not a true algorithm: if the input does have an anti-derivative, it can find it in a finite amount of time, but demonstrating there is no anti-derivative requires solving the constant problem, which can fail to halt. (In that case, probabilistic methods can be used.)

A: A key result in this area is a theorem by Liouville. You'll find easy expositions of this result in the references below:

*

*Antoine Chambert-Loir. A Field Guide to Algebra, last chapter, Springer, 2005.

*M Rosenlicht. Integration in finite terms, Amer.    Math. Monthly,
    (1972), pp 963-972.

*Toni Kasper. Integration in finite
terms: the Liouville theory. Math.
Mag.,  53(4):195–201, 1980.

*D.    H. Potts. Elementary
integrals. Amer.    Math. Monthly,
63:545–554, 1956.

*A. D. Fitt and G. T. Q. Hoare. The closed-form integration of arbitrary functions,
The Mathematical Gazette, Vol. 77, No. 479 (Jul., 1993), pp. 227-236

*Elena Anne Marchisotto and Gholam-Ali Zakeri. An invitation to integration in finite terms, The College Mathematics Journal, Vol. 25, No. 4 (Sep., 1994), pp. 295-308

*D. G. Mead. Integration, The American Mathematical Monthly, Vol. 68, No. 2 (Feb., 1961), pp. 152-156

A: Brian Conrad explains this in the following:
Impossibility theorems on integration in elementary terms (archived PDF)

A: It is a theorem of Liouville, reproven later with purely algebraic methods, that for rational functions $f$ and $g$, $g$ non-constant, the antiderivative of
$$f(x)\exp(g(x)) \, \mathrm dx$$
can be expressed in terms of elementary functions if and only if there exists some rational function $h$ such that it is a solution of
$$f = h' + hg'$$
$e^{x^2}$ is another classic example of such a function with no elementary antiderivative.
I don't know how much math you've had, but some of this paper might be comprehensible in its broad strokes:
https://ksda.ccny.cuny.edu/PostedPapers/liouv06.pdf
Liouville's original paper:

Liouville, J. "Suite du Mémoire sur la classification des Transcendantes, et sur l'impossibilité d'exprimer les racines de certaines équations en fonction finie explicite des coefficients." J. Math. Pure Appl. 3, 523-546, 1838.

Michael Spivak's book on Calculus also has a section with a discussion of this.

A: The general pattern is always the same: (1). Study properties of derivatives of closed form functions. (2). If your function $f(x)$ fails one of those properties, then it has no closed form antiderivative.
Here is how to get started: First, consider derivatives of rational functions. Notice that their pole orders at finite points are never 1 (more generally: the residue is 0). If $f(x)$ fails this property, then you know that its antiderivative can not be a rational function. Sounds simple, but the surprising part is that this can be generalized quite easily to logarithmic extensions (handling exponential extensions in Risch algorithm is more involved, and handling algebraic extensions is more involved still).
Take for example a function $f(x) \in \mathbb{C}(x, \ln(x))$. For each irreducible factor $p \in \mathbb{C}(x)[ \ln(x) ]$ in the denominator of $f(x)$, you can define a corresponding residue (which will be algebraic over $\mathbb{C}(x)$). A necessary condition for $f(x)$ to have an elementary anti-derivative is for these residues to be constants  (in the more basic case, $f(x) \in \mathbb{C}(x)$, residues are always constants, and thus, rational functions always have an elementary antiderivative). See "Liouville's theorem (differential algebra)" on wikipedia for more.


text:
Q: react-native, Android Freshchat isFreshchatNotification not handling firebase remote message I'm trying to integrate react-native-freshchat-sdk to react native app, but when firebase remote message is coming, freshchatNotification is 0, but it should be 1. Even if I pass notification to Freshchat.handlePushNotification nothing happens. I assume Freshchat.handlePushNotification should navigate the user to the conversation
Actual result

*

*freshchatNotification is 0 if it is fcm notification

*Freshchat.handlePushNotification(notification) does nothing

Expected result:

*

*freshchatNotification should be equal 1 if it is fcm notification

*Freshchat.handlePushNotification(notification) should navigate the user to the chat

import messaging from '@react-native-firebase/messaging'
import { Freshchat} from 'react-native-freshchat-sdk'
//...
useEffect(() => {
const unsubscribe = messaging().onMessage(notification => {
Freshchat.isFreshchatNotification(notification, (freshchatNotification) => {
    Freshchat.handlePushNotification(notification);
        if (freshchatNotification) {
            Freshchat.handlePushNotification(notification);
        } else {//...}
})
});
return unsubscribe
}, [])

See push notification payload below:

A: Faced similar issue, worked by passing notification.data instead of direct notification object to Freshchat
useEffect(() => {
  const unsubscribe = messaging().onMessage(notification => {
  Freshchat.isFreshchatNotification(notification.data, (freshchatNotification) => {
    Freshchat.handlePushNotification(notification);
        if (freshchatNotification) {
            Freshchat.handlePushNotification(notification.data);
        } else {//...}
  })
  });
  return unsubscribe
}, [])


text:
Q: Automatic sprite animation with Cocos2d I have a class representing my character in Cocos2d.
I've exported the spritesheet + .plist file.
The character has multiple animations.
The frames are simply called "Character_1.png".
Up to four. This is the basic walking animation.
In many sprite animation tutorials I found this sample code, which loops though the sprite frame cache and just adds it to an array so you can animate it:
for(int i = 1; i <= 4; ++i) {
    [animationFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"Character_%d.png", i]]];
}

However, because most of my sprites will be animated just like this, I'd like to delegate this to an super class.
I thought about calling it something like
spriteWithAnimations:(NSArray *)animationNames

and then I'd look though them, just like in the example above.
So as a parameter in the array I'd get a string @"Character_%d", I'd make a while loop and check if the file exists, and while so, I'd add it to the array.
The only problem is, that I cannot check if a frame "Character_05.png" exists, because CCSpriteFrameCache has no such method.
How is this usually solved?

A: If CCSpriteFrameCache returns nil for a given frame name you know it doesn't exist. Not elegant but it works.


text:
Q: Change file input button's Text when the user chooses his/her file I have this file input:
<input id="some_file_input" type="file"  name="some_file" class="custom-input-thing" data-buttonName="btn-primary" data-icon="true">

i hide the text that comes with the button, the one that says "no file selected", just becouse of the "looks":
input[type=file] {
color: transparent;
display: block;

}
Is there a way to change the text of the file input when the user selects the file to upload??
Thanks in advance for any help.

A: Use the inputFileText plugin for this
https://github.com/datchung/jquery.inputFileText
Load this file after jQuery
<script src='jquery-input-file-text.js'></script>

Here is your jQuery code.
$("input[type=file]").on("change", function() {
    $(this).inputFileText( { text: 'Uploaded' } );
});

If a file is updated, the value of input[type=file] will be changed. We use the change event handler. Then we include the plugin function for changing the text.


text:
Q: jQuery - Pass Event Listener's Selector to Plugin I am making my own simple jquery plugin.
But I'm in the beginning stages, and I'm only focusing on things that help me with debugging my custom plugin.
At this point I'm firing an event listener, and the element is an
The plugin is only meant to Identify another element, nothing fancy.
index.html
Click Me

   Testing table cell

identifyElement.js
(function ($) {
    $.fn.extend({
        identifyElement: function(options) {

                    // goal 1:  (identify the type of element)
                    console.log( $.type($(this)) ); // returns "object"

                    // goal 2:  (what's the element that fired off the 'click' method?

        }
    })//eof extend()
})(jQuery);

This is as far as I got.
For all you hard-core debuggers, you can see I'm working to know as much as possible about the elements I'm working with.  (totally helps with future projects)
Goal 1:
In this case, I'd love to know that #randomElement is an html table.  If it were something else, then obviously I'd like to print to the console what it is, or if it's not recognized.
-you can see console.log( $.type($(this)) );  which returns "object" but I'm wanting it to return "table"
Goal 2:
I clicked an href to fire the event and trigger the plugin to do it's magic.  I'd love to print to the console that information too.  (I never know when I may need to know what spawns an event)
Again, I'm not building a jquery plugin to do anything except practice debugging and identifying elements I'm working with.
Can anyone help me with my 2 unfinished goals?

A: You could use the .is() method to look for a specific tag.
If you pass the event object that jquery gives in the click() callback, event.target will be the element that triggered the event.

A: Goal 1:
this[0].tagName

will return "TABLE".
Goal 2: I don't think you can get the A element in your plugin. If you want this, you need to require that the caller pass this or the event object as a parameter.

A: here is a working fiddle for goals 1 and 2. I dropped your options parameter for now, replaced with event param
http://jsfiddle.net/Q5cV7/2/
 $("a#funhref").on('click', function (event) {

    $("#randomElement").identifyElement(event);

});

(function ($) {
$.fn.extend({
    identifyElement: function(event) {

    // goal 1:  (identify the type of element)
    console.log( this[0].tagName );

     // goal 2: what's the element that fired off the 'click' method?
    console.log( event.target );
      }
   })//eof extend()
   })(jQuery);

UPDATE:
here is a version using your options param:
http://jsfiddle.net/Q5cV7/4/
 $("a#funhref").on('click', function (event) {

   $("#randomElement").identifyElement({event : event});

});

 (function ($) {
 $.fn.extend({
    identifyElement: function(options) {

    // goal 1:  (identify the type of element)
    console.log( this[0].tagName ); // returns "object"

   // goal 2:  (what's the element that fired off the 'click' method?
   console.log( options.event.target );
    }
 })//eof extend()
 })(jQuery);


text:
Q: Enroll visitor in Sitecore Engagement Plan programmatically I would like to Enroll a Sitecore visitor in a specific state of an engagement plan through code. Can't find how to do this in the documentation.
Anyone?

A: Found it through the help of the great Sitecore Support staff.
Sitecore.Analytics.Automation.VisitorManager.AddVisitor(userName, stateId);

You have to reference "Sitecore.Automation.MarketingAutomation.dll" in your project.

A: In Sitecore 8.1 Automation API has changed and now is using AutomationStateManager to manage the engagement plans from code.
automationContext.MoveToEngagementState(planId, stateId);

A: If the contact is not in the Engagement Plan, for Sitecore 8.1 you can use this code to enroll it:
 AutomationStateManager manager = Tracker.Current.Session.CreateAutomationStateManager();
 manager.EnrollInEngagementPlan([engagement plan id], [state id]);

 manager.SaveChanges(AutomationManager.Provider)