答:
If you look at the typings, you'll see that both to and from are Route's. Here's their interface declaration:

```<code>export interface Route {
  path: string;
  name?: string;
  hash: string;
  query: Dictionary<string | (string | null)[]>;
  params: Dictionary<string>;
  fullPath: string;
  matched: RouteRecord[];
  redirectedFrom?: string;
  meta?: any;
}
</code>```

If look at the Definition of BeforeEnter:

```<code>beforeEnter?: NavigationGuard;
</code>```

If you look at the Definition of NavigationGuard:

```<code>export type NavigationGuard<V extends Vue = Vue> = (
  to: Route,
  from: Route,
  next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
) => any
</code>```

So as we can see, the beforeEnter returns a closure that exposes 3 methods to us: (to, from, next).

As we can see the typings of both to and from are just Route Interfaces and next is a function that we pass arguments into, we can safely determine that the scope of this is indeed, undefined.

So you can either define it in the meta of the Route declaration and access it with this.$meta.cookies, or you can import the cookie package directly and use it with cookies.get('token') or you can augment the return type of the beforeEnter method:

```<code>beforeEnter: (to, from, next) => isLoggedIn(to, from, next, $cookies)
</code>```

You still, cannot, use the in component guards as they do not expose this to you because they execute before the component has been created

Title: Cannot get cookie in vue-router to work. Undefined "this"

Body:
If you look at the typings, you'll see that both to and from are Route's. Here's their interface declaration:

export interface Route {
  path: string;
  name?: string;
  hash: string;
  query: Dictionary<string | (string | null)[]>;
  params: Dictionary<string>;
  fullPath: string;
  matched: RouteRecord[];
  redirectedFrom?: string;
  meta?: any;
}

If look at the Definition of BeforeEnter:

beforeEnter?: NavigationGuard;

If you look at the Definition of NavigationGuard:

export type NavigationGuard<V extends Vue = Vue> = (
  to: Route,
  from: Route,
  next: (to?: RawLocation | false | ((vm: V) => any) | void) => void
) => any

So as we can see, the beforeEnter returns a closure that exposes 3 methods to us: (to, from, next).

As we can see the typings of both to and from are just Route Interfaces and next is a function that we pass arguments into, we can safely determine that the scope of this is indeed, undefined.

So you can either define it in the meta of the Route declaration and access it with this.$meta.cookies, or you can import the cookie package directly and use it with cookies.get('token') or you can augment the return type of the beforeEnter method:

beforeEnter: (to, from, next) => isLoggedIn(to, from, next, $cookies)

You still, cannot, use the in component guards as they do not expose this to you because they execute before the component has been created


来源: stackexchange

问:
Databinding with C# and Mysql shows wrong data
I have just created my first WPF-application and connected it to MySql-database.
I am able to retrieve data from DB, but it presents it totally wrong

I have searched through internet and different threads and now I have tried different things for a couple of hours.

My XAML-file

```<code>   <Window x:Class="AppGetMySQL.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AppGetMySQL"
    mc:Ignorable="d"
    Title="Get All Records" Height="450" WindowStartupLocation="CenterScreen" Width="800" AllowsTransparency="False" WindowStyle="ThreeDBorderWindow">
<Window.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFF1F7FF" Offset="0"/>
        <GradientStop Color="White" Offset="1"/>
    </LinearGradientBrush>
</Window.Background>
<Grid Margin="0,-52,0,0">
    <Button Content="Connect" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="112" Height="41" Click="Button_Click"/>
    <ListView HorizontalAlignment="Left" Margin="126,170,0,0" VerticalAlignment="Top" Name="ListAllUsers" Width="527" Height="291" FontSize="16" FontFamily="Calibri">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" />
                <GridViewColumn Header="Name" Width="300px"/>
                <GridViewColumn Header="City" Width="300px" />
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</Window>
</code>```

My .cs-file

```<code>int x = 0;

string connectionString = "SERVER=db5.freemysqlhosting.net;" + "DATABASE=db5233941;" + "UID=db5233941;" + "PASSWORD=*******;";
        string query = "select * from AllUsers";//I know I should not use *, but this is just test.
        MySqlConnection con = new MySqlConnection(connectionString);
        MySqlDataAdapter ada = new MySqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        ada.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            List<String> stringList = new List<string>();
            stringList.Add(dr["Id"].ToString());
            stringList.Add(dr["Name"].ToString());
            stringList.Add(dr["City"].ToString());
            ListAllUsers.ItemsSource = stringList;
        }
</code>```

I hope to print something like:

| id | Name | City |

| id | Name | City |

| id | Name | City |

But instead it prints

| id | id | id |

| Name | Name | Name |

| City | City | City |

Picture:

What am I doing wrong?

Edit:
Actually when I add this in the loop:

```<code>            Console.WriteLine("Id: " + dr["Id"].ToString());
            Console.WriteLine("Name: " + dr["Name"].ToString());
            Console.WriteLine("City: " + dr["City"].ToString());
</code>```

It prints everything correct. All five rows I have in my table.

答:
I solved it, and posts the solution if anybody needs it later.

I changed this in my xaml:

```<code>                <GridView>
                <GridViewColumn Header="Id"   DisplayMemberBinding="{Binding Id}" />
                <GridViewColumn Header="Name" Width="300px"  DisplayMemberBinding="{Binding Name}"  />
                <GridViewColumn Header="City" Width="300px" DisplayMemberBinding="{Binding City}"  />
                </GridView>
</code>```

And used this in my .cs-file

```<code>for (int i = 0; i < dt.Rows.Count; i++)
            {
            DataRow dr = dt.Rows[i];
            ListAllUsers.Items.Add(new User() {Id = Convert.ToInt32(dr["Id"]), Name = dr["Name"].ToString(), City = dr["City"].ToString() });
            ...
</code>```

This was all I needed to change.

Hope the next one will have some need of this.

ContentLicense: CC BY-SA 4.0

Body:
I have just created my first WPF-application and connected it to MySql-database.
I am able to retrieve data from DB, but it presents it totally wrong

I have searched through internet and different threads and now I have tried different things for a couple of hours.

My XAML-file

   <Window x:Class="AppGetMySQL.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:AppGetMySQL"
    mc:Ignorable="d"
    Title="Get All Records" Height="450" WindowStartupLocation="CenterScreen" Width="800" AllowsTransparency="False" WindowStyle="ThreeDBorderWindow">
<Window.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
        <GradientStop Color="#FFF1F7FF" Offset="0"/>
        <GradientStop Color="White" Offset="1"/>
    </LinearGradientBrush>
</Window.Background>
<Grid Margin="0,-52,0,0">
    <Button Content="Connect" HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Width="112" Height="41" Click="Button_Click"/>
    <ListView HorizontalAlignment="Left" Margin="126,170,0,0" VerticalAlignment="Top" Name="ListAllUsers" Width="527" Height="291" FontSize="16" FontFamily="Calibri">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" />
                <GridViewColumn Header="Name" Width="300px"/>
                <GridViewColumn Header="City" Width="300px" />
            </GridView>
        </ListView.View>
    </ListView>

</Grid>
</Window>

My .cs-file

int x = 0;

string connectionString = "SERVER=db5.freemysqlhosting.net;" + "DATABASE=db5233941;" + "UID=db5233941;" + "PASSWORD=*******;";
        string query = "select * from AllUsers";//I know I should not use *, but this is just test.
        MySqlConnection con = new MySqlConnection(connectionString);
        MySqlDataAdapter ada = new MySqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        ada.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            DataRow dr = dt.Rows[i];
            List<String> stringList = new List<string>();
            stringList.Add(dr["Id"].ToString());
            stringList.Add(dr["Name"].ToString());
            stringList.Add(dr["City"].ToString());
            ListAllUsers.ItemsSource = stringList;
        }

I hope to print something like:

| id | Name | City |

| id | Name | City |

| id | Name | City |

But instead it prints

| id | id | id |

| Name | Name | Name |

| City | City | City |

Picture:

What am I doing wrong?

Edit:
Actually when I add this in the loop:

            Console.WriteLine("Id: " + dr["Id"].ToString());
            Console.WriteLine("Name: " + dr["Name"].ToString());
            Console.WriteLine("City: " + dr["City"].ToString());

It prints everything correct. All five rows I have in my table.

Body:
I solved it, and posts the solution if anybody needs it later.

I changed this in my xaml:

                <GridView>
                <GridViewColumn Header="Id"   DisplayMemberBinding="{Binding Id}" />
                <GridViewColumn Header="Name" Width="300px"  DisplayMemberBinding="{Binding Name}"  />
                <GridViewColumn Header="City" Width="300px" DisplayMemberBinding="{Binding City}"  />
                </GridView>

And used this in my .cs-file

