问:
Training and Predicting with instance keys
I am able to train my model and use ML Engine for prediction but my results don't include any identifying information. This works fine when submitting one row at a time for prediction but when submitting multiple rows I have no way of connecting the prediction back to the original input data. The GCP documentation discusses using instance keys but I can't find any example code that trains and predicts using an instance key. Taking the GCP census example how would I update the input functions to pass a unique ID through the graph and ignore it during training yet return the unique ID with predictions? Or alternatively if anyone knows of a different example already using keys that would help as well.

From Census Estimator Sample

```<code>def serving_input_fn():
    feature_placeholders = {
      column.name: tf.placeholder(column.dtype, [None])
      for column in INPUT_COLUMNS
    }

    features = {
      key: tf.expand_dims(tensor, -1)
      for key, tensor in feature_placeholders.items()
    }

    return input_fn_utils.InputFnOps(
      features,
      None,
      feature_placeholders
    )

def generate_input_fn(filenames,
                  num_epochs=None,
                  shuffle=True,
                  skip_header_lines=0,
                  batch_size=40):

    def _input_fn():
        files = tf.concat([
          tf.train.match_filenames_once(filename)
          for filename in filenames
        ], axis=0)

        filename_queue = tf.train.string_input_producer(
          files, num_epochs=num_epochs, shuffle=shuffle)
        reader = tf.TextLineReader(skip_header_lines=skip_header_lines)

        _, rows = reader.read_up_to(filename_queue, num_records=batch_size)

        row_columns = tf.expand_dims(rows, -1)
        columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
        features = dict(zip(CSV_COLUMNS, columns))

        # Remove unused columns
        for col in UNUSED_COLUMNS:
          features.pop(col)

        if shuffle:
           features = tf.train.shuffle_batch(
             features,
             batch_size,
             capacity=batch_size * 10,
             min_after_dequeue=batch_size*2 + 1,
             num_threads=multiprocessing.cpu_count(),
             enqueue_many=True,
             allow_smaller_final_batch=True
           )
        label_tensor = parse_label_column(features.pop(LABEL_COLUMN))
        return features, label_tensor

    return _input_fn
</code>```

Update:
I was able to use the suggested code from this answer below I just needed to alter it slightly to update the output alternatives in the model_fn_ops instead of just the prediction dict. However, this only works if my serving input function is coded for json inputs similar to this. My serving input function was previously modeled after the CSV serving input function in the Census Core Sample.

I think my problem is coming from the build_standardized_signature_def function and even more so the is_classification_problem function that it calls. The input dict length using the csv serving function is 1 so this logic ends up using the classification_signature_def which only ends up displaying the scores (which turns out are actually the probabilities) whereas the input dict length is greater than 1 with the json serving input function and instead the predict_signature_def is used which includes all of the outputs.

答:
UPDATE: In version 1.3 the contrib estimators (tf.contrib.learn.DNNClassifier for example), were changed to inherit from the core estimator class tf.estimator.Estimator which unlike it's predecessor, hides the model function as a private class member, so you'll need to replace estimator.model_fn in the solution below with estimator._model_fn.

Josh's answer points you to the Flowers example, which is a good solution if you want to use a custom estimator. If you want to stick with a canned estimator, (e.g. the tf.contrib.learn.DNNClassifiers) you can wrap it in a custom estimator that adds support for keys. (Note: I think it's likely canned estimators will gain key support when they move into core).

```<code>KEY = 'key'
def key_model_fn_gen(estimator):
    def _model_fn(features, labels, mode, params):
        key = features.pop(KEY, None)
        model_fn_ops = estimator.model_fn(
           features=features, labels=labels, mode=mode, params=params)
        if key:
            model_fn_ops.predictions[KEY] = key
            # This line makes it so the exported SavedModel will also require a key
            model_fn_ops.output_alternatives[None][1][KEY] = key
        return model_fn_ops
    return _model_fn

my_key_estimator = tf.contrib.learn.Estimator(
    model_fn=key_model_fn_gen(
        tf.contrib.learn.DNNClassifier(model_dir=model_dir...)
    ),
    model_dir=model_dir
)
</code>```

my_key_estimator can then be used exactly like your DNNClassifier would be used, except it will expect a feature with the name 'key' from input_fns (prediction, evaluation and training).

EDIT2:
You will also need to add the corresponding input tensor to the prediction input function of your choice. For example, a new JSON serving input fn would look like:

```<code>def json_serving_input_fn():
  inputs = # ... input_dict as before
  inputs[KEY] = tf.placeholder([None], dtype=tf.int64)
  features = # .. feature dict made from input_dict as before
  tf.contrib.learn.InputFnOps(features, None, inputs)
</code>```

(slightly different between 1.2 and 1.3, as tf.contrib.learn.InputFnOps is replaced with tf.estimator.export.ServingInputReceiver, and padding tensors to rank 2 is no longer necessary in 1.3)

Then ML Engine will send a tensor named "key" with your prediction request, which will be passed to your model, and through with your predictions.

EDIT3: Modified key_model_fn_gen to support ignoring missing key values.
EDIT4: Added key for prediction

Body:
I am able to train my model and use ML Engine for prediction but my results don't include any identifying information. This works fine when submitting one row at a time for prediction but when submitting multiple rows I have no way of connecting the prediction back to the original input data. The GCP documentation discusses using instance keys but I can't find any example code that trains and predicts using an instance key. Taking the GCP census example how would I update the input functions to pass a unique ID through the graph and ignore it during training yet return the unique ID with predictions? Or alternatively if anyone knows of a different example already using keys that would help as well.

From Census Estimator Sample

def serving_input_fn():
    feature_placeholders = {
      column.name: tf.placeholder(column.dtype, [None])
      for column in INPUT_COLUMNS
    }

    features = {
      key: tf.expand_dims(tensor, -1)
      for key, tensor in feature_placeholders.items()
    }

    return input_fn_utils.InputFnOps(
      features,
      None,
      feature_placeholders
    )

def generate_input_fn(filenames,
                  num_epochs=None,
                  shuffle=True,
                  skip_header_lines=0,
                  batch_size=40):

    def _input_fn():
        files = tf.concat([
          tf.train.match_filenames_once(filename)
          for filename in filenames
        ], axis=0)

        filename_queue = tf.train.string_input_producer(
          files, num_epochs=num_epochs, shuffle=shuffle)
        reader = tf.TextLineReader(skip_header_lines=skip_header_lines)

        _, rows = reader.read_up_to(filename_queue, num_records=batch_size)

        row_columns = tf.expand_dims(rows, -1)
        columns = tf.decode_csv(row_columns, record_defaults=CSV_COLUMN_DEFAULTS)
        features = dict(zip(CSV_COLUMNS, columns))

        # Remove unused columns
        for col in UNUSED_COLUMNS:
          features.pop(col)

        if shuffle:
           features = tf.train.shuffle_batch(
             features,
             batch_size,
             capacity=batch_size * 10,
             min_after_dequeue=batch_size*2 + 1,
             num_threads=multiprocessing.cpu_count(),
             enqueue_many=True,
             allow_smaller_final_batch=True
           )
        label_tensor = parse_label_column(features.pop(LABEL_COLUMN))
        return features, label_tensor

    return _input_fn

Update:
I was able to use the suggested code from this answer below I just needed to alter it slightly to update the output alternatives in the model_fn_ops instead of just the prediction dict. However, this only works if my serving input function is coded for json inputs similar to this. My serving input function was previously modeled after the CSV serving input function in the Census Core Sample.

I think my problem is coming from the build_standardized_signature_def function and even more so the is_classification_problem function that it calls. The input dict length using the csv serving function is 1 so this logic ends up using the classification_signature_def which only ends up displaying the scores (which turns out are actually the probabilities) whereas the input dict length is greater than 1 with the json serving input function and instead the predict_signature_def is used which includes all of the outputs.

Body:
UPDATE: In version 1.3 the contrib estimators (tf.contrib.learn.DNNClassifier for example), were changed to inherit from the core estimator class tf.estimator.Estimator which unlike it's predecessor, hides the model function as a private class member, so you'll need to replace estimator.model_fn in the solution below with estimator._model_fn.

Josh's answer points you to the Flowers example, which is a good solution if you want to use a custom estimator. If you want to stick with a canned estimator, (e.g. the tf.contrib.learn.DNNClassifiers) you can wrap it in a custom estimator that adds support for keys. (Note: I think it's likely canned estimators will gain key support when they move into core).

KEY = 'key'
def key_model_fn_gen(estimator):
    def _model_fn(features, labels, mode, params):
        key = features.pop(KEY, None)
        model_fn_ops = estimator.model_fn(
           features=features, labels=labels, mode=mode, params=params)
        if key:
            model_fn_ops.predictions[KEY] = key
            # This line makes it so the exported SavedModel will also require a key
            model_fn_ops.output_alternatives[None][1][KEY] = key
        return model_fn_ops
    return _model_fn

my_key_estimator = tf.contrib.learn.Estimator(
    model_fn=key_model_fn_gen(
        tf.contrib.learn.DNNClassifier(model_dir=model_dir...)
    ),
    model_dir=model_dir
)

my_key_estimator can then be used exactly like your DNNClassifier would be used, except it will expect a feature with the name 'key' from input_fns (prediction, evaluation and training).

