问:
howto receive media volume change notifications?
Is it possible to register a BroadcastReceiver or something to get notifications of media player volume changes?

Thanks

答:
Immediate value you can get if you use AudioManager

```<code>AudioManager mAudioManager = Context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.getStreamVolume(STREAM_MUSIC);
</code>```

The only function that gives you opportunity to register broadcast receiver is

```<code>mAudioManager.registerMediaButtonEventReceiver(audioBroadcastReceiver);
</code>```

where audioBroadcastReceiver extends BroadcastReceiver and must be declared in the application manifest.

Not sure if this is exactly what you were looking for.

Body:
Immediate value you can get if you use AudioManager

AudioManager mAudioManager = Context.getSystemService(Context.AUDIO_SERVICE);
mAudioManager.getStreamVolume(STREAM_MUSIC);

The only function that gives you opportunity to register broadcast receiver is

mAudioManager.registerMediaButtonEventReceiver(audioBroadcastReceiver);

where audioBroadcastReceiver extends BroadcastReceiver and must be declared in the application manifest.

Not sure if this is exactly what you were looking for.


来源: stackexchange

问:
JTextField and JButton login page
```<code>ublic class TheMedicalResourceManagementSystem
{
    JFrame jf;
    JPanel jp;
    JButton b;
    JTextField t;
    JTextField t2;

    public static void main(String[] args)
    {
        TheMedicalResourceManagementSystem cc = new TheMedicalResourceManagementSystem();

       // SwingUtilities.invokeLater(() -> new GUI("The Medical Resource Management System").setVisible(true));
    }

    public TheMedicalResourceManagementSystem()
    {

        jf = new JFrame("Frame");
        jp = new JPanel();
        jp.setLayout(new FlowLayout());
        jf.add(jp);
        t = new JTextField(15);
        jp.add(t);
           t2 = new JTextField(15);
        jp.add(t);
        jp.add(t2);

b= new JButton("Login");
jp.add(b);

        jf.setSize(200,200);
        jf.setVisible(true);

        String username = t.getText();
        String password = t2.getText();

         b.addActionListener((ActionEvent e) -> {
             if(username.equals("admin") && password.equals("password"))
             {
                 SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
             }

             else
             {
                 JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
             }});

}

}
</code>```

<p>within my program i am looking to enter a username and password and when it is entered and correct it should run everything. I cant get it to run as when i enter admin and password it keeps telling me the user or password is wrong even though it is not? </p>

答:
Like most GUI frameworks, Swing is event driven.  This means that information is relative to the time it is collected.

In your example above, you are getting the username and password even before the UI is fully realised (presented to the user), so it will only return the initial values of the text fields (which are probably blank)

Instead, you need to get the username and password at the time of the ActionEvent, as that's when it's most relevant to the code, for example...

```<code>b.addActionListener((ActionEvent e) -> {
    String username = t.getText();
    String password = t2.getText();
    if(username.equals("admin") && password.equals("password")) {
        SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
    } else {
        JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: JTextField and JButton login page

Body:
ublic class TheMedicalResourceManagementSystem
{
    JFrame jf;
    JPanel jp;
    JButton b;
    JTextField t;
    JTextField t2;

    public static void main(String[] args)
    {
        TheMedicalResourceManagementSystem cc = new TheMedicalResourceManagementSystem();

       // SwingUtilities.invokeLater(() -> new GUI("The Medical Resource Management System").setVisible(true));
    }

    public TheMedicalResourceManagementSystem()
    {

        jf = new JFrame("Frame");
        jp = new JPanel();
        jp.setLayout(new FlowLayout());
        jf.add(jp);
        t = new JTextField(15);
        jp.add(t);
           t2 = new JTextField(15);
        jp.add(t);
        jp.add(t2);

b= new JButton("Login");
jp.add(b);

        jf.setSize(200,200);
        jf.setVisible(true);

        String username = t.getText();
        String password = t2.getText();

         b.addActionListener((ActionEvent e) -> {
             if(username.equals("admin") && password.equals("password"))
             {
                 SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
             }

             else
             {
                 JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
             }});

}

}

within my program i am looking to enter a username and password and when it is entered and correct it should run everything. I cant get it to run as when i enter admin and password it keeps telling me the user or password is wrong even though it is not?

Body:
Like most GUI frameworks, Swing is event driven.  This means that information is relative to the time it is collected.

In your example above, you are getting the username and password even before the UI is fully realised (presented to the user), so it will only return the initial values of the text fields (which are probably blank)

Instead, you need to get the username and password at the time of the ActionEvent, as that's when it's most relevant to the code, for example...

b.addActionListener((ActionEvent e) -> {
    String username = t.getText();
    String password = t2.getText();
    if(username.equals("admin") && password.equals("password")) {
        SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
    } else {
        JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
    }
});


问:
How to get keyboard to move to next textfield
I have several UITextFields that are in a group... I need to be able to move from the first to the last, and on the last make it FirstResponder.

I thought the Next key would move the focus, and Done would cause it to become FirstResponder, but apparently not.

Ideas?

答: You have to implement the UITextFieldDelegate's ShouldReturn method and in there make the next text field BecomeFirstResponder(). Then return/next will take you to the next field. If return is hit on the last textfield you will call ResignFirstResponder() on that field. </p>

ContentLicense: CC BY-SA 2.5


问:
Arrange 3 images in a row in React Native
I have just started working on a React Native project and I got stuck. I need to display a listof images from an API. The API only gives image urls that I can use like this:

```<code><Image
      style={{width: 50, height: 50}}
      source={{uri: 'https://avatars0.githubusercontent.com/u/13102253?s=460&v=4'}}
/>
</code>```

The image count is dynamic but I want to display only 3 images per row. How can I achieve this?

答:
The React-Native FlatList is exactly what you need. It accepts a numColumns prop which in your case should be 3.

```<code><FlatList
  numColumns={3}
  data={yourImagesArray}
  renderItem={<YourImageComponent >}
/>
</code>```

Each iteration of the data array (which I called here yourImagesArray) is passed to the renderItem (which I called here YourImageComponent) as a data prop. So the render function of YourImageComponent should be something like this:

```<code>render() {
  const { data } = this.props;

  return (
    <Image source={{ uri: data.uri }} style={{ width: 50, height: 50 }} />
  );
}
</code>```

Body:
I have just started working on a React Native project and I got stuck. I need to display a listof images from an API. The API only gives image urls that I can use like this:

<Image
      style={{width: 50, height: 50}}
      source={{uri: 'https://avatars0.githubusercontent.com/u/13102253?s=460&v=4'}}
/>

The image count is dynamic but I want to display only 3 images per row. How can I achieve this?

Body:
The React-Native FlatList is exactly what you need. It accepts a numColumns prop which in your case should be 3.

<FlatList
  numColumns={3}
  data={yourImagesArray}
  renderItem={<YourImageComponent >}
/>

Each iteration of the data array (which I called here yourImagesArray) is passed to the renderItem (which I called here YourImageComponent) as a data prop. So the render function of YourImageComponent should be something like this:

render() {
  const { data } = this.props;

  return (
    <Image source={{ uri: data.uri }} style={{ width: 50, height: 50 }} />
  );
}


问:
Cloning a section with JQuery not working
I try to clone a section after another section on user input (clicking a radio button), but it doesn’t works...
your help is appreciated. </p>

```<code><section class="clonetester">
    <input id="1a" type="radio" value="1" name="q1">yes
    <input id="1b" type="radio" value="0" name="q1" >no
    <br />
    <input id="date1" type="datetime-local" name="date" />date<br />
</section>

<section class="here">clone follows</section>

<script>
$('input').click(function(e){
    $('#1a').(':checked'){
        $('.clonetester').clone().appendTo(".here");
    }
})
</script>
</code>```

答:
You have multiple changes that you will have to make for it to work.

Use change instead of click for input elements.

$('#1a').(':checked') has to be replaced with $('#1a').is(':checked') and should be enclosed in a if block.

$('body').on('change', 'input[type="radio"]', function() {
    var $this = $(this);

    if ($this.hasClass('1a') && $this.is(':checked')) {
      // closeset clonetester

      var $clonetester = $this.closest('.clonetester').first();

      if ($clonetester) {
        $clonetester.clone().appendTo(".here");
      }
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="clonetester">
  <input class="1a" type="radio" value="1" name="q1">yes
  <input class="1b" type="radio" value="0" name="q1">no
  <br />
  <input class="date1" type="datetime-local" name="date" />date
  <br />
</section>
<section class="here">clone follows</section></code>```

Body:
I try to clone a section after another section on user input (clicking a radio button), but it doesn’t works...
your help is appreciated.

    <input id="1a" type="radio" value="1" name="q1">yes
    <input id="1b" type="radio" value="0" name="q1" >no

    <input id="date1" type="datetime-local" name="date" />date

clone follows

Body:
You have multiple changes that you will have to make for it to work.

Use change instead of click for input elements.

$('#1a').(':checked') has to be replaced with $('#1a').is(':checked') and should be enclosed in a if block.