for (int i = 0; i < dt.Rows.Count; i++)
            {
            DataRow dr = dt.Rows[i];
            ListAllUsers.Items.Add(new User() {Id = Convert.ToInt32(dr["Id"]), Name = dr["Name"].ToString(), City = dr["City"].ToString() });
            ...

This was all I needed to change.

Hope the next one will have some need of this.


问:
Why does this code overflow with Int -> Int?
I am using recursive calls to calc an exponent. It works to 2**63 and then zeros out. I assume I have some overflow. But I thought Haskell handled this.

I tried numbers until 64 and checked into Int.

```<code>power :: Int -> Int
power n = if n==0 then 1 else 2*power(n-1)
main = return()
</code>```

In GHCI

```<code>1152921504606846976
*Main> power 70
0
*Main> power 65
0
*Main> power 64
0
*Main> power 63
-9223372036854775808
*Main> power 62
4611686018427387904
</code>```

答:
I assume I have some overflow. But I thought Haskell handled this.

It is indeed overflow, and Haskell has a type to handle integral numbers with arbitrary size: the Integer. You however use an Int. As the documentation specifies, for an Int:

data Int

A fixed-precision integer type with at least the range [-2^29 .. 2^29-1]. The exact range for a given implementation can be determined by using minBound and maxBound from the Bounded class.

An Int thus has a fixed word size, and can overflow. You can use an Integer however that can represent an arbitrary number (well until the memory is exhausted).

If we thus change the definition to:

```<code>power :: <b>Integer</b> -> <b>Integer</b>
power 0 = 1
power n = 2 * power (n-1)</code>```

we indeed can calculate 2128:

```<code>Prelude> power 128
340282366920938463463374607431768211456
</code>```

Note that we can boost the performance of this power function with:

```<code>power :: Integral i => i -> Integer
power 0 = 1
power n | even n = b2 * b2
        | otherwise = 2 * b2 * b2
    where b2 = power (div n 2)</code>```

This holds since b2 a = (b2)a. If we thus assume that all the operations are in constant time, then this algorithm runs in O(log p). This however does not completely hold, since b2 can be quite large, and thus multiplying b2 does not run in constant time.

Body:
I am using recursive calls to calc an exponent. It works to 2**63 and then zeros out. I assume I have some overflow. But I thought Haskell handled this.

I tried numbers until 64 and checked into Int.

power :: Int -> Int
power n = if n==0 then 1 else 2*power(n-1)
main = return()

In GHCI

1152921504606846976
*Main> power 70
0
*Main> power 65
0
*Main> power 64
0
*Main> power 63
-9223372036854775808
*Main> power 62
4611686018427387904

Body:
I assume I have some overflow. But I thought Haskell handled this.

It is indeed overflow, and Haskell has a type to handle integral numbers with arbitrary size: the Integer. You however use an Int. As the documentation specifies, for an Int:

data Int

A fixed-precision integer type with at least the range [-2^29 .. 2^29-1]. The exact range for a given implementation can be determined by using minBound and maxBound from the Bounded class.

An Int thus has a fixed word size, and can overflow. You can use an Integer however that can represent an arbitrary number (well until the memory is exhausted).

If we thus change the definition to:

power :: Integer -> Integer
power 0 = 1
power n = 2 * power (n-1)

we indeed can calculate 2128:

Prelude> power 128
340282366920938463463374607431768211456

Note that we can boost the performance of this power function with:

power :: Integral i => i -> Integer
power 0 = 1
power n | even n = b2 * b2
        | otherwise = 2 * b2 * b2
    where b2 = power (div n 2)

This holds since b2 a = (b2)a. If we thus assume that all the operations are in constant time, then this algorithm runs in O(log p). This however does not completely hold, since b2 can be quite large, and thus multiplying b2 does not run in constant time.


问:
Getting started with Intel x86 SSE SIMD instructions
I want to learn more about using the SSE.

What ways are there to learn, besides the obvious reading the Intel® 64 and IA-32 Architectures Software Developer's Manuals?

Mainly I'm interested to work with the GCC X86 Built-in Functions.

答:
Step 1: write some assembly manually

I recommend that you first try to write your own assembly manually to see and control exactly what is happening when you start learning.

Then the question becomes how to observe what is happening in the program, and the answers are:

GDB

use the C standard library to print and assert things

Using the C standard library yourself requires a little bit of work, but nothing much. I have for example done this work nicely for you on Linux in the following files of my test setup:

lkmc.h

lkmc.c

lkmc/x86_64.h

Using those helpers, I then start playing around with the basics, such as:

load and store data to / from memory into SSE registers

add integers and floating point numbers of different sizes

assert that the results are what I expect

addpd.S

```<code>#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    addps_input0: .float 1.5, 2.5,  3.5,  4.5
    addps_input1: .float 5.5, 6.5,  7.5,  8.5
    addps_expect: .float 7.0, 9.0, 11.0, 13.0
    addpd_input0: .double 1.5, 2.5
    addpd_input1: .double 5.5, 6.5
    addpd_expect: .double 7.0, 9.0
.bss
    .align 16
    output:       .skip 16
.text
    /* 4x 32-bit */
    movaps addps_input0, %xmm0
    movaps addps_input1, %xmm1
    addps %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addps_expect, $0x10)

    /* 2x 64-bit */
    movaps addpd_input0, %xmm0
    movaps addpd_input1, %xmm1
    addpd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addpd_expect, $0x10)
LKMC_EPILOGUE
</code>```

GitHub upstream.

paddq.S

```<code>#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    input0:       .long 0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4
    input1:       .long 0x12121212, 0x13131313, 0x14141414, 0x15151515
    paddb_expect: .long 0x03030303, 0x05050505, 0x07070707, 0x09090909
    paddw_expect: .long 0x04030403, 0x06050605, 0x08070807, 0x0A090A09
    paddd_expect: .long 0x04040403, 0x06060605, 0x08080807, 0x0A0A0A09
    paddq_expect: .long 0x04040403, 0x06060606, 0x08080807, 0x0A0A0A0A
.bss
    .align 16
    output:       .skip 16
.text
    movaps input1, %xmm1

    /* 16x 8bit */
    movaps input0, %xmm0
    paddb %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddb_expect, $0x10)

    /* 8x 16-bit */
    movaps input0, %xmm0
    paddw %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddw_expect, $0x10)

    /* 4x 32-bit */
    movaps input0, %xmm0
    paddd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddd_expect, $0x10)

    /* 2x 64-bit */
    movaps input0, %xmm0
    paddq %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddq_expect, $0x10)

LKMC_EPILOGUE
</code>```

GitHub upstream.

Step 2: write some intrinsics

For production code however, you will likely want to use the pre-existing intrinsics instead of raw assembly as mentioned at: https://stackoverflow.com/a/1390802/895245

So now I try to convert the previous examples into more or less equivalent C code with intrinsics.

addpq.c

```<code>#include <assert.h>
#include <string.h>

#include <x86intrin.h>

float global_input0[] __attribute__((aligned(16))) = {1.5f, 2.5f, 3.5f, 4.5f};
float global_input1[] __attribute__((aligned(16))) = {5.5f, 6.5f, 7.5f, 8.5f};
float global_output[4] __attribute__((aligned(16)));
float global_expected[] __attribute__((aligned(16))) = {7.0f, 9.0f, 11.0f, 13.0f};

int main(void) {
    /* 32-bit add (addps). */
    {
        __m128 input0 = _mm_set_ps(1.5f, 2.5f, 3.5f, 4.5f);
        __m128 input1 = _mm_set_ps(5.5f, 6.5f, 7.5f, 8.5f);
        __m128 output = _mm_add_ps(input0, input1);
        /* _mm_extract_ps returns int instead of float:
        * * https://stackoverflow.com/questions/5526658/intel-sse-why-does-mm-extract-ps-return-int-instead-of-float
        * * https://stackoverflow.com/questions/3130169/how-to-convert-a-hex-float-to-a-float-in-c-c-using-mm-extract-ps-sse-gcc-inst
        * so we must use instead: _MM_EXTRACT_FLOAT
        */
        float f;
        _MM_EXTRACT_FLOAT(f, output, 3);
        assert(f == 7.0f);
        _MM_EXTRACT_FLOAT(f, output, 2);
        assert(f == 9.0f);
        _MM_EXTRACT_FLOAT(f, output, 1);
        assert(f == 11.0f);
        _MM_EXTRACT_FLOAT(f, output, 0);
        assert(f == 13.0f);

        /* And we also have _mm_cvtss_f32 + _mm_shuffle_ps, */
        assert(_mm_cvtss_f32(output) == 13.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 1)) == 11.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 2)) ==  9.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 3)) ==  7.0f);
    }

    /* Now from memory. */
    {
        __m128 *input0 = (__m128 *)global_input0;
        __m128 *input1 = (__m128 *)global_input1;
        _mm_store_ps(global_output, _mm_add_ps(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* 64-bit add (addpd). */
    {
        __m128d input0 = _mm_set_pd(1.5, 2.5);
        __m128d input1 = _mm_set_pd(5.5, 6.5);
        __m128d output = _mm_add_pd(input0, input1);
        /* OK, and this is how we get the doubles out:
        * with _mm_cvtsd_f64 + _mm_unpackhi_pd
        * https://stackoverflow.com/questions/19359372/mm-cvtsd-f64-analogon-for-higher-order-floating-point
        */
        assert(_mm_cvtsd_f64(output) == 9.0);
        assert(_mm_cvtsd_f64(_mm_unpackhi_pd(output, output)) == 7.0);
    }

    return 0;
}
</code>```

GitHub upstream.

paddq.c

```<code>#include <assert.h>
#include <inttypes.h>
#include <string.h>

#include <x86intrin.h>

uint32_t global_input0[] __attribute__((aligned(16))) = {1, 2, 3, 4};
uint32_t global_input1[] __attribute__((aligned(16))) = {5, 6, 7, 8};
uint32_t global_output[4] __attribute__((aligned(16)));
uint32_t global_expected[] __attribute__((aligned(16))) = {6, 8, 10, 12};

int main(void) {

    /* 32-bit add hello world. */
    {
        __m128i input0 = _mm_set_epi32(1, 2, 3, 4);
        __m128i input1 = _mm_set_epi32(5, 6, 7, 8);
        __m128i output = _mm_add_epi32(input0, input1);
        /* _mm_extract_epi32 mentioned at:
        * https://stackoverflow.com/questions/12495467/how-to-store-the-contents-of-a-m128d-simd-vector-as-doubles-without-accessing/56404421#56404421 */
        assert(_mm_extract_epi32(output, 3) == 6);
        assert(_mm_extract_epi32(output, 2) == 8);
        assert(_mm_extract_epi32(output, 1) == 10);
        assert(_mm_extract_epi32(output, 0) == 12);
    }

    /* Now from memory. */
    {
        __m128i *input0 = (__m128i *)global_input0;
        __m128i *input1 = (__m128i *)global_input1;
        _mm_store_si128((__m128i *)global_output, _mm_add_epi32(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* Now a bunch of other sizes. */
    {
        __m128i input0 = _mm_set_epi32(0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4);
        __m128i input1 = _mm_set_epi32(0x12121212, 0x13131313, 0x14141414, 0x15151515);
        __m128i output;

        /* 8-bit integers (paddb) */
        output = _mm_add_epi8(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x03030303);
        assert(_mm_extract_epi32(output, 2) == 0x05050505);
        assert(_mm_extract_epi32(output, 1) == 0x07070707);
        assert(_mm_extract_epi32(output, 0) == 0x09090909);

        /* 32-bit integers (paddw) */
        output = _mm_add_epi16(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04030403);
        assert(_mm_extract_epi32(output, 2) == 0x06050605);
        assert(_mm_extract_epi32(output, 1) == 0x08070807);
        assert(_mm_extract_epi32(output, 0) == 0x0A090A09);

        /* 32-bit integers (paddd) */
        output = _mm_add_epi32(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040403);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080807);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);

        /* 64-bit integers (paddq) */
        output = _mm_add_epi64(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040404);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080808);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);
    }

    return 0;
</code>```

GitHub upstream.

Step 3: go and optimize some code and benchmark it

The final, and most important and hard step, is of course to actually use the intrinsics to make your code fast, and then to benchmark your improvement.

Doing so, will likely require you to learn a bit about the x86 microarchitecture, which I don't know myself. CPU vs IO bound will likely be one of the things that comes up: What do the terms "CPU bound" and "I/O bound" mean?

As mentioned at: https://stackoverflow.com/a/12172046/895245 this will almost inevitably involve reading Agner Fog's documentation, which appear to be better than anything Intel itself has published.

Hopefully however steps 1 and 2 will serve as a basis to at least experiment with functional non-performance aspects and quickly see what instructions are doing.

TODO: produce a minimal interesting example of such optimization here.

Body:
Step 1: write some assembly manually

I recommend that you first try to write your own assembly manually to see and control exactly what is happening when you start learning.

Then the question becomes how to observe what is happening in the program, and the answers are:

GDB

use the C standard library to print and assert things

Using the C standard library yourself requires a little bit of work, but nothing much. I have for example done this work nicely for you on Linux in the following files of my test setup:

lkmc.h

lkmc.c

lkmc/x86_64.h

Using those helpers, I then start playing around with the basics, such as:

load and store data to / from memory into SSE registers

add integers and floating point numbers of different sizes

assert that the results are what I expect

addpd.S

#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    addps_input0: .float 1.5, 2.5,  3.5,  4.5
    addps_input1: .float 5.5, 6.5,  7.5,  8.5
    addps_expect: .float 7.0, 9.0, 11.0, 13.0
    addpd_input0: .double 1.5, 2.5
    addpd_input1: .double 5.5, 6.5
    addpd_expect: .double 7.0, 9.0
.bss
    .align 16
    output:       .skip 16
.text
    /* 4x 32-bit */
    movaps addps_input0, %xmm0
    movaps addps_input1, %xmm1
    addps %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addps_expect, $0x10)

    /* 2x 64-bit */
    movaps addpd_input0, %xmm0
    movaps addpd_input1, %xmm1
    addpd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, addpd_expect, $0x10)