EDIT2:
You will also need to add the corresponding input tensor to the prediction input function of your choice. For example, a new JSON serving input fn would look like:

def json_serving_input_fn():
  inputs = # ... input_dict as before
  inputs[KEY] = tf.placeholder([None], dtype=tf.int64)
  features = # .. feature dict made from input_dict as before
  tf.contrib.learn.InputFnOps(features, None, inputs)

(slightly different between 1.2 and 1.3, as tf.contrib.learn.InputFnOps is replaced with tf.estimator.export.ServingInputReceiver, and padding tensors to rank 2 is no longer necessary in 1.3)

Then ML Engine will send a tensor named "key" with your prediction request, which will be passed to your model, and through with your predictions.

EDIT3: Modified key_model_fn_gen to support ignoring missing key values.
EDIT4: Added key for prediction


来源: stackexchange

问:
Does a heaviside step function exist?
Is there a heaviside function in Python similar to that of MATLAB's heaviside?

I am struggling to find one.

答: As of numpy 1.13, it is numpy.heaviside.

ContentLicense: CC BY-SA 3.0

Title: Does a heaviside step function exist?


问:
Using checkbox in a recycler view row causes the row to not display all its content
My recycler view row layout below. The recycler view is used without particular attribute.

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="test"/>

</LinearLayout>
</code>```

My 2 lines texts are cut in height when the checkbox is used in the layout and displayed entirely when the checkbox is removed ???

答:
Hope this helps you.</p>

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/activity_vertical_margin"
    android:layout_marginStart="@dimen/activity_vertical_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:orientation="horizontal">

        <TextView
            android:id="@+id/firstTV"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:layout_weight="3"
            android:textSize="15sp"
            android:textColor="#484848"
            android:layout_marginBottom="10dp"
            android:text="@string/firstTV" />

        <CheckBox
            android:id="@+id/checkbox_ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:layout_gravity="center"/>

</LinearLayout>
</code>```

Body:
My recycler view row layout below. The recycler view is used without particular attribute.

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<CheckBox
    android:id="@+id/checkbox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="test"/>

</LinearLayout>

My 2 lines texts are cut in height when the checkbox is used in the layout and displayed entirely when the checkbox is removed ???

Body:
Hope this helps you.

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/activity_vertical_margin"
    android:layout_marginStart="@dimen/activity_vertical_margin"
    android:layout_marginTop="@dimen/activity_vertical_margin"
    android:orientation="horizontal">

        <TextView
            android:id="@+id/firstTV"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:layout_weight="3"
            android:textSize="15sp"
            android:textColor="#484848"
            android:layout_marginBottom="10dp"
            android:text="@string/firstTV" />

        <CheckBox
            android:id="@+id/checkbox_ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:layout_gravity="center"/>

</LinearLayout>


问:
Virtual destructor for CustomVertex in DIRECTX9
This is my first question on stackoverflow, so forgive me if my question is dumb.
I am trying to simply render a triangle in DirectX9 in Visual Studio 2012 following this: www.directxtutorial.com/Lesson.aspx?lessonid=9-4-4.

When I create a CUSTOMVERTEX class with a non-virtual destructor it renders the triangle without any problem. Whereas if I make the destructor virtual the triangle is not rendered.

Here is the code with the virtual destructor:

```<code>// include the basic windows header files and the Direct3D header file
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>

// define the screen resolution
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the Direct3D Library file
#pragma comment (lib, "d3d9.lib")

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

// global declarations
LPDIRECT3D9 d3d;    // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev;    // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;    // the pointer to the vertex buffer

// function prototypes
void initD3D(HWND hWnd);    // sets up and initializes Direct3D
void render_frame(void);    // renders a single frame
void cleanD3D(void);    // closes Direct3D and releases memory
void init_graphics(void);    // 3D declarations
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//************CUSTOMVERTEX CLASS**********/
class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    virtual ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";

    RegisterClassEx(&wc);

    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          "Our Direct3D Program",
                          WS_OVERLAPPEDWINDOW,
                          0, 0,
                          SCREEN_WIDTH, SCREEN_HEIGHT,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    initD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while(TRUE)
    {
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if(msg.message == WM_QUIT)
            break;

        render_frame();
    }

    // clean up DirectX and COM
    cleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_DESTROY:
            {
                PostQuitMessage(0);
                return 0;
            } break;
    }

    return DefWindowProc (hWnd, message, wParam, lParam);
}

// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS d3dpp;

    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow = hWnd;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferWidth = SCREEN_WIDTH;
    d3dpp.BackBufferHeight = SCREEN_HEIGHT;

    // create a device class using this information and the info from the d3dpp struct
    d3d->CreateDevice(D3DADAPTER_DEFAULT,
                      D3DDEVTYPE_HAL,
                      hWnd,
                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                      &d3dpp,
                      &d3ddev);

    init_graphics();    // call the function to initialize the triangle
}

// this is the function used to render a single frame
void render_frame(void)
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

    d3ddev->BeginScene();

        // select which vertex format we are using
        d3ddev->SetFVF(CUSTOMFVF);

        // select the vertex buffer to display
        d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));

        // copy the vertex buffer to the back buffer
        d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    d3ddev->EndScene();

    d3ddev->Present(NULL, NULL, NULL, NULL);
}

// this is the function that cleans up Direct3D and COM
void cleanD3D(void)
{
    v_buffer->Release();    // close and release the vertex buffer
    d3ddev->Release();    // close and release the 3D device
    d3d->Release();    // close and release Direct3D
}

// this is the function that puts the 3D models into video RAM
void init_graphics(void)
{
    // create the vertices using the CUSTOMVERTEX class
    CUSTOMVERTEX vertices[] =
    {
        CUSTOMVERTEX(400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255)),
        CUSTOMVERTEX(650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0)),
        CUSTOMVERTEX(150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0)),
    };

    // create a vertex buffer interface called v_buffer
    d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),
                               0,
                               CUSTOMFVF,
                               D3DPOOL_MANAGED,
                               &v_buffer,
                               NULL);

    VOID* pVoid;    // a void pointer

    // lock v_buffer and load the vertices into it
    v_buffer->Lock(0, 0, (void**)&pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    v_buffer->Unlock();
}
</code>```

Rendered triangle:Rendered Triangle

The code without virtual destructor:

```<code>// include the basic windows header files and the Direct3D header file
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>

// define the screen resolution
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the Direct3D Library file
#pragma comment (lib, "d3d9.lib")

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

// global declarations
LPDIRECT3D9 d3d;    // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev;    // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;    // the pointer to the vertex buffer

// function prototypes
void initD3D(HWND hWnd);    // sets up and initializes Direct3D
void render_frame(void);    // renders a single frame
void cleanD3D(void);    // closes Direct3D and releases memory
void init_graphics(void);    // 3D declarations
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//************CUSTOMVERTEX CLASS**********/
class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";

    RegisterClassEx(&wc);

    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          "Our Direct3D Program",
                          WS_OVERLAPPEDWINDOW,
                          0, 0,
                          SCREEN_WIDTH, SCREEN_HEIGHT,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    initD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while(TRUE)
    {
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if(msg.message == WM_QUIT)
            break;

        render_frame();
    }

    // clean up DirectX and COM
    cleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_DESTROY:
            {
                PostQuitMessage(0);
                return 0;
            } break;
    }

    return DefWindowProc (hWnd, message, wParam, lParam);
}

// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS d3dpp;

    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow = hWnd;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferWidth = SCREEN_WIDTH;
    d3dpp.BackBufferHeight = SCREEN_HEIGHT;

    // create a device class using this information and the info from the d3dpp struct
    d3d->CreateDevice(D3DADAPTER_DEFAULT,
                      D3DDEVTYPE_HAL,
                      hWnd,
                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                      &d3dpp,
                      &d3ddev);

    init_graphics();    // call the function to initialize the triangle
}

// this is the function used to render a single frame
void render_frame(void)
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

    d3ddev->BeginScene();

        // select which vertex format we are using
        d3ddev->SetFVF(CUSTOMFVF);

        // select the vertex buffer to display
        d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));

        // copy the vertex buffer to the back buffer
        d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    d3ddev->EndScene();

    d3ddev->Present(NULL, NULL, NULL, NULL);
}

// this is the function that cleans up Direct3D and COM
void cleanD3D(void)
{
    v_buffer->Release();    // close and release the vertex buffer
    d3ddev->Release();    // close and release the 3D device
    d3d->Release();    // close and release Direct3D
}

// this is the function that puts the 3D models into video RAM
void init_graphics(void)
{
    // create the vertices using the CUSTOMVERTEX class
    CUSTOMVERTEX vertices[] =
    {
        CUSTOMVERTEX(400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255)),
        CUSTOMVERTEX(650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0)),
        CUSTOMVERTEX(150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0)),
    };

    // create a vertex buffer interface called v_buffer
    d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),
                               0,
                               CUSTOMFVF,
                               D3DPOOL_MANAGED,
                               &v_buffer,
                               NULL);

    VOID* pVoid;    // a void pointer

    // lock v_buffer and load the vertices into it
    v_buffer->Lock(0, 0, (void**)&pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    v_buffer->Unlock();
}
</code>```