$('body').on('change', 'input[type="radio"]', function() {
    var $this = $(this);

    if ($this.hasClass('1a') && $this.is(':checked')) {
      // closeset clonetester

      var $clonetester = $this.closest('.clonetester').first();

      if ($clonetester) {
        $clonetester.clone().appendTo(".here");
      }
    }
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="clonetester">
  <input class="1a" type="radio" value="1" name="q1">yes
  <input class="1b" type="radio" value="0" name="q1">no
  <br />
  <input class="date1" type="datetime-local" name="date" />date
  <br />
</section>
<section class="here">clone follows</section>


问:
Hide JQ Error Messages from Curl command
I'm running the following curl command:

```<code>installer_to_delete=$(curl -s -u username:password "URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn" | jq -r '.results[].uri'|sed 's=/api/storage==')

if [[ $installer_to_delete == "" ]]
then
    echo "No installers found"
else
    for installer in $installer_to_delete
    do
    echo $installer
    done
fi
</code>```

The error/output for this is:

```<code>assertion "cb == jq_util_input_next_input_cb" failed: file "/usr/src/ports/jq/jq-1.5-3.x86_64/src/jq-1.5/util.c", line 371, function: jq_util_input_get_position
</code>```

It shows this output whenever the Curl command can't find a file. How can I silence the JQ error from popping up whenever it can't find a file?

答:
Use curl --fail to only continue on to run the jq command if the curl succeeds:

```<code>url="URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn"

if result=$(curl -s --fail  -u username:password "$url"); then
  readarray -t installers < <(jq -r '.results[].uri' <<<"$result" | sed 's=/api/storage==')
  if (( ${#installers[@]} )); then
    for installer in "${installers_to_delete[@]}"; do
      echo "$installer"
    done
  else
    echo "Empty list of installers retrieved" >&2
  fi
else
  echo "HTTP error retrieving installers" >&2
fi
</code>```

Body:
I'm running the following curl command:

installer_to_delete=$(curl -s -u username:password "URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn" | jq -r '.results[].uri'|sed 's=/api/storage==')

if [[ $installer_to_delete == "" ]]
then
    echo "No installers found"
else
    for installer in $installer_to_delete
    do
    echo $installer
    done
fi

The error/output for this is:

assertion "cb == jq_util_input_next_input_cb" failed: file "/usr/src/ports/jq/jq-1.5-3.x86_64/src/jq-1.5/util.c", line 371, function: jq_util_input_get_position

It shows this output whenever the Curl command can't find a file. How can I silence the JQ error from popping up whenever it can't find a file?

Body:
Use curl --fail to only continue on to run the jq command if the curl succeeds:

url="URL/api/search/dates?dateFields=created&from=${Two_Years_Ago}&today&repos=npm-local-lrn"

if result=$(curl -s --fail  -u username:password "$url"); then
  readarray -t installers < <(jq -r '.results[].uri' <<<"$result" | sed 's=/api/storage==')
  if (( ${#installers[@]} )); then
    for installer in "${installers_to_delete[@]}"; do
      echo "$installer"
    done
  else
    echo "Empty list of installers retrieved" >&2
  fi
else
  echo "HTTP error retrieving installers" >&2
fi


问:
Conditional string representation based on variable type
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.

Let's say I have the following two variables:

```<code>import datetime as dt

a = None
b = dt.datetime(2017, 11, 30)

def str_format(str):
    return '{:%Y-%m-%d}'.format(str)
</code>```

The following would return a formatted string:

```<code>str_format(b)
'2017-11-30'
</code>```

But the following would return an error:

```<code>str_format(a)
TypeError: unsupported format string passed to NoneType.__format__
</code>```

So far I can up with the following solution:

```<code>def str_format(str):
    if isinstance(str, type(None)) is False:
        return '{:%Y-%m-%d}'.format(str)
    else:
        return '{}'.format(str)

str_format(a)
'None'

str_format(b)
'2017-11-30'
</code>```

However, I was looking at a more efficient/cleaner way of writing the function.

答:
your function is overcomplex. None is a singleton, so the pythonic way of testing against it is just is None.

Just do it in one line with a ternary expression:

```<code>def str_format(s):
   return str(s) if s is None else '{:%Y-%m-%d}'.format(s)
</code>```

or to return a default date (ex: 1/1/2010) if None is passed:

```<code>def str_format(s):
   return '{:%Y-%m-%d}'.format(s or dt.datetime(2010, 1, 1))
</code>```

as a side note don't use str as a variable name as it is the python string type.

Body:
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.

Let's say I have the following two variables:

import datetime as dt

a = None
b = dt.datetime(2017, 11, 30)

def str_format(str):
    return '{:%Y-%m-%d}'.format(str)

The following would return a formatted string:

str_format(b)
'2017-11-30'

But the following would return an error:

str_format(a)
TypeError: unsupported format string passed to NoneType.__format__

So far I can up with the following solution:

def str_format(str):
    if isinstance(str, type(None)) is False:
        return '{:%Y-%m-%d}'.format(str)
    else:
        return '{}'.format(str)

str_format(a)
'None'

str_format(b)
'2017-11-30'

However, I was looking at a more efficient/cleaner way of writing the function.

Body:
your function is overcomplex. None is a singleton, so the pythonic way of testing against it is just is None.

Just do it in one line with a ternary expression:

def str_format(s):
   return str(s) if s is None else '{:%Y-%m-%d}'.format(s)

or to return a default date (ex: 1/1/2010) if None is passed:

def str_format(s):
   return '{:%Y-%m-%d}'.format(s or dt.datetime(2010, 1, 1))

as a side note don't use str as a variable name as it is the python string type.


问:
OpenGL draws nothing on Mac, Objective-C
I'm trying to draw something using OpenGL with VAO and VBO objects. To do that, I just subclassed NSOpenGLView. By default, OpenGL v2.1 was used, so, I put a PixelFormat, wrote code, and solved all the printed errors. For now the app is running well, but nothing is drawing at the window, even glClearColor has no effect. Please, help me to find and solve the problems. My OS is Mac v10.12 with OpenGL v4.1.

MyOpenGLView.m, part 1:

```<code>#import "MyOpenGLView.h"
#include <OpenGL/gl3.h>
#include "error.h"

static const char *vertexShaderSource =
"#version 410\n"
"in vec3 posAttr;\n"
"in vec3 colAttr;\n"
"out vec3 col;\n"
"void main() {\n"
"   col = colAttr;\n"
"   gl_Position.xyz = posAttr;\n"
"   gl_Position.w = 1.0;\n"
"   col = colAttr;\n"
"}\n";

static const char *fragmentShaderSource =
"#version 410\n"
"in vec3 col;\n"
"out vec4 color;\n"
"void main() {\n"
"   color.rgb = col;\n"
"   color.a = 1.0;\n"
//"   color = vec4(1,1,1,1);\n"
"}\n";

// Shader properties
GLuint m_posAttr;
GLuint m_colAttr;
GLuint program;

// Arrays of positions and colors
float fTriangle[9];
float fTriangleColor[9];

// Low-level VBOs and VBAs
GLuint uiVBO[2];
GLuint uiVAO[1];

GLuint makeShader(GLenum type, const char *source) {
    GLuint shader;

    shader = glCreateShader(type);
    GetError();
    glShaderSource(shader, 1, &source, NULL);
    GetError();
    glCompileShader(shader);
    GetError();

#if defined(DEBUG)
    GLint logLength;

    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
    GetError();
    if (logLength > 0) {
        GLchar *log = malloc((size_t)logLength);
        glGetShaderInfoLog(shader, logLength, &logLength, log);
        GetError();
        NSLog(@"Shader compilation failed with error:\n%s", log);
        free(log);
    }
#endif

    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    GetError();
    if (0 == status) {
        glDeleteShader(shader);
        GetError();
        NSLog(@"Shader compilation failed from code!");
        assert(0);
    }

    return shader;
}
</code>```

MyOpenGLView.m, part 2:

```<code>//// General staff

@implementation MyOpenGLView

- (void)awakeFromNib {
    // Positions and colors of figures
    fTriangle[0] = -0.4f; fTriangle[1] = 0.1f; fTriangle[2] = 0.0f;
    fTriangle[3] = 0.4f; fTriangle[4] = 0.1f; fTriangle[5] = 0.0f;
    fTriangle[6] = 0.0f; fTriangle[7] = 0.7f; fTriangle[8] = 0.0f;
    fTriangleColor[0] = 1.0f; fTriangleColor[1] = 0.0f; fTriangleColor[2] = 0.0f;
    fTriangleColor[3] = 0.0f; fTriangleColor[4] = 1.0f; fTriangleColor[5] = 0.0f;
    fTriangleColor[6] = 0.0f; fTriangleColor[7] = 0.0f; fTriangleColor[8] = 1.0f;

    NSOpenGLPixelFormatAttribute attrs[] = {
        NSOpenGLPFADoubleBuffer,
        NSOpenGLPFADepthSize, 24,
        NSOpenGLPFAOpenGLProfile,
        NSOpenGLProfileVersion4_1Core,
        0
    };
    NSOpenGLPixelFormat *pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
    if (!pf) {
        NSLog(@"No OpenGL pixel format");
    }
    NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil];
    [self setPixelFormat:pf];
    [self setOpenGLContext:context];
    NSLog(@"%s", glGetString(GL_VERSION));
    GetError();

    GLuint vertexShader = makeShader(GL_VERTEX_SHADER, vertexShaderSource);
    GLuint fragmentShader = makeShader(GL_FRAGMENT_SHADER, fragmentShaderSource);

    program = glCreateProgram();
    GetError();
    glAttachShader(program, vertexShader);
    GetError();
    glAttachShader(program, fragmentShader);
    GetError();
    glLinkProgram(program);
    GetError();
    GLint status;
    glGetProgramiv(program, GL_LINK_STATUS, &status);
    GetError();
    if (0 == status) {
        NSLog(@"Failed to link shader program");
        assert( 0 );
    }

    m_posAttr = glGetAttribLocation(program, "posAttr");
    GetError();
    m_colAttr = glGetAttribLocation(program, "colAttr");
    GetError();

    glGenVertexArrays(1, &uiVAO[0]);
    glGenBuffers(2, &uiVBO[0]);
    GetError();
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(program);
    GetError();

    glBindVertexArray(uiVAO[0]);
    GetError();

    glBindBuffer(GL_ARRAY_BUFFER, uiVBO[0]);
    glBufferData(GL_ARRAY_BUFFER, 9*sizeof(float), fTriangle, GL_STATIC_DRAW);
    glEnableVertexAttribArray(m_posAttr);
    GetError();
    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 0, 0);
    GetError();

    glBindBuffer(GL_ARRAY_BUFFER, uiVBO[1]);
    glBufferData(GL_ARRAY_BUFFER, 9*sizeof(float), fTriangleColor, GL_STATIC_DRAW);
    glEnableVertexAttribArray(m_colAttr);
    GetError();
    glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, 0);
    GetError();

    glDrawArrays(GL_TRIANGLES, 0, 3);
    GetError();

    glDisableVertexAttribArray(m_posAttr);
    glDisableVertexAttribArray(m_colAttr);

    glFlush();
    GetError();
}

- (void)dealloc {
    glDeleteProgram(program);
    glDeleteBuffers(2, uiVBO);
    glDeleteVertexArrays(1, uiVAO);
    GetError();
}

@end
</code>```

error.h:

```<code>//// Prints OpenGL errors

#ifndef __ERROR_H__
#define __ERROR_H__

#include <stdlib.h>
#include <assert.h>

#ifdef  DEBUG

#define GetError( )\
{\
for ( GLenum Error = glGetError( ); ( GL_NO_ERROR != Error ); Error = glGetError( ) )\
{\
switch ( Error )\
{\
case GL_INVALID_ENUM:      printf( "\n%s\n\n", "GL_INVALID_ENUM"      ); assert( 0 ); break;\
case GL_INVALID_VALUE:     printf( "\n%s\n\n", "GL_INVALID_VALUE"     ); assert( 0 ); break;\
case GL_INVALID_OPERATION: printf( "\n%s\n\n", "GL_INVALID_OPERATION" ); assert( 0 ); break;\
case GL_OUT_OF_MEMORY:     printf( "\n%s\n\n", "GL_OUT_OF_MEMORY"     ); assert( 0 ); break;\
default:                                                                              break;\
}\
}\
}

#else

#define GetError( )

#endif /*   DEBUG     */
#endif /* __ERROR_H__ */
</code>```

答:
After lots of effort and code's modifications I figured it out: the only real problem was with NSOpenGLPFADoubleBuffer option in NSOpenGLPixelFormatAttribute array. After commenting this option I got the desired output.

To my mind, the reason is that I had 2 output graphical buffers. However, the code was executed a single time, 1st buffer was painted and then swapped. So, the 2nd buffer, which is empty, was drawn.

Body:
I'm trying to draw something using OpenGL with VAO and VBO objects. To do that, I just subclassed NSOpenGLView. By default, OpenGL v2.1 was used, so, I put a PixelFormat, wrote code, and solved all the printed errors. For now the app is running well, but nothing is drawing at the window, even glClearColor has no effect. Please, help me to find and solve the problems. My OS is Mac v10.12 with OpenGL v4.1.

MyOpenGLView.m, part 1:

#import "MyOpenGLView.h"
#include <OpenGL/gl3.h>
#include "error.h"

static const char *vertexShaderSource =
"#version 410\n"
"in vec3 posAttr;\n"
"in vec3 colAttr;\n"
"out vec3 col;\n"
"void main() {\n"
"   col = colAttr;\n"
"   gl_Position.xyz = posAttr;\n"
"   gl_Position.w = 1.0;\n"
"   col = colAttr;\n"
"}\n";

static const char *fragmentShaderSource =
"#version 410\n"
"in vec3 col;\n"
"out vec4 color;\n"
"void main() {\n"
"   color.rgb = col;\n"
"   color.a = 1.0;\n"
//"   color = vec4(1,1,1,1);\n"
"}\n";

// Shader properties
GLuint m_posAttr;
GLuint m_colAttr;
GLuint program;

// Arrays of positions and colors
float fTriangle[9];
float fTriangleColor[9];

// Low-level VBOs and VBAs
GLuint uiVBO[2];
GLuint uiVAO[1];

GLuint makeShader(GLenum type, const char *source) {
    GLuint shader;

    shader = glCreateShader(type);
    GetError();
    glShaderSource(shader, 1, &source, NULL);
    GetError();
    glCompileShader(shader);
    GetError();

#if defined(DEBUG)
    GLint logLength;

    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
    GetError();
    if (logLength > 0) {
        GLchar *log = malloc((size_t)logLength);
        glGetShaderInfoLog(shader, logLength, &logLength, log);
        GetError();
        NSLog(@"Shader compilation failed with error:\n%s", log);
        free(log);
    }
#endif

    GLint status;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
    GetError();
    if (0 == status) {
        glDeleteShader(shader);
        GetError();
        NSLog(@"Shader compilation failed from code!");
        assert(0);
    }

    return shader;
}

MyOpenGLView.m, part 2:

//// General staff

@implementation MyOpenGLView

- (void)awakeFromNib {
    // Positions and colors of figures
    fTriangle[0] = -0.4f; fTriangle[1] = 0.1f; fTriangle[2] = 0.0f;
    fTriangle[3] = 0.4f; fTriangle[4] = 0.1f; fTriangle[5] = 0.0f;
    fTriangle[6] = 0.0f; fTriangle[7] = 0.7f; fTriangle[8] = 0.0f;
    fTriangleColor[0] = 1.0f; fTriangleColor[1] = 0.0f; fTriangleColor[2] = 0.0f;
    fTriangleColor[3] = 0.0f; fTriangleColor[4] = 1.0f; fTriangleColor[5] = 0.0f;
    fTriangleColor[6] = 0.0f; fTriangleColor[7] = 0.0f; fTriangleColor[8] = 1.0f;

    NSOpenGLPixelFormatAttribute attrs[] = {
        NSOpenGLPFADoubleBuffer,
        NSOpenGLPFADepthSize, 24,
        NSOpenGLPFAOpenGLProfile,
        NSOpenGLProfileVersion4_1Core,
        0
    };
    NSOpenGLPixelFormat *pf = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
    if (!pf) {
        NSLog(@"No OpenGL pixel format");
    }
    NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:pf shareContext:nil];
    [self setPixelFormat:pf];
    [self setOpenGLContext:context];
    NSLog(@"%s", glGetString(GL_VERSION));
    GetError();

    GLuint vertexShader = makeShader(GL_VERTEX_SHADER, vertexShaderSource);
    GLuint fragmentShader = makeShader(GL_FRAGMENT_SHADER, fragmentShaderSource);

    program = glCreateProgram();
    GetError();
    glAttachShader(program, vertexShader);
    GetError();
    glAttachShader(program, fragmentShader);
    GetError();
    glLinkProgram(program);
    GetError();
    GLint status;
    glGetProgramiv(program, GL_LINK_STATUS, &status);
    GetError();
    if (0 == status) {
        NSLog(@"Failed to link shader program");
        assert( 0 );
    }

    m_posAttr = glGetAttribLocation(program, "posAttr");
    GetError();
    m_colAttr = glGetAttribLocation(program, "colAttr");
    GetError();

    glGenVertexArrays(1, &uiVAO[0]);
    glGenBuffers(2, &uiVBO[0]);
    GetError();
}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(program);
    GetError();

    glBindVertexArray(uiVAO[0]);
    GetError();

    glBindBuffer(GL_ARRAY_BUFFER, uiVBO[0]);
    glBufferData(GL_ARRAY_BUFFER, 9*sizeof(float), fTriangle, GL_STATIC_DRAW);
    glEnableVertexAttribArray(m_posAttr);
    GetError();
    glVertexAttribPointer(m_posAttr, 3, GL_FLOAT, GL_FALSE, 0, 0);
    GetError();

    glBindBuffer(GL_ARRAY_BUFFER, uiVBO[1]);
    glBufferData(GL_ARRAY_BUFFER, 9*sizeof(float), fTriangleColor, GL_STATIC_DRAW);
    glEnableVertexAttribArray(m_colAttr);
    GetError();
    glVertexAttribPointer(m_colAttr, 3, GL_FLOAT, GL_FALSE, 0, 0);
    GetError();

    glDrawArrays(GL_TRIANGLES, 0, 3);
    GetError();

    glDisableVertexAttribArray(m_posAttr);
    glDisableVertexAttribArray(m_colAttr);

    glFlush();
    GetError();
}

- (void)dealloc {
    glDeleteProgram(program);
    glDeleteBuffers(2, uiVBO);
    glDeleteVertexArrays(1, uiVAO);
    GetError();
}

@end

error.h:

//// Prints OpenGL errors

#ifndef __ERROR_H__
#define __ERROR_H__

#include <stdlib.h>
#include <assert.h>

#ifdef  DEBUG

#define GetError( )\
{\
for ( GLenum Error = glGetError( ); ( GL_NO_ERROR != Error ); Error = glGetError( ) )\
{\
switch ( Error )\
{\
case GL_INVALID_ENUM:      printf( "\n%s\n\n", "GL_INVALID_ENUM"      ); assert( 0 ); break;\
case GL_INVALID_VALUE:     printf( "\n%s\n\n", "GL_INVALID_VALUE"     ); assert( 0 ); break;\
case GL_INVALID_OPERATION: printf( "\n%s\n\n", "GL_INVALID_OPERATION" ); assert( 0 ); break;\
case GL_OUT_OF_MEMORY:     printf( "\n%s\n\n", "GL_OUT_OF_MEMORY"     ); assert( 0 ); break;\
default:                                                                              break;\
}\
}\
}

#else

#define GetError( )

#endif /*   DEBUG     */
#endif /* __ERROR_H__ */


问:
Inspecting Java threads in Linux using top
I am inspecting a Java process in Linux using

```<code>top -H
</code>```

However, I cannot read the name of the thread in the "COMMAND" column (because it is too long).  If I use 'c' to expand the full name of the process, then it is still to long to fit.

How can I obtain the full name of the command?

答:
You can inspect java threads with the tool jstack. It will list the names, stacktraces and other useful information of all threads belonging to the specified process pid.

Edit: The parameter nid in the thread dump of jstack is the hex version of the LWP that is displayed by top in the pid column for threads.

Body:
I am inspecting a Java process in Linux using

top -H

However, I cannot read the name of the thread in the "COMMAND" column (because it is too long).  If I use 'c' to expand the full name of the process, then it is still to long to fit.

How can I obtain the full name of the command?


问:
enum returning spring beans dynamically
Is it possible for an enum to return different spring beans for different values?

If possible, we can create an enum holding different values, and we can return different type of spring component for a different value.

I wanted to achieve something like this:

```<code>public enum MyFactory {
    BEAN1 {
        @Autowired
        Bean1 bean1;

       @Override
       public MyBean getMyBean() {
           return bean1;
       }
    },
    BEAN2 {
        @Autowired
        Bean1 bean2;

       @Override
       public MyBean getMyBean() {
           return bean2;
       }
    };

    public abstract MyBean getMyBean();
}
</code>```

Thanks,

答:
Do not use enums to conditionally inject.

Spring is more than capable of doing that on its own.

This runs somewhat counter to the whole benefit of dependency injection; so long as your components define a common interface between them, you can inject whichever one you want at will without the need for (self-managed) conditions.

Supposing that you had components AComponent and BComponent.  They are related and share a common-enough interface that it makes sense to codify it as an interface.  You can then define this.

```<code>public interface Component {
    Integer generateValue(String foo, List<Integer> bar);
}

public class AComponent implements Component {}
public class BComponent implements Component {}
</code>```

Then, you can inject it in at will:

```<code>private Component component;

@Autowired
public MyService(@Qualifier("bComponent") Component component) {
    this.component = component;
}
</code>```

Spring is perfectly capable of managing the dynamic wiring for you here.

Alternatively, if these components are completely unrelated to one another, then you'll have to wire them in individually anyway as opposed to dynamically selecting one based on your needs.

Title: enum returning spring beans dynamically

Body:
Is it possible for an enum to return different spring beans for different values?

If possible, we can create an enum holding different values, and we can return different type of spring component for a different value.

I wanted to achieve something like this:

public enum MyFactory {
    BEAN1 {
        @Autowired
        Bean1 bean1;

       @Override
       public MyBean getMyBean() {
           return bean1;
       }
    },
    BEAN2 {
        @Autowired
        Bean1 bean2;

       @Override
       public MyBean getMyBean() {
           return bean2;
       }
    };

    public abstract MyBean getMyBean();
}

Thanks,

Body:
Do not use enums to conditionally inject.

Spring is more than capable of doing that on its own.

This runs somewhat counter to the whole benefit of dependency injection; so long as your components define a common interface between them, you can inject whichever one you want at will without the need for (self-managed) conditions.

Supposing that you had components AComponent and BComponent.  They are related and share a common-enough interface that it makes sense to codify it as an interface.  You can then define this.

public interface Component {
    Integer generateValue(String foo, List<Integer> bar);
}

public class AComponent implements Component {}
public class BComponent implements Component {}

Then, you can inject it in at will:

private Component component;

@Autowired
public MyService(@Qualifier("bComponent") Component component) {
    this.component = component;
}

Spring is perfectly capable of managing the dynamic wiring for you here.

Alternatively, if these components are completely unrelated to one another, then you'll have to wire them in individually anyway as opposed to dynamically selecting one based on your needs.


问:
Reshaping 2 numpy dimensions into one with zipping?
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

```<code>[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]
</code>```

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

```<code>[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]
</code>```

Unlike the array we get with reshape:

```<code>[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]
</code>```

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

```<code>import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])
</code>```

And again, I want my output to look like this instead:

```<code>[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]
</code>```

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps

Body:
I tried searching for this question but I couldn't find anything relevant.

The quickest way to describe the problem is with a simple example:
lets say I have a 2D numpy arrayl like this:

[[0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]

So it has the shape [3,6]
I want to reshape it into a 1D array that looks like this:

[0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ]

Unlike the array we get with reshape:

[ 0,  1,  2,  3, 10, 11, 12, 13, 20, 21, 22, 23]

Now, to the actual problem I have...
I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above.
And another example would be:

import numpy
a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]],
[[100,101,102],[110,111,112],[120,121,122]],
 [[200,201,202],[210,211,212],[220,221,222]]])