LKMC_EPILOGUE

GitHub upstream.

paddq.S

#include <lkmc.h>

LKMC_PROLOGUE
.data
    .align 16
    input0:       .long 0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4
    input1:       .long 0x12121212, 0x13131313, 0x14141414, 0x15151515
    paddb_expect: .long 0x03030303, 0x05050505, 0x07070707, 0x09090909
    paddw_expect: .long 0x04030403, 0x06050605, 0x08070807, 0x0A090A09
    paddd_expect: .long 0x04040403, 0x06060605, 0x08080807, 0x0A0A0A09
    paddq_expect: .long 0x04040403, 0x06060606, 0x08080807, 0x0A0A0A0A
.bss
    .align 16
    output:       .skip 16
.text
    movaps input1, %xmm1

    /* 16x 8bit */
    movaps input0, %xmm0
    paddb %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddb_expect, $0x10)

    /* 8x 16-bit */
    movaps input0, %xmm0
    paddw %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddw_expect, $0x10)

    /* 4x 32-bit */
    movaps input0, %xmm0
    paddd %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddd_expect, $0x10)

    /* 2x 64-bit */
    movaps input0, %xmm0
    paddq %xmm1, %xmm0
    movaps %xmm0, output
    LKMC_ASSERT_MEMCMP(output, paddq_expect, $0x10)

LKMC_EPILOGUE

GitHub upstream.

Step 2: write some intrinsics

For production code however, you will likely want to use the pre-existing intrinsics instead of raw assembly as mentioned at: https://stackoverflow.com/a/1390802/895245

So now I try to convert the previous examples into more or less equivalent C code with intrinsics.

addpq.c

#include <assert.h>
#include <string.h>

#include <x86intrin.h>

float global_input0[] __attribute__((aligned(16))) = {1.5f, 2.5f, 3.5f, 4.5f};
float global_input1[] __attribute__((aligned(16))) = {5.5f, 6.5f, 7.5f, 8.5f};
float global_output[4] __attribute__((aligned(16)));
float global_expected[] __attribute__((aligned(16))) = {7.0f, 9.0f, 11.0f, 13.0f};