Rendered without any triangle: without any triangle

Can anyone please explain to me why this is happening?

答:
In short: Adding the virtual changes the memory layout of the structure, meaning your data is no longer in the correct place for the Vertex Declaration you provided:

```<code>struct CUSTOMVERTEX {
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    float X, Y, Z, RHW;
    DWORD COLOR;
};
</code>```

The size of this structure is 20 bytes.

```<code>class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    virtual ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};
</code>```

The size of this structure is 24 bytes for x86 (Win32) and 32 bytes for x64 native. This is because there's a pointer to the vtable added at the start of the structure (and on x64 the additional padding pushes it out a little more than 8 bytes).

Furthermore, since you are using the type through a Direct3D Vertex Buffer, it's never going to have it's constructor or destructor executed. It's just allocated from the heap as a "plain old data type". The only time constructors or destructors are invoked for heap-allocated memory is via new, new [], delete, and/or delete []. Internally Direct3D Vertex Buffer is doing something more akin to malloc.

Your constructor is being invoked by the C++ compiler when you create the initialized array vertices, and the destructor is invoked when vertices goes out of scope.

In other words: This doesn't do what you think it does. Don't use virtual in your vertex data structures.

Note that you should consider making using of a smart pointer like Microsoft::WRL::ComPtr for managing the lifetime of your Direct3D COM objects. This takes advantage of the C++ scoping rules for ctors/destructors to properly call Release automatically. Of course, you should also not be spending a lot of time learning legacy Direc3D 9 either.

Body:
This is my first question on stackoverflow, so forgive me if my question is dumb.
I am trying to simply render a triangle in DirectX9 in Visual Studio 2012 following this: www.directxtutorial.com/Lesson.aspx?lessonid=9-4-4.

When I create a CUSTOMVERTEX class with a non-virtual destructor it renders the triangle without any problem. Whereas if I make the destructor virtual the triangle is not rendered.

Here is the code with the virtual destructor:

// include the basic windows header files and the Direct3D header file
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>

// define the screen resolution
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the Direct3D Library file
#pragma comment (lib, "d3d9.lib")

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

// global declarations
LPDIRECT3D9 d3d;    // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev;    // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;    // the pointer to the vertex buffer

// function prototypes
void initD3D(HWND hWnd);    // sets up and initializes Direct3D
void render_frame(void);    // renders a single frame
void cleanD3D(void);    // closes Direct3D and releases memory
void init_graphics(void);    // 3D declarations
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//************CUSTOMVERTEX CLASS**********/
class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    virtual ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";

    RegisterClassEx(&wc);

    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          "Our Direct3D Program",
                          WS_OVERLAPPEDWINDOW,
                          0, 0,
                          SCREEN_WIDTH, SCREEN_HEIGHT,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    initD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while(TRUE)
    {
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if(msg.message == WM_QUIT)
            break;

        render_frame();
    }

    // clean up DirectX and COM
    cleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_DESTROY:
            {
                PostQuitMessage(0);
                return 0;
            } break;
    }

    return DefWindowProc (hWnd, message, wParam, lParam);
}

// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS d3dpp;

    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow = hWnd;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferWidth = SCREEN_WIDTH;
    d3dpp.BackBufferHeight = SCREEN_HEIGHT;

    // create a device class using this information and the info from the d3dpp struct
    d3d->CreateDevice(D3DADAPTER_DEFAULT,
                      D3DDEVTYPE_HAL,
                      hWnd,
                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                      &d3dpp,
                      &d3ddev);

    init_graphics();    // call the function to initialize the triangle
}

// this is the function used to render a single frame
void render_frame(void)
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

    d3ddev->BeginScene();

        // select which vertex format we are using
        d3ddev->SetFVF(CUSTOMFVF);

        // select the vertex buffer to display
        d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));

        // copy the vertex buffer to the back buffer
        d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    d3ddev->EndScene();

    d3ddev->Present(NULL, NULL, NULL, NULL);
}

// this is the function that cleans up Direct3D and COM
void cleanD3D(void)
{
    v_buffer->Release();    // close and release the vertex buffer
    d3ddev->Release();    // close and release the 3D device
    d3d->Release();    // close and release Direct3D
}

// this is the function that puts the 3D models into video RAM
void init_graphics(void)
{
    // create the vertices using the CUSTOMVERTEX class
    CUSTOMVERTEX vertices[] =
    {
        CUSTOMVERTEX(400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255)),
        CUSTOMVERTEX(650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0)),
        CUSTOMVERTEX(150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0)),
    };

    // create a vertex buffer interface called v_buffer
    d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),
                               0,
                               CUSTOMFVF,
                               D3DPOOL_MANAGED,
                               &v_buffer,
                               NULL);

    VOID* pVoid;    // a void pointer

    // lock v_buffer and load the vertices into it
    v_buffer->Lock(0, 0, (void**)&pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    v_buffer->Unlock();
}

Rendered triangle:Rendered Triangle

The code without virtual destructor:

// include the basic windows header files and the Direct3D header file
#include <windows.h>
#include <windowsx.h>
#include <d3d9.h>

// define the screen resolution
#define SCREEN_WIDTH 800
#define SCREEN_HEIGHT 600

// include the Direct3D Library file
#pragma comment (lib, "d3d9.lib")

#define CUSTOMFVF (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

// global declarations
LPDIRECT3D9 d3d;    // the pointer to our Direct3D interface
LPDIRECT3DDEVICE9 d3ddev;    // the pointer to the device class
LPDIRECT3DVERTEXBUFFER9 v_buffer = NULL;    // the pointer to the vertex buffer

// function prototypes
void initD3D(HWND hWnd);    // sets up and initializes Direct3D
void render_frame(void);    // renders a single frame
void cleanD3D(void);    // closes Direct3D and releases memory
void init_graphics(void);    // 3D declarations
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

//************CUSTOMVERTEX CLASS**********/
class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    HWND hWnd;
    WNDCLASSEX wc;

    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";

    RegisterClassEx(&wc);

    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          "Our Direct3D Program",
                          WS_OVERLAPPEDWINDOW,
                          0, 0,
                          SCREEN_WIDTH, SCREEN_HEIGHT,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);

    ShowWindow(hWnd, nCmdShow);

    // set up and initialize Direct3D
    initD3D(hWnd);

    // enter the main loop:

    MSG msg;

    while(TRUE)
    {
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if(msg.message == WM_QUIT)
            break;

        render_frame();
    }

    // clean up DirectX and COM
    cleanD3D();

    return msg.wParam;
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_DESTROY:
            {
                PostQuitMessage(0);
                return 0;
            } break;
    }

    return DefWindowProc (hWnd, message, wParam, lParam);
}

// this function initializes and prepares Direct3D for use
void initD3D(HWND hWnd)
{
    d3d = Direct3DCreate9(D3D_SDK_VERSION);

    D3DPRESENT_PARAMETERS d3dpp;

    ZeroMemory(&d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow = hWnd;
    d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferWidth = SCREEN_WIDTH;
    d3dpp.BackBufferHeight = SCREEN_HEIGHT;

    // create a device class using this information and the info from the d3dpp struct
    d3d->CreateDevice(D3DADAPTER_DEFAULT,
                      D3DDEVTYPE_HAL,
                      hWnd,
                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                      &d3dpp,
                      &d3ddev);

    init_graphics();    // call the function to initialize the triangle
}

// this is the function used to render a single frame
void render_frame(void)
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

    d3ddev->BeginScene();

        // select which vertex format we are using
        d3ddev->SetFVF(CUSTOMFVF);

        // select the vertex buffer to display
        d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));

        // copy the vertex buffer to the back buffer
        d3ddev->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

    d3ddev->EndScene();

    d3ddev->Present(NULL, NULL, NULL, NULL);
}

// this is the function that cleans up Direct3D and COM
void cleanD3D(void)
{
    v_buffer->Release();    // close and release the vertex buffer
    d3ddev->Release();    // close and release the 3D device
    d3d->Release();    // close and release Direct3D
}

// this is the function that puts the 3D models into video RAM
void init_graphics(void)
{
    // create the vertices using the CUSTOMVERTEX class
    CUSTOMVERTEX vertices[] =
    {
        CUSTOMVERTEX(400.0f, 62.5f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 0, 255)),
        CUSTOMVERTEX(650.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(0, 255, 0)),
        CUSTOMVERTEX(150.0f, 500.0f, 0.5f, 1.0f, D3DCOLOR_XRGB(255, 0, 0)),
    };

    // create a vertex buffer interface called v_buffer
    d3ddev->CreateVertexBuffer(3*sizeof(CUSTOMVERTEX),
                               0,
                               CUSTOMFVF,
                               D3DPOOL_MANAGED,
                               &v_buffer,
                               NULL);

    VOID* pVoid;    // a void pointer

    // lock v_buffer and load the vertices into it
    v_buffer->Lock(0, 0, (void**)&pVoid, 0);
    memcpy(pVoid, vertices, sizeof(vertices));
    v_buffer->Unlock();
}

Rendered without any triangle: without any triangle

Can anyone please explain to me why this is happening?

Body:
In short: Adding the virtual changes the memory layout of the structure, meaning your data is no longer in the correct place for the Vertex Declaration you provided:

struct CUSTOMVERTEX {
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    float X, Y, Z, RHW;
    DWORD COLOR;
};

The size of this structure is 20 bytes.

class CUSTOMVERTEX {
public:
    CUSTOMVERTEX( float _X, float _Y, float _Z, float _RHW, DWORD _COLOR )
        : X(_X), Y(_Y), Z(_Z), RHW(_RHW), COLOR(_COLOR)
    {}

    virtual ~CUSTOMVERTEX(){
        OutputDebugString("Destructed!!!\n");
    }
    float X, Y, Z, RHW;
    DWORD COLOR;
};

The size of this structure is 24 bytes for x86 (Win32) and 32 bytes for x64 native. This is because there's a pointer to the vtable added at the start of the structure (and on x64 the additional padding pushes it out a little more than 8 bytes).

Furthermore, since you are using the type through a Direct3D Vertex Buffer, it's never going to have it's constructor or destructor executed. It's just allocated from the heap as a "plain old data type". The only time constructors or destructors are invoked for heap-allocated memory is via new, new [], delete, and/or delete []. Internally Direct3D Vertex Buffer is doing something more akin to malloc.

Your constructor is being invoked by the C++ compiler when you create the initialized array vertices, and the destructor is invoked when vertices goes out of scope.

In other words: This doesn't do what you think it does. Don't use virtual in your vertex data structures.

Note that you should consider making using of a smart pointer like Microsoft::WRL::ComPtr for managing the lifetime of your Direct3D COM objects. This takes advantage of the C++ scoping rules for ctors/destructors to properly call Release automatically. Of course, you should also not be spending a lot of time learning legacy Direc3D 9 either.


问:
Scala subString function
Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).</p>

```<code>def subStringEn(input:String,start:Int,end:Int)={
  // multiple if check for avoiding index out of bound exception
    input.substring(start,end)
}
</code>```

答:
Try is one way of doing it. The other way is applying substring only if length is greater than end using Option[String].

invalid end index

```<code>scala> val start = 1
start: Int = 1

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res9: Option[String] = None
</code>```

valid end index

```<code>scala> val end = 6
end: Int = 6

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)
</code>```

Also, you can combine filter and map to .collect as below,

```<code>scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res14: Option[String] = Some(rayag)

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res15: Option[String] = None
</code>```

Title: Scala subString function

Body:
Hi I am looking for a solution it will return a substring from string for the given indexes.For avoiding index bound exception currently using if and else check.Is there a better approach(functional).

def subStringEn(input:String,start:Int,end:Int)={
  // multiple if check for avoiding index out of bound exception
    input.substring(start,end)
}

Body:
Try is one way of doing it. The other way is applying substring only if length is greater than end using Option[String].

invalid end index

scala> val start = 1
start: Int = 1

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res9: Option[String] = None

valid end index

scala> val end = 6
end: Int = 6

scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)

Also, you can combine filter and map to .collect as below,

scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res14: Option[String] = Some(rayag)

scala> val end = 1000
end: Int = 1000

scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res15: Option[String] = None


问:
Wordpress Pagination - can't access to second page
I use WP Beginner pagination (without plugin) on my website, but I can't access to second and other pages.

```<code><?php

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

 $custom_query_args = array(
        'post_type' => array( 'tutorials','post' ),
        'posts_per_page' => 2,
        'cat' => $cat_id,
 );

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
        while ( $custom_query->have_posts() ) :
                        $custom_query->the_post();

            echo '<article class="other-post col-xs-12 col-sm-12 col-md-3 col-lg-3">';
            echo '<div class="back-color">';
            echo '<h3>';
            echo the_post_thumbnail('post-thumbnail', array( 'class' => 'post-image' ));
            echo '<a href="'. get_permalink() .'" title="'. get_the_title() .'">';
            echo '<span><b>'. get_the_title() .'</b></span>';
            echo '</a>';
            echo '</h3>';
            echo '</div>';
            echo '</article>';

        endwhile;
endif;

// Reset postdata
wp_reset_postdata();

// Custom query loop pagination
wpbeginner_numeric_posts_nav();

// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>
</code>```

Here is code from function.php, but I think it isn't the problem.
http://virtual-wizard.eu/function.txt

答:
Try using this code instead. Make sure to read through as they are explaining how to implement this function into your WP website.

http://www.kriesi.at/archives/how-to-build-a-wordpress-post-pagination-without-plugin

Function is setup inside of a functions.php and on the specific page when you want to display pagination just call the function like pagination();

Before calling out pagination check also the CSS part and structure of the pagination to get the desired effect.

Srecno!

Body:
I use WP Beginner pagination (without plugin) on my website, but I can't access to second and other pages.

<?php

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

 $custom_query_args = array(
        'post_type' => array( 'tutorials','post' ),
        'posts_per_page' => 2,
        'cat' => $cat_id,
 );

// Get current page and append to custom query parameters array
$custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;

// Instantiate custom query
$custom_query = new WP_Query( $custom_query_args );

// Pagination fix
$temp_query = $wp_query;
$wp_query   = NULL;
$wp_query   = $custom_query;

// Output custom query loop
if ( $custom_query->have_posts() ) :
        while ( $custom_query->have_posts() ) :
                        $custom_query->the_post();

            echo '
';
            echo '
';
            echo '
';
            echo the_post_thumbnail('post-thumbnail', array( 'class' => 'post-image' ));
            echo '';
            echo ''. get_the_title() .'';
            echo '';
            echo '
';
            echo '
';
            echo '
';

        endwhile;
endif;

// Reset postdata
wp_reset_postdata();

// Custom query loop pagination
wpbeginner_numeric_posts_nav();

// Reset main query object
$wp_query = NULL;
$wp_query = $temp_query;
?>

Here is code from function.php, but I think it isn't the problem.
http://virtual-wizard.eu/function.txt