a.shape
a.reshape(3,9)
OUTPUT: array([[  0,   1,   2,  10,  11,  12,  20,  21,  22],
       [100, 101, 102, 110, 111, 112, 120, 121, 122],
       [200, 201, 202, 210, 211, 212, 220, 221, 222]])

And again, I want my output to look like this instead:

[[  0,  10,  20,   1,  11,  21,   2,  12,  22],
 [100, 110, 120, 101, 111, ..................],
 [...........................................]]

EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for:

Interweave dimensions numpy array

Zip dimensions numpy array

Numpy reshape ordered dimensions

Tensor reshape dimensions timesteps

Body:
We need to swap the last two axes with np.swapaxes or np.transpose and then reshape.

For 2D input case, it would be -

a.swapaxes(-2,-1).ravel()

For 3D input case, only the reshape part changes -

a.swapaxes(-2,-1).reshape(a.shape[0],-1)

Generic way : To make it generic that would cover all n-dim array cases -

a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze()

Sample runs

2D case :

In [186]: a
Out[186]:
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23]])

In [187]: a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze()
Out[187]: array([ 0, 10, 20,  1, 11, 21,  2, 12, 22,  3, 13, 23])

3D case :

In [189]: a
Out[189]:
array([[[  0,   1,   2],
        [ 10,  11,  12],
        [ 20,  21,  22]],

       [[100, 101, 102],
        [110, 111, 112],
        [120, 121, 122]],

       [[200, 201, 202],
        [210, 211, 212],
        [220, 221, 222]]])