int main(void) {
    /* 32-bit add (addps). */
    {
        __m128 input0 = _mm_set_ps(1.5f, 2.5f, 3.5f, 4.5f);
        __m128 input1 = _mm_set_ps(5.5f, 6.5f, 7.5f, 8.5f);
        __m128 output = _mm_add_ps(input0, input1);
        /* _mm_extract_ps returns int instead of float:
        * * https://stackoverflow.com/questions/5526658/intel-sse-why-does-mm-extract-ps-return-int-instead-of-float
        * * https://stackoverflow.com/questions/3130169/how-to-convert-a-hex-float-to-a-float-in-c-c-using-mm-extract-ps-sse-gcc-inst
        * so we must use instead: _MM_EXTRACT_FLOAT
        */
        float f;
        _MM_EXTRACT_FLOAT(f, output, 3);
        assert(f == 7.0f);
        _MM_EXTRACT_FLOAT(f, output, 2);
        assert(f == 9.0f);
        _MM_EXTRACT_FLOAT(f, output, 1);
        assert(f == 11.0f);
        _MM_EXTRACT_FLOAT(f, output, 0);
        assert(f == 13.0f);

        /* And we also have _mm_cvtss_f32 + _mm_shuffle_ps, */
        assert(_mm_cvtss_f32(output) == 13.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 1)) == 11.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 2)) ==  9.0f);
        assert(_mm_cvtss_f32(_mm_shuffle_ps(output, output, 3)) ==  7.0f);
    }

    /* Now from memory. */
    {
        __m128 *input0 = (__m128 *)global_input0;
        __m128 *input1 = (__m128 *)global_input1;
        _mm_store_ps(global_output, _mm_add_ps(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* 64-bit add (addpd). */
    {
        __m128d input0 = _mm_set_pd(1.5, 2.5);
        __m128d input1 = _mm_set_pd(5.5, 6.5);
        __m128d output = _mm_add_pd(input0, input1);
        /* OK, and this is how we get the doubles out:
        * with _mm_cvtsd_f64 + _mm_unpackhi_pd
        * https://stackoverflow.com/questions/19359372/mm-cvtsd-f64-analogon-for-higher-order-floating-point
        */
        assert(_mm_cvtsd_f64(output) == 9.0);
        assert(_mm_cvtsd_f64(_mm_unpackhi_pd(output, output)) == 7.0);
    }

    return 0;
}

GitHub upstream.

paddq.c

#include <assert.h>
#include <inttypes.h>
#include <string.h>

#include <x86intrin.h>

uint32_t global_input0[] __attribute__((aligned(16))) = {1, 2, 3, 4};
uint32_t global_input1[] __attribute__((aligned(16))) = {5, 6, 7, 8};
uint32_t global_output[4] __attribute__((aligned(16)));
uint32_t global_expected[] __attribute__((aligned(16))) = {6, 8, 10, 12};

int main(void) {

    /* 32-bit add hello world. */
    {
        __m128i input0 = _mm_set_epi32(1, 2, 3, 4);
        __m128i input1 = _mm_set_epi32(5, 6, 7, 8);
        __m128i output = _mm_add_epi32(input0, input1);
        /* _mm_extract_epi32 mentioned at:
        * https://stackoverflow.com/questions/12495467/how-to-store-the-contents-of-a-m128d-simd-vector-as-doubles-without-accessing/56404421#56404421 */
        assert(_mm_extract_epi32(output, 3) == 6);
        assert(_mm_extract_epi32(output, 2) == 8);
        assert(_mm_extract_epi32(output, 1) == 10);
        assert(_mm_extract_epi32(output, 0) == 12);
    }

    /* Now from memory. */
    {
        __m128i *input0 = (__m128i *)global_input0;
        __m128i *input1 = (__m128i *)global_input1;
        _mm_store_si128((__m128i *)global_output, _mm_add_epi32(*input0, *input1));
        assert(!memcmp(global_output, global_expected, sizeof(global_output)));
    }

    /* Now a bunch of other sizes. */
    {
        __m128i input0 = _mm_set_epi32(0xF1F1F1F1, 0xF2F2F2F2, 0xF3F3F3F3, 0xF4F4F4F4);
        __m128i input1 = _mm_set_epi32(0x12121212, 0x13131313, 0x14141414, 0x15151515);
        __m128i output;

        /* 8-bit integers (paddb) */
        output = _mm_add_epi8(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x03030303);
        assert(_mm_extract_epi32(output, 2) == 0x05050505);
        assert(_mm_extract_epi32(output, 1) == 0x07070707);
        assert(_mm_extract_epi32(output, 0) == 0x09090909);

        /* 32-bit integers (paddw) */
        output = _mm_add_epi16(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04030403);
        assert(_mm_extract_epi32(output, 2) == 0x06050605);
        assert(_mm_extract_epi32(output, 1) == 0x08070807);
        assert(_mm_extract_epi32(output, 0) == 0x0A090A09);

        /* 32-bit integers (paddd) */
        output = _mm_add_epi32(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040403);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080807);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);

        /* 64-bit integers (paddq) */
        output = _mm_add_epi64(input0, input1);
        assert(_mm_extract_epi32(output, 3) == 0x04040404);
        assert(_mm_extract_epi32(output, 2) == 0x06060605);
        assert(_mm_extract_epi32(output, 1) == 0x08080808);
        assert(_mm_extract_epi32(output, 0) == 0x0A0A0A09);
    }

    return 0;

GitHub upstream.

Step 3: go and optimize some code and benchmark it

The final, and most important and hard step, is of course to actually use the intrinsics to make your code fast, and then to benchmark your improvement.

Doing so, will likely require you to learn a bit about the x86 microarchitecture, which I don't know myself. CPU vs IO bound will likely be one of the things that comes up: What do the terms "CPU bound" and "I/O bound" mean?

As mentioned at: https://stackoverflow.com/a/12172046/895245 this will almost inevitably involve reading Agner Fog's documentation, which appear to be better than anything Intel itself has published.

Hopefully however steps 1 and 2 will serve as a basis to at least experiment with functional non-performance aspects and quickly see what instructions are doing.

TODO: produce a minimal interesting example of such optimization here.


问:
SEO ranking for drop-down containing product text, which can be viewable or hidden by website visitor?
I'm building a site on behalf of a watch company who want to have their images very prominently displayed on each page.

They also want product descriptions to be ranked well in terms of SEO, but they like the concept I have presented to them in using the JQuery 'A Different Top Navigation' (by Connor Zwick), for both the navigation AND a way of allowing users to VIEW and HIDE the product description for images. Checking out the demo will give you an idea of my plan:

Tutorial here: http://net.tutsplus.com/tutorials/javascript-ajax/a-different-top-navigation/

Demo here: http://d2o0t5hpnwv4c1.cloudfront.net/386_navigation/top-nav-demo/index.html#

So, with reference to another stackoverflow answer about crawlers indexing only the first level of hidden links, is this technique impractical for SEO because the product descriptions may not be indexed due to the association with keyword spamming in hidden boxes?

Thanks for any suggestions you can provide,

Dale M. Rollinson

答:
I haven't heard that bit about only the first level of hidden elements being traversed by search engine crawlers.  If that's true, you can avoid setting the style with CSS and use javascript to do it instead (crawlers don't run JS).

```<code><nav>
stuff
</nav>
<script type="text/javascript">
$('nav').hide();
</script>
</code>```

I placed it in the document like this so it's run immediately after the nav is loaded on the page.  Do not wait for document ready on this.  You could also put it at the bottom of your  if you so chose.  I'd maybe do that too.

ContentLicense: CC BY-SA 3.0

Body:
I haven't heard that bit about only the first level of hidden elements being traversed by search engine crawlers.  If that's true, you can avoid setting the style with CSS and use javascript to do it instead (crawlers don't run JS).

<nav>
stuff
</nav>
<script type="text/javascript">
$('nav').hide();
</script>

I placed it in the document like this so it's run immediately after the nav is loaded on the page.  Do not wait for document ready on this.  You could also put it at the bottom of your  if you so chose.  I'd maybe do that too.


问:
Best Practice For Reading Form Data in React
I'm trying to do something in React that would be very simple in any other framework: I want to collect a bunch of values from a form.

Previously I did this sort of thing with a Backbone View, and it was very simple:

```<code>readFormValues: function() {
    this.data.foo = this.$('[name="foo"]').val();
    this.data.bar = this.$('[name="bar"]:checked').val();
});
</code>```

But in React I can't seem to find an easy way to do that.  It seems my only options are to ...

NOTE: Apologies for the formatting: code blocks and lists don't play well together :-(

Completely bypass React and use the jQuery + e.target to access the form:

handleSubmit: function(e) {

var $form = $(e.target).parents('form:first');

this.data.foo =  $form.find('[name="foo"]);

},

render: function() {

return <form onSubmit="handleSubmit"><input name="foo"/></form>;

}

That works, and is simple, but it feels like I'm bypassing React and using JQuery when I should just be using React.

Provide callbacks to every form control:

handleFooClick: function(e) {

this.data.foo = event.target.value;

},

render: function() {

return <form><input name="foo" onChange="handleFooChange"/></form>;

}

This appears to be the React/Flux way, but it feels like a crazy amount of unnecessary work.  In my Backbone example I needed just one line per form control, but with this approach every last control I build has to have its own onChange handler (and I have to hook that handler up to every element as I render it).

EDIT: One more disadvantage of this approach is that inside the callbacks this.props and this.state won't point to my form control's props/state (it will point to the input's props/state).  This means that not only do I have to write a handler per input AND add that callback to every input as I render, but I also have to pass in my data object to every input!

Use refs:

handleSubmit: function(e) {

this.state.data.foo = this.refs.foo.value;

},

render: function() {

return <form><input ref="foo"/></form>;

}

This seems like a more sane solution, as I only need to add a "ref" attribute to every form control, and then I can read the data as easily as I could in Backbone.  However, all the React documentation suggests that using refs that way is wrong (all of the examples using refs involve sending signals to the controls, eg. "focus on this input", not on reading data out of the controls).

I feel like there must be a "React-ive" way to access my form data that isn't needlessly complex, but I'm not seeing it because I don't understand React well enough.  If any React expert could explain what I'm missing I would greatly appreciate it.

答:
The quickest and easiest way, using React's useState():

```<code>const Form = () => {
  const [fullName, setFullName] = React.useState("");
  const [is18, setOver18] = React.useState(false);

  return (
    <form>
      <input
        type="text"
        name="fullName"
        value={fullName}
        onChange={event => setFullName(event.target.value)}
      />

      <input
        type="checkbox"
        name="over18"
        checked={is18}
        onChange={() => setOver18(!is18)}
      />
    </form>
  );
};
</code>```

Body:
I'm trying to do something in React that would be very simple in any other framework: I want to collect a bunch of values from a form.

Previously I did this sort of thing with a Backbone View, and it was very simple:

readFormValues: function() {
    this.data.foo = this.$('[name="foo"]').val();
    this.data.bar = this.$('[name="bar"]:checked').val();
});

But in React I can't seem to find an easy way to do that.  It seems my only options are to ...

NOTE: Apologies for the formatting: code blocks and lists don't play well together :-(

Completely bypass React and use the jQuery + e.target to access the form:

handleSubmit: function(e) {

var $form = $(e.target).parents('form:first');

this.data.foo =  $form.find('[name="foo"]);

},

render: function() {

return <form onSubmit="handleSubmit"><input name="foo"/></form>;

}

That works, and is simple, but it feels like I'm bypassing React and using JQuery when I should just be using React.

Provide callbacks to every form control:

handleFooClick: function(e) {

this.data.foo = event.target.value;

},

render: function() {

return <form><input name="foo" onChange="handleFooChange"/></form>;

}

This appears to be the React/Flux way, but it feels like a crazy amount of unnecessary work.  In my Backbone example I needed just one line per form control, but with this approach every last control I build has to have its own onChange handler (and I have to hook that handler up to every element as I render it).

EDIT: One more disadvantage of this approach is that inside the callbacks this.props and this.state won't point to my form control's props/state (it will point to the input's props/state).  This means that not only do I have to write a handler per input AND add that callback to every input as I render, but I also have to pass in my data object to every input!

Use refs:

handleSubmit: function(e) {

this.state.data.foo = this.refs.foo.value;

},

render: function() {

return <form><input ref="foo"/></form>;

}

This seems like a more sane solution, as I only need to add a "ref" attribute to every form control, and then I can read the data as easily as I could in Backbone.  However, all the React documentation suggests that using refs that way is wrong (all of the examples using refs involve sending signals to the controls, eg. "focus on this input", not on reading data out of the controls).

I feel like there must be a "React-ive" way to access my form data that isn't needlessly complex, but I'm not seeing it because I don't understand React well enough.  If any React expert could explain what I'm missing I would greatly appreciate it.

Body:
The quickest and easiest way, using React's useState():

const Form = () => {
  const [fullName, setFullName] = React.useState("");
  const [is18, setOver18] = React.useState(false);

  return (
    <form>
      <input
        type="text"
        name="fullName"
        value={fullName}
        onChange={event => setFullName(event.target.value)}
      />

      <input
        type="checkbox"
        name="over18"
        checked={is18}
        onChange={() => setOver18(!is18)}
      />
    </form>
  );
};


问:
Why won't the plot update even though the data has changed
In the demo app below, the user can change the Selected state of the data rows by either clicking input$Go1 or select a region in the plot.

Selection the region in the plot is my intended functionality.

However, for a reason I fail to understand, the button does cause a re-render of the plot while select does not, even though both approaches have the same effect, i.e. a change in the values in column Selected of data.table RFImp_FP1

Why is it not working when I select points in the plot?

```<code>ui <- fluidPage(
  actionButton(inputId = 'Go', label = 'Go'),
  actionButton(inputId = 'Go2', label = 'Go2'),
  plotlyOutput('RFAcc_FP1',  width = 450)

)

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

  observeEvent(input$Go, {
    values$RFImp_FP1 <- data.table(MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
    values$RFImp_FP1$Selected <- 1
  })

observeEvent(input$Go2,{

  values$RFImp_FP1$Selected[1:4] <- 1-values$RFImp_FP1$Selected[1:4]
  print(values$RFImp_FP1$Selected)
})

observe({
  if(!is.null(values$RFImp_FP1)) {
    parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
    if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
      data_df <- values$RFImp_FP1
      data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
      values$RFImp_FP1$Selected <- data_df$Selected
    print(values$RFImp_FP1)
      }
  }
})
observeEvent(values$RFImp_FP1, {
  print('seeing change')
  })

output$RFAcc_FP1 <- renderPlotly({

  values$RFImp_FP1
  if(!is.null(values$RFImp_FP1)) {

    RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
    plotheight <- length(RFImp_score$Variables) * input$testme
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#1b73c1', '#797979'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('circle','x'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                               '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p$elementId <- NULL   ## to surpress warning of widgetid
    p <- p %>% config(displayModeBar = F)
    p

  } else {
    p <- plot_ly( type = 'scatter', mode = 'markers',  height = '400px', width = 450) %>% layout(
      margin = list(l = 160, r= 20, b = 70, t = 50),
      xaxis = list(title = 'Mean decrease accuracy index', range= c(0,1), nticks = 2, showline = TRUE),
      yaxis = list(title = 'Model input variables', range = c(0,1), nticks = 2, showline = TRUE)) %>%
      add_annotations(x = 0.5, y = 1.1, textangle = 0, font = list(size = 14, color = 'black'),
                      text = 'Contribution to accuracy',
                      showarrow = F, xref='paper', yref='paper')
    p$elementId <- NULL
    p <- p %>% config(displayModeBar = F)
    p}
})

}
shinyApp(ui, server)
</code>```

select vs button result:

答:
Don't ask me why, but I managed to get it to work with observeEvent and assigning NULL to the values$RFImp_FP1 before reassigning the altered data.table to it

```<code>  values$RFImp_FP1 <- NULL
  values$RFImp_FP1<- resDF
</code>```

Full version:

```<code>library(shiny)
library(plotly)
library(dplyr)
library(data.table)

testDF <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
testDF$Selected <- T

ui <- fluidPage(
  plotlyOutput('RFAcc_FP1',  width = 450)
)

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

  values <- reactiveValues(RFImp_FP1 = testDF)

observeEvent(event_data("plotly_selected", source = 'RFAcc_FP1')$y, {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      resDF <- values$RFImp_FP1 %>% .[, Selected := if_else(Variables %in% parsToChange, !Selected, Selected)]
      values$RFImp_FP1 <- NULL  ## without this line the plot does not react
      values$RFImp_FP1<- resDF ## re-assign the altered data.table to the reactiveValue
  })

  output$RFAcc_FP1 <- renderPlotly({

    RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
    plotheight <- length(RFImp_score$Variables) * 80
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#F0F0F0', '#1b73c1'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('x', 'circle'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                               '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p <- p %>% config(displayModeBar = F)
    p
  })

}
shinyApp(ui, server)
</code>```

and to avoid the plotly warnings about not being registered, we can change the observe structure to

```<code>  observe({
    if(!is.null( values$RFImp_FP1)) {
      values$Selected <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
    }
  })

  observeEvent(values$Selected, {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- values$RFImp_FP1
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, !Selected, Selected)]
        values$RFImp_FP1 <- NULL
        values$RFImp_FP1 <- data_df
      }

  })
</code>```

One problem remains: making the same selection twice in a row does not trigger the observers as the selection is identical....

Body:
In the demo app below, the user can change the Selected state of the data rows by either clicking input$Go1 or select a region in the plot.

Selection the region in the plot is my intended functionality.

However, for a reason I fail to understand, the button does cause a re-render of the plot while select does not, even though both approaches have the same effect, i.e. a change in the values in column Selected of data.table RFImp_FP1

Why is it not working when I select points in the plot?

ui <- fluidPage(
  actionButton(inputId = 'Go', label = 'Go'),
  actionButton(inputId = 'Go2', label = 'Go2'),
  plotlyOutput('RFAcc_FP1',  width = 450)

)

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

  observeEvent(input$Go, {
    values$RFImp_FP1 <- data.table(MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
    values$RFImp_FP1$Selected <- 1
  })

observeEvent(input$Go2,{

  values$RFImp_FP1$Selected[1:4] <- 1-values$RFImp_FP1$Selected[1:4]
  print(values$RFImp_FP1$Selected)
})

observe({
  if(!is.null(values$RFImp_FP1)) {
    parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
    if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
      data_df <- values$RFImp_FP1
      data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, 1-Selected, Selected)]
      values$RFImp_FP1$Selected <- data_df$Selected
    print(values$RFImp_FP1)
      }
  }
})
observeEvent(values$RFImp_FP1, {
  print('seeing change')
  })

output$RFAcc_FP1 <- renderPlotly({

  values$RFImp_FP1
  if(!is.null(values$RFImp_FP1)) {

    RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
    plotheight <- length(RFImp_score$Variables) * input$testme
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#1b73c1', '#797979'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('circle','x'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('
', 'Parameter: ', RFImp_score$Variables,
                               '
',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p$elementId <- NULL   ## to surpress warning of widgetid
    p <- p %>% config(displayModeBar = F)
    p

  } else {
    p <- plot_ly( type = 'scatter', mode = 'markers',  height = '400px', width = 450) %>% layout(
      margin = list(l = 160, r= 20, b = 70, t = 50),
      xaxis = list(title = 'Mean decrease accuracy index', range= c(0,1), nticks = 2, showline = TRUE),
      yaxis = list(title = 'Model input variables', range = c(0,1), nticks = 2, showline = TRUE)) %>%
      add_annotations(x = 0.5, y = 1.1, textangle = 0, font = list(size = 14, color = 'black'),
                      text = 'Contribution to accuracy',
                      showarrow = F, xref='paper', yref='paper')
    p$elementId <- NULL
    p <- p %>% config(displayModeBar = F)
    p}
})

}
shinyApp(ui, server)

select vs button result:

Body:
Don't ask me why, but I managed to get it to work with observeEvent and assigning NULL to the values$RFImp_FP1 before reassigning the altered data.table to it

  values$RFImp_FP1 <- NULL
  values$RFImp_FP1<- resDF

Full version:

library(shiny)
library(plotly)
library(dplyr)
library(data.table)

testDF <- data.table( MeanDecreaseAccuracy =  runif(10, min = 0, max = 1), Variables = letters[1:10])
testDF$Selected <- T

ui <- fluidPage(
  plotlyOutput('RFAcc_FP1',  width = 450)
)

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

  values <- reactiveValues(RFImp_FP1 = testDF)

observeEvent(event_data("plotly_selected", source = 'RFAcc_FP1')$y, {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      resDF <- values$RFImp_FP1 %>% .[, Selected := if_else(Variables %in% parsToChange, !Selected, Selected)]
      values$RFImp_FP1 <- NULL  ## without this line the plot does not react
      values$RFImp_FP1<- resDF ## re-assign the altered data.table to the reactiveValue
  })

  output$RFAcc_FP1 <- renderPlotly({

    RFImp_score <- values$RFImp_FP1[order(MeanDecreaseAccuracy)]
    plotheight <- length(RFImp_score$Variables) * 80
    p <- plot_ly(data = RFImp_score,
                 source = 'RFAcc_FP1',
                 height = plotheight,
                 width = 450)  %>%
      add_trace(x = RFImp_score$MeanDecreaseAccuracy,
                y = RFImp_score$Variables,
                type = 'scatter',
                mode = 'markers',
                color = factor(RFImp_score$Selected),
                colors = c('#F0F0F0', '#1b73c1'),
                symbol = factor(RFImp_score$Selected),
                symbols = c('x', 'circle'),
                marker = list(size  = 6),
                hoverinfo = "text",
                text = ~paste ('<br>', 'Parameter: ', RFImp_score$Variables,
                               '<br>',  'Mean decrease accuracy: ', format(round(RFImp_score$MeanDecreaseAccuracy*100, digits = 2), nsmall = 2),'%',
                               sep = '')) %>%
      layout(
        margin = list(l = 160, r= 20, b = 70, t = 50),
        hoverlabel = list(font=list( color = '#1b73c1'), bgcolor='#f7fbff'),
        xaxis =  list(title = 'Mean decrease accuracy index (%)',
                      tickformat = "%",
                      showgrid = F,
                      showline = T,
                      zeroline = F,
                      nticks = 5,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        yaxis =  list(categoryarray = RFImp_score$Variables,
                      autorange = T,
                      showgrid = F,
                      showline = T,
                      autotick = T,
                      font = list(size = 8),
                      ticks = "outside",
                      ticklen = 5,
                      tickwidth = 2,
                      tickcolor = toRGB("black")
        ),
        dragmode =  "select"
      ) %>%  add_annotations(x = 0.5,
                             y = 1.05,
                             textangle = 0,
                             font = list(size = 14,
                                         color = 'black'),
                             text = "Contribution to accuracy",
                             showarrow = F,
                             xref='paper',
                             yref='paper')

    p <- p %>% config(displayModeBar = F)
    p
  })

}
shinyApp(ui, server)

and to avoid the plotly warnings about not being registered, we can change the observe structure to

  observe({
    if(!is.null( values$RFImp_FP1)) {
      values$Selected <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
    }
  })

  observeEvent(values$Selected, {
      parsToChange <- event_data("plotly_selected", source = 'RFAcc_FP1')$y
      if(!is.null(event_data("plotly_selected", source = 'RFAcc_FP1'))){
        data_df <- values$RFImp_FP1
        data_df <- data_df %>% .[, Selected := if_else(Variables %in% parsToChange, !Selected, Selected)]
        values$RFImp_FP1 <- NULL
        values$RFImp_FP1 <- data_df
      }

  })

One problem remains: making the same selection twice in a row does not trigger the observers as the selection is identical....


问:
Neural Network doesn't learn - simple classification problem
I am currently trying to learn simple neural network recognize 4 different outputs. There are 2-value-inputs which are actually something like this:

output + uniform(-0.2,0.2) + 1

There are only 200 records of that data - but that's important for me to stay with as little data as possible.

Example of input and output next to it:

```<code>0.9936288071867917,1.0163870658585894  -  0

2.0133450399223953,1.9965272907556022  -  1

3.013918319917813,3.018102735071009  -  2

3.9935640040186025,4.00379069782054  -  3
</code>```

I tried to set different number of epochs, hidden neurons and activation functions. The thing is I want to keep neural network very simple - that means only two hidden layers with max number of about 20 hidden neurons per layer.
No matter what I do it still doesn't learn or learns very poorly.

Here's code

import keras
import numpy as np
from sklearn.model_selection import train_test_split
#import pandas as pd
#import tensorflow as tf
from sklearn.utils import shuffle
from sklearn import metrics

seed = 10
np.random.seed(seed)

dataset = np.loadtxt("dataset.csv",delimiter=',')
#dataset = shuffle(dataset)

X = dataset[:,:2]
Y = dataset[:,2]

#print(X)
#print(Y)

(X_train,X_test,Y_train,Y_test) = train_test_split(X, Y, test_size=0.10, random_state=seed)
input_shape = (2,)

model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape))
model.add(keras.layers.core.Dense(8, activation='sigmoid'))
model.add(keras.layers.core.Dense(4, activation='sigmoid'))

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
history = model.fit(X_train,Y_train,validation_split=0.10,epochs=30)

val_loss, val_acc = model.evaluate(X_test,Y_test)
print('\nCost = ',val_loss,'\nAccuracy = ',val_acc,'\n')

```

<p>I still get results looking like this through epochs(almost the same) and evaluation:</p>

<pre class="lang-py prettyprint-override"><code>Cost =  1.40975821018219
Accuracy =  0.20000000298023224
</code>```

What can I do to improve that neural network?

答:
The first thing you might want to change is the activation function in your last layer. Since you have 4 different outputs, softmax is the correct activation function.

```<code>model.add(keras.layers.core.Dense(4, activation='softmax'))
</code>```

The next thing you should do is to replace

```<code> model.add(keras.layers.core.Dense(8, activation='sigmoid'))
</code>```

with

```<code>  model.add(keras.layers.core.Dense(8, activation='relu'))
</code>```

Body:
I am currently trying to learn simple neural network recognize 4 different outputs. There are 2-value-inputs which are actually something like this:

output + uniform(-0.2,0.2) + 1

There are only 200 records of that data - but that's important for me to stay with as little data as possible.

Example of input and output next to it:

0.9936288071867917,1.0163870658585894  -  0

2.0133450399223953,1.9965272907556022  -  1

3.013918319917813,3.018102735071009  -  2

3.9935640040186025,4.00379069782054  -  3

I tried to set different number of epochs, hidden neurons and activation functions. The thing is I want to keep neural network very simple - that means only two hidden layers with max number of about 20 hidden neurons per layer.
No matter what I do it still doesn't learn or learns very poorly.

Here's code

import keras
import numpy as np
from sklearn.model_selection import train_test_split
#import pandas as pd
#import tensorflow as tf
from sklearn.utils import shuffle
from sklearn import metrics

seed = 10
np.random.seed(seed)

dataset = np.loadtxt("dataset.csv",delimiter=',')
#dataset = shuffle(dataset)

X = dataset[:,:2]
Y = dataset[:,2]

#print(X)
#print(Y)

(X_train,X_test,Y_train,Y_test) = train_test_split(X, Y, test_size=0.10, random_state=seed)
input_shape = (2,)

model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape))
model.add(keras.layers.core.Dense(8, activation='sigmoid'))
model.add(keras.layers.core.Dense(4, activation='sigmoid'))