问:
jQuery Show-Hide DIV based on Checkbox Value
Using AJAX I populate a DIV with a bunch of checkboxes (each with it's own unique ID). The IDs are "projectID1", "projectID2", "projectID3" and so on... I have given all checkboxes a class of "pChk".

My end goal is to show the DIV containing the Submit Button if ANY of the checkboxes are checked. The only time the DIV containing the Submit Button show be hidden is if all checkboxes are unchecked.

However the code I have come up with below shows/hides the Submit Button DIV for each checkbox instance. In other words, if I have three checkboxes CHECKED and I UNCHECK one of them, the Submit Button DIV get hidden.

Your expert advice is more than welcome!

```<code>function checkUncheck() {
    $('.pChk').click(function() {
        if (this.checked) {
            $("#ProjectListButton").show();
        } else {
            $("#ProjectListButton").hide();
        }
    });
}
</code>```

答:
That is because you are only checking the current checkbox.

Change it to

```<code>function checkUncheck() {
    $('.pChk').click(function() {
        if ( $('.pChk:checked').length > 0) {
            $("#ProjectListButton").show();
        } else {
            $("#ProjectListButton").hide();
        }
    });
}
</code>```

to check if any of the checkboxes is checked (lots of checks in this line..).

reference: http://api.jquery.com/checked-selector/

ContentLicense: CC BY-SA 2.5

Body:
Using AJAX I populate a DIV with a bunch of checkboxes (each with it's own unique ID). The IDs are "projectID1", "projectID2", "projectID3" and so on... I have given all checkboxes a class of "pChk".

My end goal is to show the DIV containing the Submit Button if ANY of the checkboxes are checked. The only time the DIV containing the Submit Button show be hidden is if all checkboxes are unchecked.

However the code I have come up with below shows/hides the Submit Button DIV for each checkbox instance. In other words, if I have three checkboxes CHECKED and I UNCHECK one of them, the Submit Button DIV get hidden.

Your expert advice is more than welcome!

function checkUncheck() {
    $('.pChk').click(function() {
        if (this.checked) {
            $("#ProjectListButton").show();
        } else {
            $("#ProjectListButton").hide();
        }
    });
}

Body:
That is because you are only checking the current checkbox.

Change it to

function checkUncheck() {
    $('.pChk').click(function() {
        if ( $('.pChk:checked').length > 0) {
            $("#ProjectListButton").show();
        } else {
            $("#ProjectListButton").hide();
        }
    });
}

to check if any of the checkboxes is checked (lots of checks in this line..).

reference: http://api.jquery.com/checked-selector/


问:
Tcl -- Tcllib HTTP: geturl
I'm having trouble trying to implement tcllib's http package.

One issue that I am having is that after running the following code:

```<code>set fp [::http::geturl "https://google.com"]
</code>```

I get the following error:

```<code>error reading "sock23": software caused connection abort
    while executing
"::http::geturl "https://google.com""
    ("uplevel" body line 55)
    invoked from within
"uplevel {
    #package require yajltcl
package require sha256
package require base64
package require http 1.0
package require tls
package require pki
</code>```

Is there something wrong with my brain?

答:
Running the following command before performing ::http::register made my script work: </p>

```<code>tls::init -tls1 true -ssl2 false -ssl3 false
</code>```

Title: Tcl -- Tcllib HTTP: geturl

Body:
I'm having trouble trying to implement tcllib's http package.

One issue that I am having is that after running the following code:

set fp [::http::geturl "https://google.com"]

I get the following error:

error reading "sock23": software caused connection abort
    while executing
"::http::geturl "https://google.com""
    ("uplevel" body line 55)
    invoked from within
"uplevel {
    #package require yajltcl
package require sha256
package require base64
package require http 1.0
package require tls
package require pki

Is there something wrong with my brain?

Body:
Running the following command before performing ::http::register made my script work:

tls::init -tls1 true -ssl2 false -ssl3 false


问:
Why is my excel reader class reading every field correctly except for the date field?
I am reading in multiple fields from an excel sheet using Interop and it is working almost perfectly. Every field is read in except for the date field, which is populated by a weird number that has nothing to do with anything on the excel document. My code that is needed to run the program is below. In order to see the problem the test class must be run in order to see the results that are printed out on the console as well as the tests in the test class. The excel file must be on the desktop and titled TEST.xlsx. If you need to check my Excel sheet it is linked here on a google document. </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    /// <summary>
    /// This class reads data from an excel sheet and stores the data in Sales objects
    /// and then places each Sale into a List of Sales.
    /// </summary>
    public class Reader
    {
        public string path;
        public _Application excel;
        public _Workbook wb;
        public _Worksheet ws;
        public List<Sales> salesList { get; set; }

        /// <summary>
        /// This constructor opens the excel file, creates a list of sales, creates a modifier
        /// object.
        /// </summary>
        /// <param name="path"> Name of the excel file to be opened.  </param>
        /// <param name="sheet"> Sheet number within the excel file. </param>
        public Reader(string path, int sheet)
        {

            this.path = path;

            excel = new _Excel.Application();
            wb = excel.Workbooks.Open(path);
            ws = wb.Worksheets[sheet];

            salesList = new List<Sales>();
            createSales();

            // Console output test to ensure the excel file is being read correctly.
            for (int i = 0; i < salesList.Count; i++ )
            {
                Console.WriteLine("Row: " + (i + 1).ToString());
                Console.WriteLine(salesList[i].salesNum);
                Console.WriteLine(salesList[i].material);
                Console.WriteLine(salesList[i].description);
                Console.WriteLine(salesList[i].MSPS);
                Console.WriteLine(salesList[i].MRPC);
                Console.WriteLine(salesList[i].quantity);
                Console.WriteLine(salesList[i].date);
                Console.WriteLine("");
            }
        }

        public Reader()
        {
            new Reader("", 1);
        }

        /// <summary>
        /// This method creates a new Sale for every row in the excel file.
        /// </summary>
        /// <returns> Number of rows (sales) in the excel sheet. </returns>
        public int createSales()
        {
            int rows = 1; // Excel sheets start at 1 not 0.

            while (ws.Cells[rows, 1].Value2 != null)
            {
                Sales sale = new Sales();
                addFields(sale, rows);
                salesList.Add(sale);

                rows++;
            }

            return rows;
        }

        /// <summary>
        /// This helper method adds fields to all of the sales.
        /// </summary>
        /// <param name="sale"> Sale that is getting fields filled. </param>
        /// <param name="row"> Row to look for fields on </param>
        private void addFields(Sales sale, int row)
        {
            int i = 1;

            sale.salesNum = readCell(row, i);              // Sales Number field
            i++;

            sale.material = readCell(row, i);              // material field
            i++;

            sale.description = readCell(row, i);           // Description field
            i++;

            sale.MSPS = readCell(row, i);                  // MSPS field
            i++;

            sale.MRPC = readCell(row, i);                  // MRPC field
            i++;

            sale.quantity = readCell(row, i);              // Quantity field
            i++;

            sale.date = readCell(row, i);                  // Date field
        }

        /// <summary>
        /// This method reads a cell from the excel document.
        /// </summary>
        /// <param name="i"> The x-coordinate of the cell to read. </param>
        /// <param name="j"> The y-coordinate of the cell to read. </param>
        /// <returns> Data in the cell in a string. </returns>
        private string readCell(int i, int j)
        {
            if (ws.Cells[i, j].Value2 != null)
            {
                return ws.Cells[i, j].Value2.ToString();
            }
            else
            {
                return "";
            }
        }

    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using ConsoleApplication1;

namespace AutomationProgramTests
{
    [TestClass]
    public class ReaderTest
    {

        Reader reader;

        [TestMethod]
        public void testCreateSales()
        {
            reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);

            // Check if the list added every sale.
            Assert.AreEqual(90, reader.salesList.Count);

            // Check contents of sales[0].
            Assert.AreEqual("5/11/2017", reader.salesList[0].date);

            // Check contents of sales[1]
            Assert.AreEqual("5/11/2017", reader.salesList[1].date);

            // Check contents of sales[89]
            Assert.AreEqual("5/22/2017", reader.salesList[0].date);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    /// <summary>
    /// Created and tested by Alexander James Bochel.
    /// Last Updated: 6/7/2017
    /// </summary>
    class Program
    {

        /// <summary>
        /// This will call the rest of the classes in the program.
        /// </summary>
        /// <param name="args"> Command line arguments. </param>
        static void Main(string[] args)
        {
            openAndExecute();
        }

        public static void openAndExecute()
        {
            Reader reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// This class contains information about each individual row on the excel sheet.
    /// </summary>
    public class Sales
    {
        // Each variable is a cell in the row for each sales order in excel.
        public String salesNum { get; set; }
        public String material { get; set; }
        public String description { get; set; }
        public String MSPS { get; set; }
        public String MRPC { get; set; }
        public String quantity { get; set; }
        public String date { get; set; }

        /// <summary>
        /// Basic Constructor.
        /// </summary>
        public Sales()
        {
            // TODO finish basic constructor.
        }

        /// <summary>
        /// This constructor sets up all of the variables within each sale.
        /// </summary>
        /// <param name="salesN"> Sales number </param>
        /// <param name="mat"> Type of material </param>
        /// <param name="desc"> Description </param>
        /// <param name="MS"> IDK </param>
        /// <param name="MR"> IDK </param>
        /// <param name="quant"> How many </param>
        /// <param name="dat"> IDK </param>
        public Sales(String salesN, String mat, String desc, String MS, String MR, String quant,
                     String dat)
        {
            // Can these be deleted.
            salesNum = salesN;
            material = mat;
            description = desc;
            MSPS = MS;
            MRPC = MR;
            quantity = quant;
            date = dat;
        }
    }
}
</code>```

答: That weird number is actually just a representation of the date in a different format. You can try using the CDate() function on that number and that should give you the date you are looking for. Another option would be to set it to a variable that is explicitly defined as a date type.

Body:
I am reading in multiple fields from an excel sheet using Interop and it is working almost perfectly. Every field is read in except for the date field, which is populated by a weird number that has nothing to do with anything on the excel document. My code that is needed to run the program is below. In order to see the problem the test class must be run in order to see the results that are printed out on the console as well as the tests in the test class. The excel file must be on the desktop and titled TEST.xlsx. If you need to check my Excel sheet it is linked here on a google document.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    ///
    /// This class reads data from an excel sheet and stores the data in Sales objects
    /// and then places each Sale into a List of Sales.
    ///
    public class Reader
    {
        public string path;
        public _Application excel;
        public _Workbook wb;
        public _Worksheet ws;
        public List<Sales> salesList { get; set; }

        ///
        /// This constructor opens the excel file, creates a list of sales, creates a modifier
        /// object.
        ///
        /// <param name="path"> Name of the excel file to be opened.  </param>
        /// <param name="sheet"> Sheet number within the excel file. </param>
        public Reader(string path, int sheet)
        {

            this.path = path;

            excel = new _Excel.Application();
            wb = excel.Workbooks.Open(path);
            ws = wb.Worksheets[sheet];

            salesList = new List<Sales>();
            createSales();

            // Console output test to ensure the excel file is being read correctly.
            for (int i = 0; i < salesList.Count; i++ )
            {
                Console.WriteLine("Row: " + (i + 1).ToString());
                Console.WriteLine(salesList[i].salesNum);
                Console.WriteLine(salesList[i].material);
                Console.WriteLine(salesList[i].description);
                Console.WriteLine(salesList[i].MSPS);
                Console.WriteLine(salesList[i].MRPC);
                Console.WriteLine(salesList[i].quantity);
                Console.WriteLine(salesList[i].date);
                Console.WriteLine("");
            }
        }

        public Reader()
        {
            new Reader("", 1);
        }

        ///
        /// This method creates a new Sale for every row in the excel file.
        ///
        /// <returns> Number of rows (sales) in the excel sheet. </returns>
        public int createSales()
        {
            int rows = 1; // Excel sheets start at 1 not 0.

            while (ws.Cells[rows, 1].Value2 != null)
            {
                Sales sale = new Sales();
                addFields(sale, rows);
                salesList.Add(sale);

                rows++;
            }

            return rows;
        }

        ///
        /// This helper method adds fields to all of the sales.
        ///
        /// <param name="sale"> Sale that is getting fields filled. </param>
        /// <param name="row"> Row to look for fields on </param>
        private void addFields(Sales sale, int row)
        {
            int i = 1;

            sale.salesNum = readCell(row, i);              // Sales Number field
            i++;

            sale.material = readCell(row, i);              // material field
            i++;

            sale.description = readCell(row, i);           // Description field
            i++;

            sale.MSPS = readCell(row, i);                  // MSPS field
            i++;

            sale.MRPC = readCell(row, i);                  // MRPC field
            i++;

            sale.quantity = readCell(row, i);              // Quantity field
            i++;

            sale.date = readCell(row, i);                  // Date field
        }

        ///
        /// This method reads a cell from the excel document.
        ///
        /// <param name="i"> The x-coordinate of the cell to read. </param>
        /// <param name="j"> The y-coordinate of the cell to read. </param>
        /// <returns> Data in the cell in a string. </returns>
        private string readCell(int i, int j)
        {
            if (ws.Cells[i, j].Value2 != null)
            {
                return ws.Cells[i, j].Value2.ToString();
            }
            else
            {
                return "";
            }
        }

    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using ConsoleApplication1;

namespace AutomationProgramTests
{
    [TestClass]
    public class ReaderTest
    {

        Reader reader;

        [TestMethod]
        public void testCreateSales()
        {
            reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);

            // Check if the list added every sale.
            Assert.AreEqual(90, reader.salesList.Count);

            // Check contents of sales[0].
            Assert.AreEqual("5/11/2017", reader.salesList[0].date);

            // Check contents of sales[1]
            Assert.AreEqual("5/11/2017", reader.salesList[1].date);

            // Check contents of sales[89]
            Assert.AreEqual("5/22/2017", reader.salesList[0].date);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    ///
    /// Created and tested by Alexander James Bochel.
    /// Last Updated: 6/7/2017
    ///
    class Program
    {

        ///
        /// This will call the rest of the classes in the program.
        ///
        /// <param name="args"> Command line arguments. </param>
        static void Main(string[] args)
        {
            openAndExecute();
        }

        public static void openAndExecute()
        {
            Reader reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    ///
    /// This class contains information about each individual row on the excel sheet.
    ///
    public class Sales
    {
        // Each variable is a cell in the row for each sales order in excel.
        public String salesNum { get; set; }
        public String material { get; set; }
        public String description { get; set; }
        public String MSPS { get; set; }
        public String MRPC { get; set; }
        public String quantity { get; set; }
        public String date { get; set; }

        ///
        /// Basic Constructor.
        ///
        public Sales()
        {
            // TODO finish basic constructor.
        }

        ///
        /// This constructor sets up all of the variables within each sale.
        ///
        /// <param name="salesN"> Sales number </param>
        /// <param name="mat"> Type of material </param>
        /// <param name="desc"> Description </param>
        /// <param name="MS"> IDK </param>
        /// <param name="MR"> IDK </param>
        /// <param name="quant"> How many </param>
        /// <param name="dat"> IDK </param>
        public Sales(String salesN, String mat, String desc, String MS, String MR, String quant,
                     String dat)
        {
            // Can these be deleted.
            salesNum = salesN;
            material = mat;
            description = desc;
            MSPS = MS;
            MRPC = MR;
            quantity = quant;
            date = dat;
        }
    }
}


问:
Change css through jquery after a click on a div
The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

```<code><div class="first">some text</div>
<div class ="second">bunch of text</div>
</code>```

Css

```<code>.second{display=none;}
</code>```

Jquery

```<code> $('.first').click(function() {
  $('.second').css('display', 'block');
});
</code>```

Thanks in advance

答:
It's best to use classes to hide and show Elements

HTML

```<code><div class="first">some text</div>
<div class ="second div-hide">bunch of text</div>
</code>```

CSS

```<code>.div-hide{display:none}
</code>```

JQUERY

```<code>$('.first').click(function() {
   if ($('.second').hasClass('div-hide'))
   {
        $('.second').removeClass('div-hide');
   }
   else
   {
       $('.second').addClass('div-hide');
   }
});
</code>```

Body:
The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

some text

bunch of text

Css

.second{display=none;}

Jquery

 $('.first').click(function() {
  $('.second').css('display', 'block');
});

Thanks in advance

Body:
It's best to use classes to hide and show Elements

HTML

<div class="first">some text</div>
<div class ="second div-hide">bunch of text</div>

CSS

.div-hide{display:none}

JQUERY

$('.first').click(function() {
   if ($('.second').hasClass('div-hide'))
   {
        $('.second').removeClass('div-hide');
   }
   else
   {
       $('.second').addClass('div-hide');
   }
});


问:
Keras neural network model accuracy is always zero
My name is Sabber. My research interests are in computational geophysics. Recently I have started working on a deep-learning application to geophysics. Part of this work I have played with some toy examples (spiral data) using both "Tensorflow" and "Keras." With some trial and error, I was able to get 97% accuracy. BTW, All the problems are the regression.

In this work, I want to predict any of the stress component based on some physical parameters (temperature, density, p-wave, s-wave velocity, thermal energy, and depth).

However, when I use the actual geophysical data, I got zero accuracies from the first epoch. I do not have any clue right now what made the accuracy zero. I have spent many hours to learn if I had made any mistake. I am a little bit frustrated since I could not figure out the problem. There might have a couple of options to dig:

Either my data has nothing to learn or

Data pre-processing is wrong.

At this stage, I feel I desperately need some help. For your convenience, I have Included:

Code ("Tensorflow" and "Keras" ):
https://github.com/msahamed/deep_learning_stress_model

This repository has three files. Out of these three "ipynb" you can look at either "predict_stress_keras.ipynb" or "predict_stress_tensorflow.ipynb". The code is very straightforward. I have written all the necessary comments.

Data: https://drive.google.com/open?id=0BwexgJqQoeJUVlVPUkhtT210MlE

The data file has no any header and has 11 columns. The X can be first seven columns. We do not need x coordinate (8 column). This column can be ignored. Based on X we want to predict any of the stress components (xx/xz/zz).

Update:
Even if ignore the accuracy for this regression problem, all the predicted results are same(see Figure)

Please give me some feedback. I appreciate your help.

答:
Matias Valdenegro is right - accuracy is not meaningful in this context and a value of zero is to be expected. See this thread: https://github.com/fchollet/keras/issues/108

Some quick recommendations regarding your code:

10 layers is way too much. Start with 2 or 3 layer max.
Start with the Keras defaults and only change where necessary.

Try sth like this and improve from there:

```<code>model = Sequential()
model.add(Dense(units = 64, activation = 'tanh', input_dim = 7))
model.add(Dense(units = 32, activation = 'tanh'))
model.add(Dense(units = 16, activation = 'tanh'))
model.add(Dense(units = 1, activation="linear"))
model.compile(optimizer = 'rmsprop', loss = 'mean_absolute_error')

history = model.fit(X_train, Y_train, batch_size = 2048, epochs = 20,
           validation_split= 0.2, verbose=0)

score = model.evaluate(X_test, Y_test, batch_size=2048)
print(score)
</code>```

Body:
Matias Valdenegro is right - accuracy is not meaningful in this context and a value of zero is to be expected. See this thread: https://github.com/fchollet/keras/issues/108

Some quick recommendations regarding your code:

10 layers is way too much. Start with 2 or 3 layer max.
Start with the Keras defaults and only change where necessary.

Try sth like this and improve from there:

model = Sequential()
model.add(Dense(units = 64, activation = 'tanh', input_dim = 7))
model.add(Dense(units = 32, activation = 'tanh'))
model.add(Dense(units = 16, activation = 'tanh'))
model.add(Dense(units = 1, activation="linear"))
model.compile(optimizer = 'rmsprop', loss = 'mean_absolute_error')

history = model.fit(X_train, Y_train, batch_size = 2048, epochs = 20,
           validation_split= 0.2, verbose=0)

score = model.evaluate(X_test, Y_test, batch_size=2048)
print(score)


问:
'NT AUTHORITY\NETWORK SERVICE' not inheritting local group permissions?
We are deleting images that have been uploaded to our server using an ASP.NET web page. The site is running under 'NT AUTHORITY\NETWORK SERVICE' in IIS.

On the IIS server we have created a local group 'Full_Access' that we have added the 'NT AUTHORITY\NETWORK SERVICE' to. This group has NTFS Modify permission enabled on the file.

When we delete the file from out app. The file does not get deleted.

If we add 'NT AUTHORITY\NETWORK SERVICE' file instead explicitly to the file and give modify permission instead of relying on it to inherit the permission from the local group it is in then it works just fine.

We have used the effective permissions check on the security tab and either way it supposedly has permission? But in actuality it only works if we directly give the service account permission?

Is there some reason 'NT AUTHORITY\NETWORK SERVICE' does not inherit the permissions of the local group it is in?

答:
Add the group IIS_WPG to your 'Full_Access' group instead of NETWORK SERVICE.

From http://msdn.microsoft.com/en-us/library/ms998320.aspx :

Note   If you need to allow the same level of access to a file resource for all accounts that run ASP.NET applications (Network Service or a custom service account), you can grant access to the IIS_WPG group instead of specifically to the Network Service account. Any account used to run ASP.NET is required to be a member of the IIS_WPG group.

OwnerDisplayName: ctrlShiftBryan

LastEditorDisplayName: Kev

OwnerDisplayName: FreddyB


问:
PHP - highlight text from a string containing HTML
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

```<code><p>bla bla foo bar bla</p>
</code>```

so it should be something like:

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

答:
I think this is more complicated than it looks. If we are searching for foo bar then

```<code><p>bla bla foo bar bla</p>
</code>```

will be converted into

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

but what about some special cases? It could be that foo bar is matched inside an HTML tag:

```<code><p>bla bla <span class="foo bar">foo bar</span> bla</p>
</code>```

which will be replaced as

```<code><p>bla <span class="<span class="highlight">foo bar</span>">foo bar</span> bla bla</p>
</code>```

Am I right with this? I haven't been into this issue, but I'd recommend you checking on CakePHP's docs (yeah, I know you are not using the framework--) in the Text helper, the highlight() method which handles HTML tags correctly. Take a look at the source, give it a shot and if it works for you, go ahead and copy it.

Body:
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

bla bla foo bar bla

so it should be something like:

bla foo bar bla bla

Body:
I think this is more complicated than it looks. If we are searching for foo bar then

<p>bla bla foo bar bla</p>

will be converted into

<p>bla <span class="highlight">foo bar</span> bla bla</p>

but what about some special cases? It could be that foo bar is matched inside an HTML tag:

<p>bla bla <span class="foo bar">foo bar</span> bla</p>

which will be replaced as

<p>bla <span class="<span class="highlight">foo bar</span>">foo bar</span> bla bla</p>

Am I right with this? I haven't been into this issue, but I'd recommend you checking on CakePHP's docs (yeah, I know you are not using the framework--) in the Text helper, the highlight() method which handles HTML tags correctly. Take a look at the source, give it a shot and if it works for you, go ahead and copy it.


问:
Search for exact phrase with Elasticsearch
I am currently starting out with Elasticsearch. I've indexed a few EDIFACT messages (a pre-historic data format;-)
The content looks something like this:

```<code>UNB+UNOA:2+SENDER+RECEIVER+170509:0050+152538'
UNH+66304+CODECO:D:95B:UN:ITG12'
BGM+34+INGATE OF UCN ABCD+9'
</code>```

When I do a search for the phrase UNH+66304+CODECO:D:95B it should only return one hit but it seems it is returning all files that contain any of these words (and UNH is in every single one of the documents).
My Query is this:

```<code>curl -XGET --netrc-file ~/curl_user  'localhost:9200/edi/message/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query":{
        "match":{"MESSAGE":"UNH+66304+CODECO:D:95B"}
    }
}'
</code>```

I've tried to add the "and" operator like this:

```<code>"match":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO",
                "operator": "and"

              }
            }
</code>```

But then no results are returned.
I've read the suggestion here: Searching for exact phrase
that I need to use double quotes. I've tried both "query":"'UNH+66304+CODECO'" and "query":"\"UNH+66304+CODECO\"" but it doesn't make a difference.

I have also tried match_phrase

```<code>"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO"

              }
            }