In [190]: a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze()
Out[190]:
array([[  0,  10,  20,   1,  11,  21,   2,  12,  22],
       [100, 110, 120, 101, 111, 121, 102, 112, 122],
       [200, 210, 220, 201, 211, 221, 202, 212, 222]])

Runtime test -

In [14]: a = np.random.rand(3,3,3)

# @mahdi n75's soln
In [15]: %timeit np.reshape(a,(3,9), order='F')
1000000 loops, best of 3: 1.22 µs per loop

In [16]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1)
1000000 loops, best of 3: 1.01 µs per loop

In [20]: a = np.random.rand(30,30,30)

# @mahdi n75's soln
In [21]: %timeit np.reshape(a,(30,900), order='F')
10000 loops, best of 3: 28.4 µs per loop

In [22]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1)
10000 loops, best of 3: 18.9 µs per loop

In [17]: a = np.random.rand(300,300,300)

# @mahdi n75's soln
In [18]: %timeit np.reshape(a,(300,90000), order='F')
1 loop, best of 3: 333 ms per loop

In [19]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1)
10 loops, best of 3: 52.4 ms per loop


问:
kdb/q: Increase visible rows in browser
Hi I am running kdb and usually use the browser for basic viewing of the tables by running the kdb on a port: \p xxx
My questions is how can I increase the visible rows in the browser? Currently I believe there is a fixed number of rows that are visible.
I would like to be able to view more or less rows.
Is there a settings or a command?

答:
To expand on the other answer, kdb allows you to change to the console size in a session with \c or via command line with the -c flag. The HTTP size is with an upper case C (\C and -C).

The HTTP size has limits of 10 and 2000 for both height and width, so if you wished to set a height of 2000 and width of 1000:

```<code>q)\C 2000 1000
</code>```

Title: kdb/q: Increase visible rows in browser

Body:
To expand on the other answer, kdb allows you to change to the console size in a session with \c or via command line with the -c flag. The HTTP size is with an upper case C (\C and -C).

The HTTP size has limits of 10 and 2000 for both height and width, so if you wished to set a height of 2000 and width of 1000:

q)\C 2000 1000


问:
Javascript replace all duplicate characters in an array the same way
I'm replacing all characters in an array with random letters/numbers. However, duplicate letters do not get the same values which is what I want.

```<code>var rWords = ["all","ball","balloon"];
var word = rWords[Math.floor(Math.random() * rWords.length)];

var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var getPos = function(arr) {
    return Math.floor(Math.random() * arr.length);
}

var arr = word.split('');
for (var i = 0; i < word.length; i++) {
    arr.splice(getPos(arr), 1, letters[getPos(letters)]);
}
word = arr.join('');
</code>```

I want the output to be something like:

all = 4xx, ball = Y4xx, balloon = Y4xxRR1

答:
create a map function that return unique char for same input (for each character we want to replace we check if we already have a replacement for it stored in _map, if not then we find one and use it and store it in _map for future use)

var rWords = ["all","ball","balloon"];

var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

var _map = {}
function map(char) {
    if (_map[char] === undefined) {
        _map[char] = letters[Math.floor(Math.random() * letters.length)]
    }
    return _map[char]
}
var result = rWords.map(function(word) {
    var arr = word.split('');
    for (var i = 0; i < word.length; i++) {
        arr.splice(i, 1, map(arr[i]));
    }
    return arr.join('');
})

console.log(result);```

Body:
I'm replacing all characters in an array with random letters/numbers. However, duplicate letters do not get the same values which is what I want.

var rWords = ["all","ball","balloon"];
var word = rWords[Math.floor(Math.random() * rWords.length)];

var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var getPos = function(arr) {
    return Math.floor(Math.random() * arr.length);
}

var arr = word.split('');
for (var i = 0; i < word.length; i++) {
    arr.splice(getPos(arr), 1, letters[getPos(letters)]);
}
word = arr.join('');

I want the output to be something like:

all = 4xx, ball = Y4xx, balloon = Y4xxRR1


问:
<prefwindow> sizing itself to the wrong tab when browser.preferences.animateFadeIn == true
I've run into (yet another) bug with the preferences screen of my extension. When browser.preferences.animateFadeIn is set to true (as it is on Mac), the window size should change to fit the content exactly on switching panes. Instead it is sized to the largest pane when the window is opened, but it changes by as much as it should when switching panes. If that's not too clear, here is a screencast: http://files.droplr.com/files/22337488/4IVT.ScreenFlow.mov

Even after removing all

答:
Yes, I'd agree that it's a bug. When the first pane loads, the prefwindow sizes itself to its content. In your case, this includes several "background" panes. Unfortunately the code to detect this gets bypassed in the animating case. The current code looks something like this:

```<code>if (animation) {
  if (switching)
    animate();
} else {
  if (panes > 1)
    fixHeight();
}
</code>```

It should instead look something like this:

```<code>if (animation && switching)
  animate();
else if (panes > 1)
  fixHeight();
</code>```

This would fix the height of the first pane even when animation was enabled. (If there is only one pane then there is nothing to do of course.)

Body:
Yes, I'd agree that it's a bug. When the first pane loads, the prefwindow sizes itself to its content. In your case, this includes several "background" panes. Unfortunately the code to detect this gets bypassed in the animating case. The current code looks something like this:

if (animation) {
  if (switching)
    animate();
} else {
  if (panes > 1)
    fixHeight();
}

It should instead look something like this:

if (animation && switching)
  animate();
else if (panes > 1)
  fixHeight();

This would fix the height of the first pane even when animation was enabled. (If there is only one pane then there is nothing to do of course.)


问:
CSS how to maintain image size without cropping

I am trying to have image display without cropping.

These are the code sections I have tried manipulating without success.  I also searched stackoverflow and W3 schools for variations but I'm not getting closer so believe my approach is flawed.

```<code>.FeaturedPost .snippet-thumbnail {
   float: $(startSide);
   margin: 0;
   margin-$endSide: 1em;
}

.FeaturedPost .snippet-thumbnail img {
 width: 200px;
 height: auto;
 max-width: 100%;
 float: left;
 margin: 10px;
}
</code>```

The goal is that the full image will show without cropping - however it continues to crop the top and bottom of image.  See attached screenshot, and site is www.paddlebeforethewave.com

screenshot of image cropping

I am trying to learn.  Appreciate any tips on why my approach is flawed.

thank you very much.

Updating with further information based on comments.

```<code>  <b:includable id='snippetedPostThumbnail'>
    <div class='snippet-thumbnail'>
      <b:with value='data:post.featuredImage.isYoutube ? resizeImage(data:post.featuredImage.youtubeMaxResDefaultUrl, 945, "945:600"): ""' var='highRes'>
          <b:include data='{image: data:post.featuredImage, imageSizes: [256, 512, 945, 1684],imageRatio: "945:600",sourceSizes: "(min-width: 954px) 842px, (min-width: 801px) calc(100vw - 112px), calc(100vw - 64px)",enhancedSourceset: data:highRes}' name='responsiveImage'/>
      </b:with>
    </div>
  </b:includable>