model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
history = model.fit(X_train,Y_train,validation_split=0.10,epochs=30)

val_loss, val_acc = model.evaluate(X_test,Y_test)
print('\nCost = ',val_loss,'\nAccuracy = ',val_acc,'\n')

I still get results looking like this through epochs(almost the same) and evaluation:

Cost =  1.40975821018219
Accuracy =  0.20000000298023224

What can I do to improve that neural network?

Body:
The first thing you might want to change is the activation function in your last layer. Since you have 4 different outputs, softmax is the correct activation function.

model.add(keras.layers.core.Dense(4, activation='softmax'))

The next thing you should do is to replace

 model.add(keras.layers.core.Dense(8, activation='sigmoid'))

with

  model.add(keras.layers.core.Dense(8, activation='relu'))


问:
Vagrant creating multiple terminals in guest machine
I have vagrant and an ubuntu server 16.04 box started with it.

By using vagrant ssh command everything is fine if you need just one terminal, but I need many terminal sessions not just one because I have to start 3 nodejs processes and some other tasks and need to monitor them while running.

Have searched a lot but haven't found any information about this issue.
Over vagrant ssh can't event use ubuntu server virtual terminals ttys-

答:
So I needed two terminal tabs with two separate processes ( local host py server ) AND SaSS for CSS3 compiling . This is what worked for me ;
I should mention that I am running virtualenv IN Vagrant and ON VirtualBox .