</code>```

does not return a result while

```<code>"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304"

              }
            }
</code>```

does.
With normal text it seems to work but somehow Elasticsearch doesn't like it with the +: etc in the search string (that is unfortunately part of EDIFACT).

How to make query_string search exact phrase in ElasticSearch talks about using a different analyser if you want exact matches?

Update: abhishek mishra confirmed that the Analyser is probably the way to go. I am using Elasticsearch 5.4 and there are a lot of Analysers to chose from: https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html

The Keyword Analyser would probably map to what abhishek suggested as the 'not analysed' as it is a noop Analyser. However I am a bit worried about using this as the messages can be quite long. What are the performance impacts for the search? If I use the Keyword Analyser will I still be able to search for parts of the whole message?

I am wondering whether the Pattern Analyser would be a good fit?
EDIFACT messages consist of segments starting with 3 Upper Case Characters and are terminated by ' (but you can escape ' by prefixing it with ?)

```<code>FTX+AAA++It?'s a strange data format'
FTX+AAA++Yes it is'
</code>```

So the example above would be two segments. If I would use a pattern that separates splits these segments, would that be a good match?

Only problem is that currently the MESSAGE field can contain EDIFACT messages and XML messages. Using the same Pattern Analyser would not work I guess so I would have to create two different types depending on the content of the MESSAGE field (all the rest is the same).

2nd Update:
I have followed the advice to look into analysers. I thought the keyword analyser is probably not a good idea as the text can be quite long. I've found that the pattern analyser (without any custom pattern) works quite nicely. It splits up everything on : and +. Searches like

```<code>{
    "query":{
        "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
    }
}
</code>```

or

```<code>{
        "query":{
            "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
        }
    }