</code>```

答:
The page at http://www.paddlebeforethewave.com is using:

```<code><img alt="Image" sizes="(min-width: 954px) 842px, (min-width: 801px) calc(100vw - 112px), calc(100vw - 64px)" src="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png" srcset="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w256-h162-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 256w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w512-h325-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 512w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w945-h600-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 945w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w1684-h1069-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 1684w">
</code>```

and if you examine the srcset URLs you'll notice the images are cropped. For example, this image.

However, the default image (https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png) is not cropped.

So, one option would be to remove the srcset and go with:

```<code><img alt="Image" src="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png" />
</code>```

Body:
I am trying to have image display without cropping.

These are the code sections I have tried manipulating without success.  I also searched stackoverflow and W3 schools for variations but I'm not getting closer so believe my approach is flawed.

.FeaturedPost .snippet-thumbnail {
   float: $(startSide);
   margin: 0;
   margin-$endSide: 1em;
}

.FeaturedPost .snippet-thumbnail img {
 width: 200px;
 height: auto;
 max-width: 100%;
 float: left;
 margin: 10px;
}

The goal is that the full image will show without cropping - however it continues to crop the top and bottom of image.  See attached screenshot, and site is www.paddlebeforethewave.com

screenshot of image cropping

I am trying to learn.  Appreciate any tips on why my approach is flawed.

thank you very much.

Updating with further information based on comments.

Body:
The page at http://www.paddlebeforethewave.com is using:

<img alt="Image" sizes="(min-width: 954px) 842px, (min-width: 801px) calc(100vw - 112px), calc(100vw - 64px)" src="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png" srcset="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w256-h162-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 256w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w512-h325-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 512w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w945-h600-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 945w, https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/w1684-h1069-p-k-no-nu/paddleb4thewave-icon-cmyk-300px.png 1684w">

and if you examine the srcset URLs you'll notice the images are cropped. For example, this image.

However, the default image (https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png) is not cropped.

So, one option would be to remove the srcset and go with:

<img alt="Image" src="https://1.bp.blogspot.com/-ntbx6vLDHxM/Wh4bAtKUUbI/AAAAAAAAMYg/s4i_ebRrafUPeG7fQGeTloTDBfVGVg5EQCLcBGAs/s200/paddleb4thewave-icon-cmyk-300px.png" />


问:
re.sub to replace multiple lists with corresponding matches (Python)
Through Regular Expression, I wanted to annotate sentiment lexicon of given sentences with corresponding polarity tags, so I wrote the code lines as below.

```<code>import re
vocab = ['good/POSI','bad/NEAG','strong/POSI','dirty/NEGA', 'never/SWIT']
sent = ["It is really good", "strong man never gets his body dirty"]

for token in vocab:
    word = re.sub(r'(\\w+)\\/[A-Z]+_[A-Z]+','\\1', token)
    TA = re.sub(str(word),str(token), str(sent))
print(TA)
</code>```

I tried to have the result like this.

```<code>["It is really good/POSI", "strong/POSI man never/SWIT gets his body dirty/NEGA"]
</code>```

Unfortunately, I couldn't, and I have no idea which lines have a problem.
Is there any better way for the annotation?

答:
I suggest to change the vocab list to a dictionary instead:

```<code>>>> vocab = {v[:v.find('/')]: v for v in vocab}
>>> vocab
{'dirty': 'dirty/NEGA', 'good': 'good/POSI', 'never': 'never/SWIT', 'bad': 'bad/NEAG', 'strong': 'strong/POSI'}
</code>```

This way you could perform a replacement of \w+ with a value in the dictionary:

```<code>result = []
for line in sent:
    line = re.sub(r'(\w+)', lambda w: vocab.get(w.group(), w.group()), line)
    result.append(line)
print(result)
</code>```

This will output what you wanted:

```<code>['It is really good/POSI', 'strong/POSI man never/SWIT gets his body dirty/NEGA']
</code>```

Body:
Through Regular Expression, I wanted to annotate sentiment lexicon of given sentences with corresponding polarity tags, so I wrote the code lines as below.

import re
vocab = ['good/POSI','bad/NEAG','strong/POSI','dirty/NEGA', 'never/SWIT']
sent = ["It is really good", "strong man never gets his body dirty"]

for token in vocab:
    word = re.sub(r'(\\w+)\\/[A-Z]+_[A-Z]+','\\1', token)
    TA = re.sub(str(word),str(token), str(sent))
print(TA)

I tried to have the result like this.

["It is really good/POSI", "strong/POSI man never/SWIT gets his body dirty/NEGA"]

Unfortunately, I couldn't, and I have no idea which lines have a problem.
Is there any better way for the annotation?

Body:
I suggest to change the vocab list to a dictionary instead:

>>> vocab = {v[:v.find('/')]: v for v in vocab}
>>> vocab
{'dirty': 'dirty/NEGA', 'good': 'good/POSI', 'never': 'never/SWIT', 'bad': 'bad/NEAG', 'strong': 'strong/POSI'}

This way you could perform a replacement of \w+ with a value in the dictionary:

result = []
for line in sent:
    line = re.sub(r'(\w+)', lambda w: vocab.get(w.group(), w.group()), line)
    result.append(line)
print(result)

This will output what you wanted:

['It is really good/POSI', 'strong/POSI man never/SWIT gets his body dirty/NEGA']


问:
How to place TextView at the very bottom of ContraintLayout?
I'm trying to position a TextView to the bottom of ConstraintLayout, but although I put app:layout_constraintHorizontal_bias="1.0" there are a kind of 'marging' of 'padding' as you can see on the image below:

The constraint to the bottom, adds this padding and I'm unable to remove it. This is my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp">

<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/picture"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:src="@drawable/ic_launcher_background"
    app:civ_border_color="#FF000000"
    app:civ_border_width="2dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

<TextView
    android:id="@+id/title"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_alignParentTop="true"
    android:layout_marginStart="8dp"
    android:layout_weight=".90"
    android:ellipsize="end"
    android:maxLines="2"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:singleLine="false"
    android:textColor="@android:color/black"
    android:textSize="16sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="@+id/picture"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toEndOf="@+id/picture"
    app:layout_constraintTop_toTopOf="@+id/picture"
    app:layout_constraintVertical_bias="0.0" />

<ImageView
    android:id="@+id/badge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:src="@drawable/orange_badge"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.08"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    android:contentDescription="notificationBadge" />

<TextView
    android:id="@+id/status"
    android:layout_height="23dp"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="24dp"
    android:gravity="bottom|end"
    android:maxLines="1"
    android:singleLine="true"
    android:textSize="12sp"
    android:layout_width="133dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

</android.support.constraint.ConstraintLayout>
</code>```

The TextView that I'm trying to place at the bottom is @+id/status.
Thank you in advance.

答: Remove the line android:paddingBottom="16dp" in the main ConstrainLayout element</p>

Body:
I'm trying to position a TextView to the bottom of ConstraintLayout, but although I put app:layout_constraintHorizontal_bias="1.0" there are a kind of 'marging' of 'padding' as you can see on the image below:

The constraint to the bottom, adds this padding and I'm unable to remove it. This is my XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp">

<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/picture"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:src="@drawable/ic_launcher_background"
    app:civ_border_color="#FF000000"
    app:civ_border_width="2dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

<TextView
    android:id="@+id/title"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_alignParentTop="true"
    android:layout_marginStart="8dp"
    android:layout_weight=".90"
    android:ellipsize="end"
    android:maxLines="2"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:singleLine="false"
    android:textColor="@android:color/black"
    android:textSize="16sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="@+id/picture"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toEndOf="@+id/picture"
    app:layout_constraintTop_toTopOf="@+id/picture"
    app:layout_constraintVertical_bias="0.0" />

<ImageView
    android:id="@+id/badge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:src="@drawable/orange_badge"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.08"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    android:contentDescription="notificationBadge" />

<TextView
    android:id="@+id/status"
    android:layout_height="23dp"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="24dp"
    android:gravity="bottom|end"
    android:maxLines="1"
    android:singleLine="true"
    android:textSize="12sp"
    android:layout_width="133dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

</android.support.constraint.ConstraintLayout>

The TextView that I'm trying to place at the bottom is @+id/status.
Thank you in advance.


问:
Exception has been thrown by the target of an invocation
I know this is a relatively common error but I am working in an application that allows custom reports to be written using vb.net or C# for scripting. Error handling is very poor and I am not knowledgable enough to add my own (if it is even possible).

My code simply retrieves a value that is stored in a textbox on the report formatted as LastName, FirstName and truncates all characters after the comma. This value LastName is placed in a new textbox on the report. Here is my code:

```<code>Sub Detail1_Format

    Dim lastNameFirstName As String = ""
    Dim lastName As String = ""
    Dim lastNameCommaIndex As Integer=

'set lastNameFirstName value from data on report'
    lastNameFirstName = ReportUtilities.ReturnTextBoxValue(rpt,"Detail1","txtdtr_DTOOLS_CompanyName")

'find index of first comma in lastNameFirstName string'
    lastNameCommaIndex = lastNameFirstName.IndexOf(",")

'set contents of lastName using substring of lastNameFirstString'
    lastName = lastNameFirstName.SubString(0, lastNameCommaIndex)
'the error happens above when I use lastNameCommaIndex'
'to set the number of characters in my substring'

'set client name textbox value using lastName'
    ReportUtilities.SetTextBoxValue(rpt,"Detail1","txtdtr_CALC_ClientName",lastName)

End Sub
</code>```

The error happens when I use lastNameCommaIndex to set the number of characters in my substring. If I replace it with a number the report is published properly.

答:
You might want to use string.split it will make this a lot easier

e.g.

```<code>   If Not String.IsNullOrWhiteSpace(lastNameFirstName) Then

        lastName = lastNameFirstName.Split(",".ToCharArray())(0)

    End If
</code>```

Here's how you write IsNullOrWriteSpace if you don't have .net 4.0