Open a new Terminal tab .
SSH from your Vagrant folder . (vagrant ssh)
Activate your virtual machine . (virtualenv)

Run SaSS compiler ( 2nd process )

Hope this helps . Everyone seems to have unique dev environments so it can be tricky .


问:
Generate random numbers according to distributions
I want to generate random numbers according some distributions. How can I do this?</p>

答: It's a standard textbook matter. See here for some code, or here at Section 3.2 for some reference mathematical background (actually very quick and simple to read).</p>


问:
Animating changes in a SliverList
I currently have a SliverList whose items are loaded dynamically. The issue is that once these items are loaded, the SliverList updates without animating the changes, making the transition between loading & loaded very jarring.

I see that AnimatedList exists but it isn't a sliver so I can't place it directly in a CustomScrollView.

答:
I have a workaround for using a simple ListView with a Sliver. It's not perfect and it has limitations, but it works for the case where you just have 2 Slivers, the AppBar and a SliverList.

```<code>NestedScrollView(
  headerSliverBuilder: (_, _a) => SliverAppBar(<Insert Code Here>),
  body: MediaQuery.removePadding(
    removeTop: true,
    context: context,
    child: AnimatedList(
      <InsertCodeHere>
    )))
</code>```

You can tweak around with the Widget tree, but that's the basic idea. Wrap the sliver appbar in a NestedScrollView and place the List in the body.

Title: Animating changes in a SliverList

Body:
I have a workaround for using a simple ListView with a Sliver. It's not perfect and it has limitations, but it works for the case where you just have 2 Slivers, the AppBar and a SliverList.

NestedScrollView(
  headerSliverBuilder: (_, _a) => SliverAppBar(<Insert Code Here>),
  body: MediaQuery.removePadding(
    removeTop: true,
    context: context,
    child: AnimatedList(
      <InsertCodeHere>
    )))

You can tweak around with the Widget tree, but that's the basic idea. Wrap the sliver appbar in a NestedScrollView and place the List in the body.


问:
How to make a string from separate int values
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

```<code>    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

</code>```

But when I printf I get nothing.

```<code>    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);
</code>```

This is what is working but seems very inefficient.

答:
The code you posted can be made more efficient by just replacing the last 4 lines with a single sprintf().

    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5] = {'\0'};
    sprintf(buffer, "%d%s%d%s", start, aux, end, aux2);
```

Body:
I'm trying to make a string out of 3 elements with the following format '0/5'.

int start = 0;
int finish = 5;

I've tried doing this:

    char string[20];

    string[0] = (char) start;
    string[1] = '/';
    string[2] = (char) finish;

    string[strlen(string)] = '\0';

But when I printf I get nothing.

    char buffer[10];
    char aux[5] = {'/', '\0'};
    char aux2[5];
    sprintf(buffer, "%d", start);
    strcat(buffer, aux);
    sprintf(aux2, "%d", finish);
    strcat(buffer, aux2);

This is what is working but seems very inefficient.


问:
How to append array into data from ipcRenderer
I am trying to get select the list of files(path) from directory and display it on the DOM,but in order to display data i have to first assign in vuejs data object.

mainRenderer

```<code>ipcMain.on("channel1", (e, args) => {
  const files = getFileFromUserSelection();
  e.reply("channel1", files); // sending to channel1 in app.vue
});