</code>```

work now. The problem before was that e.g. was split up into [rff,abt:atb150538080520172452].

答:
I think you have "query" and "match_phrase" inverted:

Can you try it like this:

```<code>{
    "query": {
        "match_phrase": {
            "MESSAGE": "UNH+66304"
        }
    }
}
</code>```

Body:
I am currently starting out with Elasticsearch. I've indexed a few EDIFACT messages (a pre-historic data format;-)
The content looks something like this:

UNB+UNOA:2+SENDER+RECEIVER+170509:0050+152538'
UNH+66304+CODECO:D:95B:UN:ITG12'
BGM+34+INGATE OF UCN ABCD+9'

When I do a search for the phrase UNH+66304+CODECO:D:95B it should only return one hit but it seems it is returning all files that contain any of these words (and UNH is in every single one of the documents).
My Query is this:

curl -XGET --netrc-file ~/curl_user  'localhost:9200/edi/message/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query":{
        "match":{"MESSAGE":"UNH+66304+CODECO:D:95B"}
    }
}'

I've tried to add the "and" operator like this:

"match":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO",
                "operator": "and"

              }
            }

But then no results are returned.
I've read the suggestion here: Searching for exact phrase
that I need to use double quotes. I've tried both "query":"'UNH+66304+CODECO'" and "query":"\"UNH+66304+CODECO\"" but it doesn't make a difference.

I have also tried match_phrase

"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304+CODECO"

              }
            }

does not return a result while

"match_phrase":{
              "MESSAGE":{
                "query":"UNH+66304"

              }
            }

does.
With normal text it seems to work but somehow Elasticsearch doesn't like it with the +: etc in the search string (that is unfortunately part of EDIFACT).

How to make query_string search exact phrase in ElasticSearch talks about using a different analyser if you want exact matches?

Update: abhishek mishra confirmed that the Analyser is probably the way to go. I am using Elasticsearch 5.4 and there are a lot of Analysers to chose from: https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html

The Keyword Analyser would probably map to what abhishek suggested as the 'not analysed' as it is a noop Analyser. However I am a bit worried about using this as the messages can be quite long. What are the performance impacts for the search? If I use the Keyword Analyser will I still be able to search for parts of the whole message?

I am wondering whether the Pattern Analyser would be a good fit?
EDIFACT messages consist of segments starting with 3 Upper Case Characters and are terminated by ' (but you can escape ' by prefixing it with ?)

FTX+AAA++It?'s a strange data format'
FTX+AAA++Yes it is'

So the example above would be two segments. If I would use a pattern that separates splits these segments, would that be a good match?

Only problem is that currently the MESSAGE field can contain EDIFACT messages and XML messages. Using the same Pattern Analyser would not work I guess so I would have to create two different types depending on the content of the MESSAGE field (all the rest is the same).

2nd Update:
I have followed the advice to look into analysers. I thought the keyword analyser is probably not a good idea as the text can be quite long. I've found that the pattern analyser (without any custom pattern) works quite nicely. It splits up everything on : and +. Searches like

{
    "query":{
        "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
    }
}

or

{
        "query":{
            "match_phrase":{"MESSAGE":"RFF+ABT:ATB150538080520172452"}
        }
    }

work now. The problem before was that e.g. was split up into [rff,abt:atb150538080520172452].

Body:
I think you have "query" and "match_phrase" inverted:

Can you try it like this:

{
    "query": {
        "match_phrase": {
            "MESSAGE": "UNH+66304"
        }
    }
}


问:
react-redux upload file errors
I try to implement file uploading on react-redux using redux-form, but there are a warning and an exception in the console:

Warning: ConnectedField is changing an uncontrolled input of type file to be
 controlled. Input elements should not switch from uncontrolled to controlled
 (or vice versa). Decide between using a controlled or uncontrolled input
 element for the lifetime of the component.

```<code>bundle.js:37467 Uncaught DOMException: Failed to set the 'value' property on
'HTMLInputElement': This input element accepts a filename, which may only be
programmatically set to the empty string.
        at Object.updateWrapper (http://localhost:8080/dist/bundle.js:37467:20)
        at ReactDOMComponent.updateComponent (http://localhost:8080/dist/bundle.js:36891:23)
        at ReactDOMComponent.receiveComponent (http://localhost:8080/dist/bundle.js:36846:10)
        at Object.receiveComponent (http://localhost:8080/dist/bundle.js:6247:22)
        at ReactCompositeComponentWrapper._updateRenderedComponent (http://localhost:8080/dist/bundle.js:35859:23)
        at ReactCompositeComponentWrapper._performComponentUpdate (http://localhost:8080/dist/bundle.js:35829:10)
        at ReactCompositeComponentWrapper.updateComponent (http://localhost:8080/dist/bundle.js:35750:12)
        at ReactCompositeComponentWrapper.receiveComponent (http://localhost:8080/dist/bundle.js:35652:10)
        at Object.receiveComponent (http://localhost:8080/dist/bundle.js:6247:22)
        at ReactCompositeComponentWrapper._updateRenderedComponent (http://localhost:8080/dist/bundle.js:35859:23)
</code>```

Here is a code of my component:

```<code>import React,{Component} from 'react';
import {Field, reduxForm} from 'redux-form';

class UploadFileForm extends Component {

  onFormSubmit(data) {
    console.log(data);
  };

  render() {
    return (
      <form role="form" onSubmit={this.props.handleSubmit(this.onFormSubmit)}>
        <div className="form-group">
          {/*<input name="file" type="file" className="file file-loading" data-allowed-file-extensions='[".owl"]'/>*/}
          <Field name="owl-file" component="input" type="file" ref="owl-file-ref"/>
          <label className="choose-file-info"></label>
        </div>
        <button type="submit" className="btn btn-primary">Upload</button>
      </form>
    );
  }
}

export default reduxForm({
  form: 'upload'
})(UploadFileForm);
</code>```

答:
The following worked for me;

```<code>const UploadFile = ({ input: {value: omitValue, ...inputProps }, meta: omitMeta, ...props }) => (
  <input type='file' {...inputProps} {...props} />
);
</code>```

Then I use it like so;

```<code><Field component={UploadFile} name='file' accept='.jpg' />
</code>```

The solution was found in:
https://github.com/erikras/redux-form/issues/1989

Title: react-redux upload file errors

Body:
I try to implement file uploading on react-redux using redux-form, but there are a warning and an exception in the console:

Warning: ConnectedField is changing an uncontrolled input of type file to be
 controlled. Input elements should not switch from uncontrolled to controlled
 (or vice versa). Decide between using a controlled or uncontrolled input
 element for the lifetime of the component.

bundle.js:37467 Uncaught DOMException: Failed to set the 'value' property on
'HTMLInputElement': This input element accepts a filename, which may only be
programmatically set to the empty string.
        at Object.updateWrapper (http://localhost:8080/dist/bundle.js:37467:20)
        at ReactDOMComponent.updateComponent (http://localhost:8080/dist/bundle.js:36891:23)
        at ReactDOMComponent.receiveComponent (http://localhost:8080/dist/bundle.js:36846:10)
        at Object.receiveComponent (http://localhost:8080/dist/bundle.js:6247:22)
        at ReactCompositeComponentWrapper._updateRenderedComponent (http://localhost:8080/dist/bundle.js:35859:23)
        at ReactCompositeComponentWrapper._performComponentUpdate (http://localhost:8080/dist/bundle.js:35829:10)
        at ReactCompositeComponentWrapper.updateComponent (http://localhost:8080/dist/bundle.js:35750:12)
        at ReactCompositeComponentWrapper.receiveComponent (http://localhost:8080/dist/bundle.js:35652:10)
        at Object.receiveComponent (http://localhost:8080/dist/bundle.js:6247:22)
        at ReactCompositeComponentWrapper._updateRenderedComponent (http://localhost:8080/dist/bundle.js:35859:23)

Here is a code of my component:

import React,{Component} from 'react';
import {Field, reduxForm} from 'redux-form';

class UploadFileForm extends Component {

  onFormSubmit(data) {
    console.log(data);
  };

  render() {
    return (
      <form role="form" onSubmit={this.props.handleSubmit(this.onFormSubmit)}>

          {/*<input name="file" type="file" className="file file-loading" data-allowed-file-extensions='[".owl"]'/>*/}
          <Field name="owl-file" component="input" type="file" ref="owl-file-ref"/>

        <button type="submit" className="btn btn-primary">Upload</button>
      </form>
    );
  }
}

export default reduxForm({
  form: 'upload'
})(UploadFileForm);

Body:
The following worked for me;

const UploadFile = ({ input: {value: omitValue, ...inputProps }, meta: omitMeta, ...props }) => (
  <input type='file' {...inputProps} {...props} />
);

Then I use it like so;

<Field component={UploadFile} name='file' accept='.jpg' />

The solution was found in:
https://github.com/erikras/redux-form/issues/1989


问:
How can I make a scroll content for my comment?
I want to make it "scrollable" when the user add a comment.

this is the css code:

```<code>.contenu_post{

    width:700px;
    height:500px;
    background-color:white;
    float:right;
    margin-right:80px;
    margin-top:20px;
    text-align:center;

    box-shadow: 0px 4px 6px #333;
   -moz-box-shadow: 0px 4px 6px #333;
   -webkit-box-shadow: 0px 4px 6px #333;
}
</code>```

And my html code:html code source

its the the class "post_user" in the html code I want to be "scrollable"

Thanks you for both of you! :)

答:
Like Michael Coker said, use overflow-y: scroll; on the content you want scrollable. And as Fred said, it's pretty hard to know exactly where that should go without more information about your markup structure.

edited

Body:
I want to make it "scrollable" when the user add a comment.

this is the css code:

.contenu_post{

    width:700px;
    height:500px;
    background-color:white;
    float:right;
    margin-right:80px;
    margin-top:20px;
    text-align:center;

    box-shadow: 0px 4px 6px #333;
   -moz-box-shadow: 0px 4px 6px #333;
   -webkit-box-shadow: 0px 4px 6px #333;
}

And my html code:html code source

its the the class "post_user" in the html code I want to be "scrollable"

Thanks you for both of you! :)


问:
jQuery only toggle this element
I have this code:

```<code>$("#communities .inventory-search button.dropdown-toggle").on("click", function () {
    $(".inventory-search .dropdown-toggle img").toggle();
});
</code>```

This works, but it keeps toggling all the .dropdown-toggle img items, how do I just target the one that was clicked?

答:
You should be able to do something like:</p>

```<code>$("#communities .inventory-search button.dropdown-toggle").on("click", function () {
   $(this).find("img").toggle();
});
</code>```

Title: jQuery only toggle this element

Body:
I have this code:

$("#communities .inventory-search button.dropdown-toggle").on("click", function () {
    $(".inventory-search .dropdown-toggle img").toggle();
});

This works, but it keeps toggling all the .dropdown-toggle img items, how do I just target the one that was clicked?

Body:
You should be able to do something like:

$("#communities .inventory-search button.dropdown-toggle").on("click", function () {
   $(this).find("img").toggle();
});


答:
First you need to make a vector of means:

```<code>> means=apply(d2, 2, function(x) mean(na.omit(x))) #don't forget na.omit
> means
  WT.hypo  WT.hyper   KO.hypo  KO.hyper
12.426192  4.656158  7.751991  5.061578
</code>```

Then you can add the lines:

```<code>> segments(0.9, means[[1]], 1.1, means[[1]], lwd=2, lty=3, col="black")
> segments(1.9, means[[2]], 2.1, means[[2]], lwd=2, lty=3, col="black")
> segments(2.9, means[[3]], 3.1, means[[3]], lwd=2, lty=3, col="black")
> segments(3.9, means[[4]], 4.1, means[[4]], lwd=2, lty=3, col="black")
</code>```

I'd advise you to think about using the built-in bxplot() function that comes in beeswarm though; it's much easier.

Title: how to add mean to a beeswarm plot

Body:
Here is the data set (d2):

    WT.hypo  WT.hyper   KO.hypo KO.hyper
1 11.996507  2.406066 10.903488 7.595285
2 10.992267  2.192558  9.399490 7.184496
3 16.797177 11.088748  6.221103 4.293984
4  9.918818  2.937259  6.317434 3.319860
5        NA        NA  5.918438 2.914264

Here is the script:

#beeswarm
beeswarm(d2, method="swarm", col = c("black"), pch = 16, cex.axis = 1, cex = 1 )

#add mean
m <- mean(d2, na.rm=T)
segments(0.9,m[[1]],1.1,m[[1]], lwd = 2, lty = 3, col = "black")

Seems like some arguments are missing in "m<- mean(d2, na.rm=T)"

Dataset:

d2=structure(list(WT.hypo = c(11.996507, 10.992267, 16.797177, 9.918818,
NA), WT.hyper = c(2.406066, 2.192558, 11.088748, 2.937259, NA
), KO.hypo = c(10.903488, 9.39949, 6.221103, 6.317434, 5.918438
), KO.hyper = c(7.595285, 7.184496, 4.293984, 3.31986, 2.914264
)), .Names = c("WT.hypo", "WT.hyper", "KO.hypo", "KO.hyper"), class = "data.frame", row.names = c(NA,
-5L))

Body:
First you need to make a vector of means:

> means=apply(d2, 2, function(x) mean(na.omit(x))) #don't forget na.omit
> means
  WT.hypo  WT.hyper   KO.hypo  KO.hyper
12.426192  4.656158  7.751991  5.061578

Then you can add the lines:

> segments(0.9, means[[1]], 1.1, means[[1]], lwd=2, lty=3, col="black")
> segments(1.9, means[[2]], 2.1, means[[2]], lwd=2, lty=3, col="black")
> segments(2.9, means[[3]], 3.1, means[[3]], lwd=2, lty=3, col="black")
> segments(3.9, means[[4]], 4.1, means[[4]], lwd=2, lty=3, col="black")

I'd advise you to think about using the built-in bxplot() function that comes in beeswarm though; it's much easier.