```<code>Function IsNullOrWhiteSpace(ByVal s As String) As Boolean

    If s Is Nothing Then
        Return True
    End If

    Return s.Trim() = String.Empty

End Function
</code>```

Body:
I know this is a relatively common error but I am working in an application that allows custom reports to be written using vb.net or C# for scripting. Error handling is very poor and I am not knowledgable enough to add my own (if it is even possible).

My code simply retrieves a value that is stored in a textbox on the report formatted as LastName, FirstName and truncates all characters after the comma. This value LastName is placed in a new textbox on the report. Here is my code:

Sub Detail1_Format

    Dim lastNameFirstName As String = ""
    Dim lastName As String = ""
    Dim lastNameCommaIndex As Integer=

'set lastNameFirstName value from data on report'
    lastNameFirstName = ReportUtilities.ReturnTextBoxValue(rpt,"Detail1","txtdtr_DTOOLS_CompanyName")

'find index of first comma in lastNameFirstName string'
    lastNameCommaIndex = lastNameFirstName.IndexOf(",")

'set contents of lastName using substring of lastNameFirstString'
    lastName = lastNameFirstName.SubString(0, lastNameCommaIndex)
'the error happens above when I use lastNameCommaIndex'
'to set the number of characters in my substring'

'set client name textbox value using lastName'
    ReportUtilities.SetTextBoxValue(rpt,"Detail1","txtdtr_CALC_ClientName",lastName)

End Sub

The error happens when I use lastNameCommaIndex to set the number of characters in my substring. If I replace it with a number the report is published properly.

Body:
You might want to use string.split it will make this a lot easier

e.g.

   If Not String.IsNullOrWhiteSpace(lastNameFirstName) Then

        lastName = lastNameFirstName.Split(",".ToCharArray())(0)

    End If

Here's how you write IsNullOrWriteSpace if you don't have .net 4.0

Function IsNullOrWhiteSpace(ByVal s As String) As Boolean

    If s Is Nothing Then
        Return True
    End If

    Return s.Trim() = String.Empty

End Function


答:
Your <ConstraintLayout> tag defines these attributes:

```<code>android:paddingBottom="16dp"
android:paddingRight="16dp"
</code>```

This is the extra space you see. You will have to remove this padding from the parent view, and add margins to the children in order to achieve the same visual effect without causing every child to be inset.

Title: How to place TextView at the very bottom of ContraintLayout?

Body:
Your <ConstraintLayout> tag defines these attributes:

android:paddingBottom="16dp"
android:paddingRight="16dp"

This is the extra space you see. You will have to remove this padding from the parent view, and add margins to the children in order to achieve the same visual effect without causing every child to be inset.


问:
Unity relative directions in shader
I have a scene in Unity with:

An empty gameobject, let's call it "Center"

A mesh projected onto a spherical surface (with Center as center of the sphere) by a shader