const getFileFromUserSelection = () => {
  const files = dialog.showOpenDialog({
    properties: ["multiSelections"]
  });
  if (!files) return;
  return files;
};
</code>```

App.Vue

```<code><template>
  <div>
    <p v-for="file in files">{{file}}</p>
  </div>
</template>

<script>
import { ipcRenderer } from "electron";

//this gets files from the main process
ipcRenderer.on("channel1", (e, files) => {
  console.log(files); // i want this file into data:function()
});

export default {
  data: function() {
    return {
      files: []
    };
  },
  methods: {
    clicked: function() {
      ipcRenderer.send("channel1", "open dialog to getFiles from user");
    }
  }
};

</script>

</code>```

答:
You can use the beforeCreate hook on the Vuecomponent in order to hydrate the data property:

```<code>export default {
  data: function() {
    return {
      files: []
    };
  },
  beforeCreate() {
    ipcRenderer.on("channel1", (e, files) => {
      this.files = files
    });
  },
  methods: {
    clicked: function() {
      ipcRenderer.send("channel1", "open dialog to getFiles from user");
    }
  }
};
</code>```

Note that, of course, you cannot interact directly with the files array until you know it's been hydrated, so a computed getter here may be of some use to you, or just use files.length.

Body:
I am trying to get select the list of files(path) from directory and display it on the DOM,but in order to display data i have to first assign in vuejs data object.

mainRenderer

ipcMain.on("channel1", (e, args) => {
  const files = getFileFromUserSelection();
  e.reply("channel1", files); // sending to channel1 in app.vue
});

const getFileFromUserSelection = () => {
  const files = dialog.showOpenDialog({
    properties: ["multiSelections"]
  });
  if (!files) return;
  return files;
};

App.Vue

<template>

{{file}}

</template>

Body:
You can use the beforeCreate hook on the Vuecomponent in order to hydrate the data property:

export default {
  data: function() {
    return {
      files: []
    };
  },
  beforeCreate() {
    ipcRenderer.on("channel1", (e, files) => {
      this.files = files
    });
  },
  methods: {
    clicked: function() {
      ipcRenderer.send("channel1", "open dialog to getFiles from user");
    }
  }
};

Note that, of course, you cannot interact directly with the files array until you know it's been hydrated, so a computed getter here may be of some use to you, or just use files.length.


问:
Split words and capitalize first character
I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

```<code>String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}
</code>```

答:
Your code is blowing up on multiple spaces because when you split you're getting a member in your array that is an empty string "hello  there" when split becomes array[0] = "hello", array[1] = "", array[2] = "there".

So when you do substring(0,1) you should get an IndexOutOfBoundsException.

Try changing your split("\\s") to split("\\s+") this way your multiple spaces get picked up in the regex and thrown out.

Edit:

This also will let you get rid of the .trim() inside your loop since all of the spaces will be taken care of by the split.

Body:
I'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.

Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?

String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
    formattedInput = formattedInput.trim() + " " +
            inputLineArray[d].trim().substring(0,1).toUpperCase() +
            inputLineArray[d].trim().substring(1).toLowerCase();
}


问:
Mock unit testing for RxJava
I'm writing unit tests base on Google's samples: TaskDetailPresenterTest.kt#L102

They use ArgumentCaptor<TasksDataSource.GetTaskCallback> to trigger callback with fake data COMPLETED_TASK

```<code>@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id), capture(taskCallbackCaptor))

    // When task is finally loaded
    taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback
}
</code>```

Everything work fine because they use TasksDataSource.GetTaskCallback to return data. See: TaskDetailPresenter.kt#L36:

```<code>fun getTask(taskId: String, callback: GetTaskCallback)
</code>```

Then use as

```<code>tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        showTask(task)
    }
}
</code>```

But when I try to use RxJava Single<> instead of normal callback, like:

```<code>fun getTask(taskId: String): Single<Task>
</code>```

Then use as

```<code>tasksRepository.getTask(taskId)
    .subscribe(object : SingleObserver<Task> {
        override fun onSuccess(task: Task) {
            showTask(task)
        }

        override fun onError(e: Throwable) {
        }
    })
}
</code>```

Then I cannot use ArgumentCaptor<> to trigger return fake data. It always throw NullPointerException when I execute my test, because  tasksRepository.getTask(taskId) is always return null.

So how can I achieve the same unit test like Google did, but in RxJava?

My unit test code:

```<code>@Mock private lateinit var tasksRepository: TasksRepository

@Captor private lateinit var taskCaptor: ArgumentCaptor<SingleObserver<Task>>

private lateinit var presenter: TaskDetailPresenter

@Before fun setup() {
    MockitoAnnotations.initMocks(this)
}

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture())

    // When task is finally loaded
    taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback
}
</code>```

Note that all other parts (declare, setup, mocking,..) is the same as Google.

答: I don't know if you have already used this library but I would suggest you to use the Dagger 2 library with a MVP code architecture to ease your unit tests by improving your dependencies and couplings</p>

Title: Mock unit testing for RxJava

Body:
I'm writing unit tests base on Google's samples: TaskDetailPresenterTest.kt#L102

They use ArgumentCaptor<TasksDataSource.GetTaskCallback> to trigger callback with fake data COMPLETED_TASK

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id), capture(taskCallbackCaptor))

    // When task is finally loaded
    taskCallbackCaptor.value.onTaskLoaded(COMPLETED_TASK) // Trigger callback
}

Everything work fine because they use TasksDataSource.GetTaskCallback to return data. See: TaskDetailPresenter.kt#L36:

fun getTask(taskId: String, callback: GetTaskCallback)

Then use as

tasksRepository.getTask(taskId, object : TasksDataSource.GetTaskCallback {
    override fun onTaskLoaded(task: Task) {
        showTask(task)
    }
}

But when I try to use RxJava Single<> instead of normal callback, like:

fun getTask(taskId: String): Single<Task>

Then use as

tasksRepository.getTask(taskId)
    .subscribe(object : SingleObserver<Task> {
        override fun onSuccess(task: Task) {
            showTask(task)
        }

        override fun onError(e: Throwable) {
        }
    })
}

Then I cannot use ArgumentCaptor<> to trigger return fake data. It always throw NullPointerException when I execute my test, because  tasksRepository.getTask(taskId) is always return null.

So how can I achieve the same unit test like Google did, but in RxJava?

My unit test code:

@Mock private lateinit var tasksRepository: TasksRepository

@Captor private lateinit var taskCaptor: ArgumentCaptor<SingleObserver<Task>>

private lateinit var presenter: TaskDetailPresenter

@Before fun setup() {
    MockitoAnnotations.initMocks(this)
}

@Test
fun getCompletedTaskFromRepositoryAndLoadIntoView() {
    presenter = TaskDetailPresenter(COMPLETED_TASK.id, tasksRepository, taskDetailView)
    presenter.start()

    // Then task is loaded from model, callback is captured
    verify(tasksRepository).getTask(
                eq(COMPLETED_TASK.id)).subscribe(taskCaptor.capture())

    // When task is finally loaded
    taskCaptor.value.onSuccess(COMPLETED_TASK) // Trigger callback
}

Note that all other parts (declare, setup, mocking,..) is the same as Google.


问:
Fluent with Spring [j2ee applications] , more insight on MEAN & MERN stack
I recently took some time to learn SPRING framework and develop a simple application which follows the MVC pattern.
But, later I came across MEAN & MERN Stack development to develop delicious looking Single page applications.

What I cannot understand is why and where to start?

Like,

should I move on with SPRING Boot and use ANGULAR or React for front-end alone,[I don't know if this is possible]

or

should I completely ditch J2EE [java] and start MEAN & MERN Stack development [javascript].

Tried googling some stuff, but didn't quite answer my question Except for the fact that many developers prefer MERN > MEAN > J2EE with SPRING.

Some insight over what should I start or continue with and maybe with some resources[Well, I found some CRUD Examples for both MEAN & MERN and would refer official docs for learning angular or react respectively, Would like to know if there is anything else I should know.] to kickstart would be much appreciated.

答:
I would shift away from Java to be honest. Oracle started charging money this year for using Java SE . I would imagine more new projects would move away from java for this reason and just use node.

java would be good if you plan on working for a large enterprise, but those companies usually dont use React for a frontend.

MERN is a popular stack for tutorials but in production apps I have seen a SQL based database systems, such as PSQL, to be more popular.

So I would learn React/Node/express with a SQL based database instead of MongoDB.


问:
Not able to scrape the all the reviews
I am trying to scrape this website and trying to get the reviews but I am facing an issue,

The page loads only 50 reviews.

To load more you have to click "Show More Reviews" and I don't know how to get all the data as there is no page link, also "Show more Reviews" doesn't have a URL to explore, the address remains the same.

url =
  "https://www.capterra.com/p/134048/HiMama-Preschool-Child-Care-App/#reviews"

```<code>import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
a = []

url = requests.get(url)
html = url.text
soup = BeautifulSoup(html, "html.parser")

table = soup.findAll("div", {"class":"review-comments"})
#print(table)
for x in table:
    a.append(x.text)
df = pd.DataFrame(a)
df.to_csv("review.csv", sep='\t')
</code>```

I know this is not pretty code but I am just trying to get the review text first.
kindly help. As I am little new to this.

答:
Looking at the website, the "Show more reviews" button makes an ajax call and returns the additional info, all you have to do is find it's link and send a get request to it (which I've done with some simple regex):

import requests
import re
from bs4 import BeautifulSoup
headers = {
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36"
}
url = "https://www.capterra.com/p/134048/HiMama-Preschool-Child-Care-App/#reviews"
Data = []
#Each page equivalant to 50 comments:
MaximumCommentPages = 3

with requests.Session() as session:
    info = session.get(url)
    #Get product ID, needed for getting more comments
    productID = re.search(r'"product_id":(\w*)', info.text).group(1)
    #Extract info from main data
    soup = BeautifulSoup(info.content, "html.parser")
    table = soup.findAll("div", {"class":"review-comments"})
    for x in table:
        Data.append(x)
    #Number of pages to get:
    #Get additional data:
    params = {
        "page": "",
        "product_id": productID
    }
    while(MaximumCommentPages > 1): # number 1 because one of them was the main page data which we already extracted!
        MaximumCommentPages -= 1
        params["page"] = str(MaximumCommentPages)
        additionalInfo = session.get("https://www.capterra.com/gdm_reviews", params=params)
        print(additionalInfo.url)
        #print(additionalInfo.text)
        #Extract info for additional info:
        soup = BeautifulSoup(additionalInfo.content, "html.parser")
        table = soup.findAll("div", {"class":"review-comments"})
        for x in table:
            Data.append(x)

#Extract data the old fashioned way:
counter = 1
with open('review.csv', 'w') as f:
    for one in Data:
        f.write(str(counter))
        f.write(one.text)
        f.write('\n')
        counter += 1
```

Notice how I'm using a session to preserve cookies for the ajax call.

Edit 1: You can reload the webpage multiple times and call the ajax again to get even more data.

Edit 2: Save data using your own method.

Edit 3: Changed some stuff, now gets any number of pages for you, saves to file with good' ol open()

Title: Not able to scrape the all the reviews

Body:
I am trying to scrape this website and trying to get the reviews but I am facing an issue,

The page loads only 50 reviews.

To load more you have to click "Show More Reviews" and I don't know how to get all the data as there is no page link, also "Show more Reviews" doesn't have a URL to explore, the address remains the same.

url =
  "https://www.capterra.com/p/134048/HiMama-Preschool-Child-Care-App/#reviews"

import requests
from bs4 import BeautifulSoup
import json
import pandas as pd
a = []

url = requests.get(url)
html = url.text
soup = BeautifulSoup(html, "html.parser")

table = soup.findAll("div", {"class":"review-comments"})
#print(table)
for x in table:
    a.append(x.text)
df = pd.DataFrame(a)
df.to_csv("review.csv", sep='\t')

I know this is not pretty code but I am just trying to get the review text first.
kindly help. As I am little new to this.

Body:
Looking at the website, the "Show more reviews" button makes an ajax call and returns the additional info, all you have to do is find it's link and send a get request to it (which I've done with some simple regex):

import requests
import re
from bs4 import BeautifulSoup
headers = {
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) snap Chromium/74.0.3729.169 Chrome/74.0.3729.169 Safari/537.36"
}
url = "https://www.capterra.com/p/134048/HiMama-Preschool-Child-Care-App/#reviews"
Data = []
#Each page equivalant to 50 comments:
MaximumCommentPages = 3

with requests.Session() as session:
    info = session.get(url)
    #Get product ID, needed for getting more comments
    productID = re.search(r'"product_id":(\w*)', info.text).group(1)
    #Extract info from main data
    soup = BeautifulSoup(info.content, "html.parser")
    table = soup.findAll("div", {"class":"review-comments"})
    for x in table:
        Data.append(x)
    #Number of pages to get:
    #Get additional data:
    params = {
        "page": "",
        "product_id": productID
    }
    while(MaximumCommentPages > 1): # number 1 because one of them was the main page data which we already extracted!
        MaximumCommentPages -= 1
        params["page"] = str(MaximumCommentPages)
        additionalInfo = session.get("https://www.capterra.com/gdm_reviews", params=params)
        print(additionalInfo.url)
        #print(additionalInfo.text)
        #Extract info for additional info:
        soup = BeautifulSoup(additionalInfo.content, "html.parser")
        table = soup.findAll("div", {"class":"review-comments"})
        for x in table:
            Data.append(x)

#Extract data the old fashioned way:
counter = 1
with open('review.csv', 'w') as f:
    for one in Data:
        f.write(str(counter))
        f.write(one.text)
        f.write('\n')
        counter += 1

Notice how I'm using a session to preserve cookies for the ajax call.

Edit 1: You can reload the webpage multiple times and call the ajax again to get even more data.

Edit 2: Save data using your own method.

Edit 3: Changed some stuff, now gets any number of pages for you, saves to file with good' ol open()


问:
Rails associations using an array as the foreign_id
I am looking to create an association where a model can be created and owned by three different entities but also references the other two entities.

For example, I have a performance model where three different types of models can create a performance: venue, artist, band. However, the performance also needs to reference the other two e.g if a venue creates a performance, it needs to list an artist or a band that will be performing. And if an artist creates a performance, then the artist needs to put a venue where he/she will be performing.

So I am starting with something like this:

```<code>class CreatePerformances < ActiveRecord::Migration[6.0]
  def change
    create_table :performances, id: :uuid do |t|
      t.belongs_to :venue, index: true
      t.belongs_to :artist, index: true
      t.belongs_to :band, index: true
      t.timestamps
    end
  end
end
</code>```

However, if a venue owner creates a performance and has two separate bands performing then I would need to have an array of bands in the band_id column. But when I do that (t.belongs_to :band, type: :uuid, array: true, default: [], index: true) and add a band to the band_id array and then do band.performances I get: ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR:  malformed array literal:

Can I make an association column an array and still be able to use the Rails association features or is that not possible or even bad practice, and if so how?

Also, I am using postgresql and if you have a more elegant ways of doing the above that would also be appreciated.

答:
I guess it's better to use a has_many relationship.

If a performance can have many bands playing then it does not "belongs to" a band, it "has many" bands.

So you may use a "has and belongs to many" or a "has many :through" relationship between performances and bands. Check the differences here https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

The easiest of the two to configure is HABTM:

```<code>class Band
  has_and_belongs_to_many :performances

class Performance
  has_and_belongs_to_many :bands
</code>```

You need a table, so add a miration that does this:

```<code>create_table :bands_performances, id: false do |t|
  t.references :band, index: true
  t.references :performance, index: true
end
</code>```

https://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has-and-belongs-to-many-associations

Check the guide, if you need extra fields you may need a join model and use has_many :through. You know the context better than anyone.

Body:
I am looking to create an association where a model can be created and owned by three different entities but also references the other two entities.

For example, I have a performance model where three different types of models can create a performance: venue, artist, band. However, the performance also needs to reference the other two e.g if a venue creates a performance, it needs to list an artist or a band that will be performing. And if an artist creates a performance, then the artist needs to put a venue where he/she will be performing.

So I am starting with something like this:

class CreatePerformances < ActiveRecord::Migration[6.0]
  def change
    create_table :performances, id: :uuid do |t|
      t.belongs_to :venue, index: true
      t.belongs_to :artist, index: true
      t.belongs_to :band, index: true
      t.timestamps
    end
  end
end

However, if a venue owner creates a performance and has two separate bands performing then I would need to have an array of bands in the band_id column. But when I do that (t.belongs_to :band, type: :uuid, array: true, default: [], index: true) and add a band to the band_id array and then do band.performances I get: ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR:  malformed array literal:

Can I make an association column an array and still be able to use the Rails association features or is that not possible or even bad practice, and if so how?

Also, I am using postgresql and if you have a more elegant ways of doing the above that would also be appreciated.

Body:
I guess it's better to use a has_many relationship.

If a performance can have many bands playing then it does not "belongs to" a band, it "has many" bands.

So you may use a "has and belongs to many" or a "has many :through" relationship between performances and bands. Check the differences here https://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many

The easiest of the two to configure is HABTM:

class Band
  has_and_belongs_to_many :performances

class Performance
  has_and_belongs_to_many :bands

You need a table, so add a miration that does this:

create_table :bands_performances, id: false do |t|
  t.references :band, index: true
  t.references :performance, index: true
end

https://guides.rubyonrails.org/association_basics.html#creating-join-tables-for-has-and-belongs-to-many-associations

Check the guide, if you need extra fields you may need a join model and use has_many :through. You know the context better than anyone.


问:
How to get last month record from databse in laravel?

i have a table remaining_bus_fees.

```<code>id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300
</code>```

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

```<code>$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();
</code>```

答:
Try this out,

```<code>$remain_fee = \DB::table('remaining_bus_fees')
    ->whereMonth('date', '=', Carbon::now()->subMonth()->month)
    ->whereStudentId(2)->get();
</code>```

Body:
i have a table remaining_bus_fees.

id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();

Body:
Try this out,

$remain_fee = \DB::table('remaining_bus_fees')
    ->whereMonth('date', '=', Carbon::now()->subMonth()->month)
    ->whereStudentId(2)->get();


问:
ExternalInterface passing values from swf to an iFrame on the same page
On a page I have a an iFrame and a swf, I've been trying to use ExternalInterface to pass values from the swf to the iFrame, anyone ever tried this and had any luck? I won't be able to post any code until tomorrow, will update then if needed.

Thanks in adavnce.

Here is a visualization of what I need to accomplish, perhaps if it can't be done the way I said someone will have a suggestion of another way to accomplish this.

答: You cannot access iframes from outside of them. These are security reasons, and browsers will and should block such attempts.</p>