It works fine.
I tried to add 3dnoise based center -> vertex (let's call it "direction").
It works fine too.
Now I'm trying to use the same 3dnoise based on direction, but relative to Center orientation. Unity has a feature called transform.WorldToLocalMatrix (working well in C#), but since it's not possible to pass matrices as properties in Unity shaders, I've passed it as four separated *Vector4*s:

```<code>void Update() {
    terrainMaterial.SetVector("_Center", transform.position);
    terrainMaterial.SetVector("_Matrix1", new Vector4(transform.worldToLocalMatrix.m00, transform.worldToLocalMatrix.m01, transform.worldToLocalMatrix.m02, 0.0f));
    terrainMaterial.SetVector("_Matrix2", new Vector4(transform.worldToLocalMatrix.m10, transform.worldToLocalMatrix.m11, transform.worldToLocalMatrix.m12, 0.0f));
    terrainMaterial.SetVector("_Matrix3", new Vector4(transform.worldToLocalMatrix.m20, transform.worldToLocalMatrix.m21, transform.worldToLocalMatrix.m22, 0.0f));
    terrainMaterial.SetVector("_Matrix4", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
}
</code>```

Then, in shader:

```<code>Shader "Custom/testShader"
</code>```

{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0

```<code>    _Center("Center of the Planet", Vector) = (0.0, 0.0, 0.0)
    _Matrix1("1", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix2("2", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix3("3", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix4("4", Vector) = (0.0, 0.0, 0.0, 0.0)

    _Scale("Scale of Noise", Range(0.001, 200.0)) = 1.0
    _Height("Height of Noise", Range(1.0, 500.0)) = 5.0
}

    SubShader
    {
        Tags{ "RenderType" = "Opaque" }

        CGPROGRAM

        #pragma target 3.0
        #pragma surface surf Standard vertex:vert

        #include "libs/noiseSimplex.cginc"

        sampler2D _MainTex;
        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        float3 _Center;
        float4 _Matrix1;
        float4 _Matrix2;
        float4 _Matrix3;
        float4 _Matrix4;

        float _Scale;
        float _Height;

        struct Input {
            float2 uv_MainTex;
        };

        void vert(inout appdata_full v)
        {
            float3 direction = mul(unity_ObjectToWorld, v.vertex) - _Center;
            float4x4 worldToLocal_matrix = (_Matrix1.x, _Matrix1.y, _Matrix1.z, _Matrix1.w,
                                            _Matrix2.x, _Matrix2.y, _Matrix2.z, _Matrix2.w,
                                            _Matrix3.x, _Matrix3.y, _Matrix3.z, _Matrix3.w,
                                            _Matrix4.x, _Matrix4.y, _Matrix4.z, _Matrix4.w);

            float3 local_direction = mul(worldToLocal_matrix, direction);

            direction = _Center + normalize(direction) * (_Radius + snoise(local_direction * _Scale) * _Height);
            v.vertex = mul(unity_WorldToObject, float4(direction, 1));
        }

        void surf(Input IN, inout SurfaceOutputStandard o)
        {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;

            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }

        ENDCG
}

Fallback "Diffuse"
}
</code>```

The thing that I don't understand at all is... without changing anything else, this line works:

```<code>direction = _Center + normalize(direction) * (_Radius + snoise(direction * _Scale) * _Height);
</code>```

This one doesn't:

```<code>direction = _Center + normalize(direction) * (_Radius + snoise(local_direction * _Scale) * _Height);
</code>```

Any idea about what I'm doing wrong?

答:
RESOLVED:

Passing WorldToLocalMatrix through SetMatrix() is fine, but splitting it and reconstructing in the shader doesn't work. I'm confused

Title: Unity relative directions in shader

Body:
I have a scene in Unity with:

An empty gameobject, let's call it "Center"

A mesh projected onto a spherical surface (with Center as center of the sphere) by a shader

It works fine.
I tried to add 3dnoise based center -> vertex (let's call it "direction").
It works fine too.
Now I'm trying to use the same 3dnoise based on direction, but relative to Center orientation. Unity has a feature called transform.WorldToLocalMatrix (working well in C#), but since it's not possible to pass matrices as properties in Unity shaders, I've passed it as four separated *Vector4*s:

void Update() {
    terrainMaterial.SetVector("_Center", transform.position);
    terrainMaterial.SetVector("_Matrix1", new Vector4(transform.worldToLocalMatrix.m00, transform.worldToLocalMatrix.m01, transform.worldToLocalMatrix.m02, 0.0f));
    terrainMaterial.SetVector("_Matrix2", new Vector4(transform.worldToLocalMatrix.m10, transform.worldToLocalMatrix.m11, transform.worldToLocalMatrix.m12, 0.0f));
    terrainMaterial.SetVector("_Matrix3", new Vector4(transform.worldToLocalMatrix.m20, transform.worldToLocalMatrix.m21, transform.worldToLocalMatrix.m22, 0.0f));
    terrainMaterial.SetVector("_Matrix4", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
}

Then, in shader:

Shader "Custom/testShader"

{
    Properties
    {
        _Color("Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
        _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0

    _Center("Center of the Planet", Vector) = (0.0, 0.0, 0.0)
    _Matrix1("1", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix2("2", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix3("3", Vector) = (0.0, 0.0, 0.0, 0.0)
    _Matrix4("4", Vector) = (0.0, 0.0, 0.0, 0.0)

    _Scale("Scale of Noise", Range(0.001, 200.0)) = 1.0
    _Height("Height of Noise", Range(1.0, 500.0)) = 5.0
}

    SubShader
    {
        Tags{ "RenderType" = "Opaque" }

        CGPROGRAM

        #pragma target 3.0
        #pragma surface surf Standard vertex:vert

        #include "libs/noiseSimplex.cginc"

        sampler2D _MainTex;
        half _Glossiness;
        half _Metallic;
        fixed4 _Color;

        float3 _Center;
        float4 _Matrix1;
        float4 _Matrix2;
        float4 _Matrix3;
        float4 _Matrix4;

        float _Scale;
        float _Height;

        struct Input {
            float2 uv_MainTex;
        };

        void vert(inout appdata_full v)
        {
            float3 direction = mul(unity_ObjectToWorld, v.vertex) - _Center;
            float4x4 worldToLocal_matrix = (_Matrix1.x, _Matrix1.y, _Matrix1.z, _Matrix1.w,
                                            _Matrix2.x, _Matrix2.y, _Matrix2.z, _Matrix2.w,
                                            _Matrix3.x, _Matrix3.y, _Matrix3.z, _Matrix3.w,
                                            _Matrix4.x, _Matrix4.y, _Matrix4.z, _Matrix4.w);

            float3 local_direction = mul(worldToLocal_matrix, direction);

            direction = _Center + normalize(direction) * (_Radius + snoise(local_direction * _Scale) * _Height);
            v.vertex = mul(unity_WorldToObject, float4(direction, 1));
        }

        void surf(Input IN, inout SurfaceOutputStandard o)
        {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
            o.Albedo = c.rgb;

            o.Metallic = _Metallic;
            o.Smoothness = _Glossiness;
            o.Alpha = c.a;
        }

        ENDCG
}

Fallback "Diffuse"
}

The thing that I don't understand at all is... without changing anything else, this line works:

direction = _Center + normalize(direction) * (_Radius + snoise(direction * _Scale) * _Height);

This one doesn't:

direction = _Center + normalize(direction) * (_Radius + snoise(local_direction * _Scale) * _Height);

Any idea about what I'm doing wrong?


问:
Development of spring boot microservice using spring cloud
I am trying to  develop a microservices using spring mvc and spring boot with using spring cloud tools and services. And i am planning to deploy my spring cloud microservices in elastic beanstalk. So I have a doubt in deployment process.

Whether I need to use any container service for deployment into elastic beanstalk? When I exploring i found that writings about containers in cloud foundry. So i  felt confusion that need I deploy any container services into elastic beanstalk or need to include container service dependency file when developing service??

答:
You can use AWS Elastic Beanstalk(EB) or EC2 Container Service(ECS).

If you want to control your scaling and capacity use ECS, ECS will give you control, as you have to specify the size and number of nodes in the cluster and whether or not auto-scaling should be used.

If you want to focus on the app and not much on DevOps use Elastic Beanstalk.  For Elastic Beanstalk just provide a Dockerfile and EB takes care of scaling your provisioning of number and size of nodes, you basically can forget about the infrastructure with the EB route.


问:
REST equivalent of CreateEnvelopeFromTemplates?
The SOAP method CreateEnvelopeFromTemplates takes a list of TemplateReference objects which allows me to create a 1-1 mapping of documents in my ECM system to DocuSign Templates. This has worked great up until now and has allowed me to build an envelope creation algorithm without having to know how many documents are involved in a specific use case.

SOAP however does not support the new Payment tabs. In trying to find a REST replacement for this API call I haven't been able to find a way to create an envelope where each document references a different Template. The envelopes: create method for example only allows for one templateID in the envelopeDefinition. Is there a way to port the functionality I've built over to REST?

BONUS QUESTION: Why does the DocuSign backend differentiate between SOAP and REST created envelopes when applying Templates? I didn't expect to be able to programatically create Payment tabs on an envelope with SOAP, but I'm surprised specifying a Template with Payment tabs using SOAP prevents those tabs from working.

This is my SOAP call with non-functional referencing a Template with non-functional Payment tabs:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CreateEnvelopeFromTemplates xmlns="http://www.docusign.net/API/3.0">
            <TemplateReferences>
                <TemplateReference>
                    <TemplateLocation>Server</TemplateLocation>
                    <Template>8E556CD1-D343-4C07-9401-D88B00A67671</Template>
                    <Document>
                        <ID>90267</ID>
                        <Name>DS - Template Mapping - 12/4/2017 John Payme2 (90267)</Name>
                        <PDFBytes>omitted</PDFBytes>
                        <FileExtension>pdf</FileExtension>
                    </Document>
                    <RoleAssignments>
                        <RoleAssignment>
                            <RoleName>Payer</RoleName>
                            <RecipientID>37974046</RecipientID>
                        </RoleAssignment>
                    </RoleAssignments>
                    <Sequence>1</Sequence>
                </TemplateReference>
            </TemplateReferences>
            <Recipients>
                <Recipient>
                    <ID>37974046</ID>
                    <UserName>John Payme2</UserName>
                    <Email>ANDREW.MORTON@HYLAND.COM</Email>
                    <Type>Signer</Type>
                    <AccessCode />
                    <RequireIDLookup>false</RequireIDLookup>
                    <RoutingOrder>1</RoutingOrder>
                    <Note/>
                    <RoleName>Payer</RoleName>
                </Recipient>
            </Recipients>
            <EnvelopeInformation>
                <AccountId>9cace92e-1384-4cf7-9b4c-a2bd70aab9a1</AccountId>
            </EnvelopeInformation>
            <ActivateEnvelope>true</ActivateEnvelope>
        </CreateEnvelopeFromTemplates>
    </soap:Body>
</soap:Envelope>
</code>```

答:
Ergin responded to your primary qs, now for your Bonus qs, DocuSign will still allow you to create an envelope using SOAP API if you are using template which has Payment tabs. I don't see any issue in creating an envelope using SOAP API. I tested it, and I got the payment screen at the time of signing. Please find the SOAP Request to create an envelope with Payment's Template. It uses different operation CreateEnvelopeFromTemplatesAndForms and CompositeTemplate design pattern. You just have to set accountGuid, TemplateGuid and RoleName which is set in a template.</p>

```<code><?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
  <SOAP-ENV:Body>
    <CreateEnvelopeFromTemplatesAndForms xmlns="http://www.docusign.net/API/3.0">
      <ActivateEnvelope>true</ActivateEnvelope>
      <EnvelopeInformation>
        <AccountId>{{accountId}}</AccountId>
        <Subject>Test SOAP Subject</Subject>
        <EmailBlurb>Test SOAP Body</EmailBlurb>
      </EnvelopeInformation>
      <CompositeTemplates>
        <CompositeTemplate>
          <ServerTemplates>
            <ServerTemplate>
              <Sequence>1</Sequence>
              <TemplateID>{{TemplateId}}</TemplateID>
            </ServerTemplate>
          </ServerTemplates>
          <InlineTemplates>
            <InlineTemplate>
              <Sequence>2</Sequence>
              <Envelope>
                <AccountId>{{accountId}}</AccountId>
                <Recipients>
                  <Recipient>
                    <ID>1</ID>
                    <RoleName>Signer1</RoleName>
                    <UserName>Signer 1</UserName>
                    <Email>email@gmail.com</Email>
                    <Type>Signer</Type>
                  </Recipient>
                </Recipients>
              </Envelope>
            </InlineTemplate>
          </InlineTemplates>
        </CompositeTemplate>
      </CompositeTemplates>
    </CreateEnvelopeFromTemplatesAndForms>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

Body:
The SOAP method CreateEnvelopeFromTemplates takes a list of TemplateReference objects which allows me to create a 1-1 mapping of documents in my ECM system to DocuSign Templates. This has worked great up until now and has allowed me to build an envelope creation algorithm without having to know how many documents are involved in a specific use case.

SOAP however does not support the new Payment tabs. In trying to find a REST replacement for this API call I haven't been able to find a way to create an envelope where each document references a different Template. The envelopes: create method for example only allows for one templateID in the envelopeDefinition. Is there a way to port the functionality I've built over to REST?

BONUS QUESTION: Why does the DocuSign backend differentiate between SOAP and REST created envelopes when applying Templates? I didn't expect to be able to programatically create Payment tabs on an envelope with SOAP, but I'm surprised specifying a Template with Payment tabs using SOAP prevents those tabs from working.

This is my SOAP call with non-functional referencing a Template with non-functional Payment tabs:

    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <CreateEnvelopeFromTemplates xmlns="http://www.docusign.net/API/3.0">
            <TemplateReferences>
                <TemplateReference>
                    <TemplateLocation>Server</TemplateLocation>
                    <Template>8E556CD1-D343-4C07-9401-D88B00A67671</Template>
                    <Document>
                        <ID>90267</ID>
                        <Name>DS - Template Mapping - 12/4/2017 John Payme2 (90267)</Name>
                        <PDFBytes>omitted</PDFBytes>
                        <FileExtension>pdf</FileExtension>
                    </Document>
                    <RoleAssignments>
                        <RoleAssignment>
                            <RoleName>Payer</RoleName>
                            <RecipientID>37974046</RecipientID>
                        </RoleAssignment>
                    </RoleAssignments>
                    <Sequence>1</Sequence>
                </TemplateReference>
            </TemplateReferences>
            <Recipients>
                <Recipient>
                    <ID>37974046</ID>
                    <UserName>John Payme2</UserName>
                    <Email>ANDREW.MORTON@HYLAND.COM</Email>
                    <Type>Signer</Type>
                    <AccessCode />
                    <RequireIDLookup>false</RequireIDLookup>
                    <RoutingOrder>1</RoutingOrder>
                    <Note/>
                    <RoleName>Payer</RoleName>
                </Recipient>
            </Recipients>
            <EnvelopeInformation>
                <AccountId>9cace92e-1384-4cf7-9b4c-a2bd70aab9a1</AccountId>
            </EnvelopeInformation>
            <ActivateEnvelope>true</ActivateEnvelope>
        </CreateEnvelopeFromTemplates>
    </soap:Body>
</soap:Envelope>

Body:
Ergin responded to your primary qs, now for your Bonus qs, DocuSign will still allow you to create an envelope using SOAP API if you are using template which has Payment tabs. I don't see any issue in creating an envelope using SOAP API. I tested it, and I got the payment screen at the time of signing. Please find the SOAP Request to create an envelope with Payment's Template. It uses different operation CreateEnvelopeFromTemplatesAndForms and CompositeTemplate design pattern. You just have to set accountGuid, TemplateGuid and RoleName which is set in a template.

<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope">
  <SOAP-ENV:Body>
    <CreateEnvelopeFromTemplatesAndForms xmlns="http://www.docusign.net/API/3.0">
      <ActivateEnvelope>true</ActivateEnvelope>
      <EnvelopeInformation>
        <AccountId>{{accountId}}</AccountId>
        <Subject>Test SOAP Subject</Subject>
        <EmailBlurb>Test SOAP Body</EmailBlurb>
      </EnvelopeInformation>
      <CompositeTemplates>
        <CompositeTemplate>
          <ServerTemplates>
            <ServerTemplate>
              <Sequence>1</Sequence>
              <TemplateID>{{TemplateId}}</TemplateID>
            </ServerTemplate>
          </ServerTemplates>
          <InlineTemplates>
            <InlineTemplate>
              <Sequence>2</Sequence>
              <Envelope>
                <AccountId>{{accountId}}</AccountId>
                <Recipients>
                  <Recipient>
                    <ID>1</ID>
                    <RoleName>Signer1</RoleName>
                    <UserName>Signer 1</UserName>
                    <Email>email@gmail.com</Email>
                    <Type>Signer</Type>
                  </Recipient>
                </Recipients>
              </Envelope>
            </InlineTemplate>
          </InlineTemplates>
        </CompositeTemplate>
      </CompositeTemplates>
    </CreateEnvelopeFromTemplatesAndForms>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>


问:
Can I Debug a NuGet Package?
We have some helper methods that get deployed to NuGet. I have pulled down that repository locally, and pointed my project to use the local NuGet package.

I am trying to debug the NuGet package, should I be able to "Go to Implementation" or somehow get to that code?

A colleague recommended just copying the NuGet project into my solution, but it seems like there should be a way to debug the NuGet code. Or is the source for NuGet packages not available / is pre-compiled? I am a bit lost.

答:
The NuGet package is just a compiled dll that your app references, consider it a convenience rather than downloading and referencing it manually.

You should include the NuGet source as a project in your solution and be able to debug it like any other code you already have (and also be happy that it's available to download while doing so :)

EDIT: As stated in the comments there is another way also which is viable if the symbols are available in the SymbolSource repository which you can use as explained here

In cases in which you don't have access to the source you can use something like ILSpy to decompile the dll.

Title: Can I Debug a NuGet Package?


问:
Prototype.js, calling invoke observe click, trying to get the element clicked. Confusion about scope
Is there a way, using 'invoke', with 'observe', and 'click' as arguments, to access the item that 'invoke' is currently iterating through?

I am doing this:

1.

```<code>$$('.item').invoke('observe', 'click', function(event) {
    // I want to access the .item that was clicked in here
});
</code>```

I can do

2.

```<code>$$('.item').first().observe('click', function(node) {
    // I can access the .item right here with 'node'
})
</code>```

I can even do

3.

```<code>    $$(".item").each(function(node) {
      node.observe('click', function(event) {
        // use 'node' here for the .item clicked
    });
</code>```

But I want to know if there is a way to do #1 (the shorthand way), while still accessing the element that was clicked.

Is there a way to do that?

答:
my funcion good: </p>

```<code>*Event.observe(document, 'click', respondToClick);
function respondToClick(e) {
    var el = e.element();
    var del = el.hasClassName('classIdDiv');
    var id = el.identify();
    if(del == true){
        Function_personal(id);
        return;
    }
}*
</code>```

Body:
Is there a way, using 'invoke', with 'observe', and 'click' as arguments, to access the item that 'invoke' is currently iterating through?

I am doing this:

1.

$$('.item').invoke('observe', 'click', function(event) {
    // I want to access the .item that was clicked in here
});

I can do

2.

$$('.item').first().observe('click', function(node) {
    // I can access the .item right here with 'node'
})

I can even do

3.

    $$(".item").each(function(node) {
      node.observe('click', function(event) {
        // use 'node' here for the .item clicked
    });

But I want to know if there is a way to do #1 (the shorthand way), while still accessing the element that was clicked.

Is there a way to do that?

Body:
my funcion good:

*Event.observe(document, 'click', respondToClick);
function respondToClick(e) {
    var el = e.element();
    var del = el.hasClassName('classIdDiv');
    var id = el.identify();
    if(del == true){
        Function_personal(id);
        return;
    }
}*


问:
Angular 5: How to get Current queryparams [Routing]
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}
</code>```

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.

答:
For Angular5 i would say the best option is using URL tree.
Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a serialized tree. UrlTree is a data structure that provides a lot of affordances in dealing with URLs

Details
https://angular.io/api/router/UrlTree

Body:
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.


问:
Vim: how to limit the left cursor movement to the first non-whitespace character of the line?
Is there a vim setting that restricts the cursor movement only to the leftmost non-whitespace character of the line?

I am writing a plugin that is outputing some information to a buffer. All the text is going to have a lot of whitespace padding on the left, but all the lines will be indented the same. I would like to prevent the user from moving the cursor on this padding area where there is no text.

For example:

```<code>|    Lorem ipsum
|    Lorem ipsum
|    Lorem ipsum
|    Lorem ipsum
</code>```

The '|' represents the vim border, and between the border and the text are whitespaces. The cursor should never be moved on these whitespaces and should stop on the 'L'.

答:
You can force the cursor to the beginning of the line with CursorMoved and :normal!

```<code>augroup BossyMotions
  autocmd!
  autocmd CursorMoved <buffer> if strpart(getline('.'), 0, col('.')) =~ '^\s*$' | execute 'normal! ^' | endif
augroup END
</code>```

For more help see:

```<code>:h :normal
:h :autocmd
:h :autocmd-buflocal
:h :augroup
:h CursorMoved
:h :exe
:h strpart()
</code>```

Body:
Is there a vim setting that restricts the cursor movement only to the leftmost non-whitespace character of the line?

I am writing a plugin that is outputing some information to a buffer. All the text is going to have a lot of whitespace padding on the left, but all the lines will be indented the same. I would like to prevent the user from moving the cursor on this padding area where there is no text.

For example:

|    Lorem ipsum
|    Lorem ipsum
|    Lorem ipsum
|    Lorem ipsum

The '|' represents the vim border, and between the border and the text are whitespaces. The cursor should never be moved on these whitespaces and should stop on the 'L'.

Body:
You can force the cursor to the beginning of the line with CursorMoved and :normal!

augroup BossyMotions
  autocmd!
  autocmd CursorMoved <buffer> if strpart(getline('.'), 0, col('.')) =~ '^\s*$' | execute 'normal! ^' | endif
augroup END

For more help see:

:h :normal
:h :autocmd
:h :autocmd-buflocal
:h :augroup
:h CursorMoved
:h :exe
:h strpart()


问:
non-standard syntax; use '&' to create a pointer to member error when assigning member function to vector

Im trying to add a member function of Player Class to a vector of functions.

This is the vector of functions that require a Keyboard::Key as parameter.

```<code>vector<function<void(Keyboard::Key)>> KeyEvent;
</code>```

Then i have the Players implementation

```<code>Player::Player() {
    KeyEvent.push_back(OnKey); //error: non-standard syntax; use '&' to create a pointer to member
}

void Player::OnKey(Keyboard::Key key) {
    //do something with key...
}
</code>```

I have other instances where something code similair works fine, but not with member functions.

```<code>vector<function<void()>> UpdateEvent;

UpdateEvent.push_back(HandleInputUpdate);

void HandleInputUpdate() {
    for (size_t i = 0; i < pressedKeys.size(); i++) {
        for (size_t e = 0; e < KeyEvent.size(); e++) {
            KeyEvent[e](pressedKeys[i]);
        }
    }
}
</code>```

Is it possible to add an a member function to this vector and if not, how could I create something similair? I am very new to C++ and I created the vector so I could replicate C# Actions. This is how far i have come until I ran into problems. This is an early concept as I still need to add a way to remove functions from the vector.

答: UsePlayer::OnKey, (merely having OnKey or even &OnKkey) is insufficient for the pointer-to-member situation.</p>

Body:
Im trying to add a member function of Player Class to a vector of functions.

This is the vector of functions that require a Keyboard::Key as parameter.

vector<function<void(Keyboard::Key)>> KeyEvent;

Then i have the Players implementation

Player::Player() {
    KeyEvent.push_back(OnKey); //error: non-standard syntax; use '&' to create a pointer to member
}

void Player::OnKey(Keyboard::Key key) {
    //do something with key...
}

I have other instances where something code similair works fine, but not with member functions.

vector<function<void()>> UpdateEvent;

UpdateEvent.push_back(HandleInputUpdate);

void HandleInputUpdate() {
    for (size_t i = 0; i < pressedKeys.size(); i++) {
        for (size_t e = 0; e < KeyEvent.size(); e++) {
            KeyEvent[e](pressedKeys[i]);
        }
    }
}

Is it possible to add an a member function to this vector and if not, how could I create something similair? I am very new to C++ and I created the vector so I could replicate C# Actions. This is how far i have come until I ran into problems. This is an early concept as I still need to add a way to remove functions from the vector.


答:
Is it possible to add an a member function to this vector

No. Non-static member function pointers are quite a bit different than non-member function pointers and static member function pointers.

and if not, how could I create something similair?

Use a lambda expression. In the lambda expression, make sure to capture the this pointer and use it in the function call.

```<code>KeyEvent.push_back([this](Keyboard::Key key) {this->OnKey(key);});
</code>```

Title: non-standard syntax; use '&' to create a pointer to member error when assigning member function to vector

Body:
Is it possible to add an a member function to this vector

No. Non-static member function pointers are quite a bit different than non-member function pointers and static member function pointers.

and if not, how could I create something similair?

Use a lambda expression. In the lambda expression, make sure to capture the this pointer and use it in the function call.

KeyEvent.push_back([this](Keyboard::Key key) {this->OnKey(key);});


问:
Hiding DGV columns according to the data of another column
I have a modified DataGridView (done with VB.NET) which data (from a SQL Server 2012 database) displays well. However, based on the values of the cells in a preexistent column in the dgv, I want to hide the new two columns I created.

I have the following code added in my files, but it give me the "waiting for an identifier". I wanted to select cells to compare:

```<code>        If Me.movtype.ToString != "CRF" Or Me.movtype.ToString != "CRFE" Or Me.movtype.ToString != "CRV" Or
            Me.movtype.ToString != "CRVE" Or Me.movtype.ToString != "VRF" Or Me.movtype.ToString != "VRFE" Or
            Me.movtype.ToString != "VRV" Or Me.movtype.ToString != "VRVE" Or Then

        Me.NewCol1.Visible = False
        Me.NewCol2.Visible = False
End if
</code>```

My idea is, if movtype cells are different to the values posted above, the NewCol1 and NewCol2 must be hidden in the DGV. If these strings are equal, the columns must be visible.

Thanks in advance

答: @LarsTech was correct. I used the wrong operator and I had an error in my code. </p>

Body:
I have a modified DataGridView (done with VB.NET) which data (from a SQL Server 2012 database) displays well. However, based on the values of the cells in a preexistent column in the dgv, I want to hide the new two columns I created.

I have the following code added in my files, but it give me the "waiting for an identifier". I wanted to select cells to compare:

        If Me.movtype.ToString != "CRF" Or Me.movtype.ToString != "CRFE" Or Me.movtype.ToString != "CRV" Or
            Me.movtype.ToString != "CRVE" Or Me.movtype.ToString != "VRF" Or Me.movtype.ToString != "VRFE" Or
            Me.movtype.ToString != "VRV" Or Me.movtype.ToString != "VRVE" Or Then

        Me.NewCol1.Visible = False
        Me.NewCol2.Visible = False
End if

My idea is, if movtype cells are different to the values posted above, the NewCol1 and NewCol2 must be hidden in the DGV. If these strings are equal, the columns must be visible.

Thanks in advance


问:
XmlSerializer - same element with different attribute
I have xml containing:

```<code><day p="d">
<day p="n">
</code>```

What attributes do I need to add to Day class in order to deserialize the xml with XmlSerializer?

答:
```<code>[XmlElement("day")]
public class Day
{
  [XmlAttribute("p")]
  public string P {get;set;}
}
</code>```

OwnerDisplayName: James

LastEditorDisplayName: Kev

ContentLicense: CC BY-SA 4.0

Body:
I have xml containing:

<day p="d">
<day p="n">

What attributes do I need to add to Day class in order to deserialize the xml with XmlSerializer?

OwnerDisplayName: leppie