问:
Why does this work under Microsoft SQL Server Management Studio but not under R?
I received this SQL statement:

use MYDATABASE;
if object_id('tempdb..#mapDT') is not null drop table #mapDT;
create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
insert into #mapDT SELECT 'varchar','type text' UNION ALL SELECT 'datetime','type datetime'UNION ALL SELECT 'tinyint','int64.Type' UNION ALL SELECT 'int','int64.Type' UNION ALL SELECT 'float','type number';
SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
```

<p>and it runs nicely under MS SSMS. The relevant part of the result is:</p>

<pre class="lang-none prettyprint-override"><code>MyString1COLUMN01MyString2type textMyString3
MyString1COLUMN02MyString2type datetimeMyString3
MyString1COLUMN03MyString2type textMyString3
MyString1COLUMN04MyString2type textMyString3
MyString1COLUMN05MyString2int64.TypeMyString3
MyString1COLUMN06MyString2type datetimeMyString3
MyString1COLUMN07MyString2type datetimeMyString3
    ...     ...    ...
</code>```

When I run it under R I must leave out use MYDATABASE; and be sure I am connected at the right database, which is the case. But the SQL-statement is problematic. The output of:

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")
```

is data frame with 0 columns and 0 rows.

Is it the use of "temporal tables" (i.e. #mapDT) the cause of the empty data frame? If so, is there a way to get R and/or Python to understand/use them?

答:
as Gord Thompson knows, the code should include SET NOCOUNT ON;. Thus,

```<code>> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   SET NOCOUNT ON; if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + '},' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")
</code>```

and in my case the row numbers are not wanted, so I also used formals(print.data.frame)$row.names <- FALSE:

```<code>> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> formals(print.data.frame)$row.names <- FALSE
> dbGetQuery(conn, "
+                   SET NOCOUNT ON; if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")
> formals(print.data.frame)$row.names <- TRUE
</code>```

Body:
I received this SQL statement:

use MYDATABASE;
if object_id('tempdb..#mapDT') is not null drop table #mapDT;
create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
insert into #mapDT SELECT 'varchar','type text' UNION ALL SELECT 'datetime','type datetime'UNION ALL SELECT 'tinyint','int64.Type' UNION ALL SELECT 'int','int64.Type' UNION ALL SELECT 'float','type number';
SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';

and it runs nicely under MS SSMS. The relevant part of the result is:

MyString1COLUMN01MyString2type textMyString3
MyString1COLUMN02MyString2type datetimeMyString3
MyString1COLUMN03MyString2type textMyString3
MyString1COLUMN04MyString2type textMyString3
MyString1COLUMN05MyString2int64.TypeMyString3
MyString1COLUMN06MyString2type datetimeMyString3
MyString1COLUMN07MyString2type datetimeMyString3
    ...     ...    ...

When I run it under R I must leave out use MYDATABASE; and be sure I am connected at the right database, which is the case. But the SQL-statement is problematic. The output of:

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")

is data frame with 0 columns and 0 rows.

Is it the use of "temporal tables" (i.e. #mapDT) the cause of the empty data frame? If so, is there a way to get R and/or Python to understand/use them?

Body:
as Gord Thompson knows, the code should include SET NOCOUNT ON;. Thus,

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> dbGetQuery(conn, "
+                   SET NOCOUNT ON; if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + '},' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")

and in my case the row numbers are not wanted, so I also used formals(print.data.frame)$row.names <- FALSE:

> library(odbc)
> conn <- dbConnect(odbc(), Driver = "SQL Server", Server = "MYSERVER\\MYINSTANCE", Database = "MYDATABASE", Trusted_Connection = "True")
> formals(print.data.frame)$row.names <- FALSE
> dbGetQuery(conn, "
+                   SET NOCOUNT ON; if object_id('tempdb..#mapDT') is not null drop table #mapDT; create table #mapDT (SqlDatatype varchar (64), MyNewDataType varchar(64));
+                   insert into #mapDT SELECT 'varchar', 'type text' UNION ALL SELECT 'datetime', 'type datetime' UNION ALL SELECT 'tinyint', 'int64.Type' UNION ALL SELECT 'int', 'int64.Type' UNION ALL SELECT 'float', 'type number';
+                   SELECT COLUMN_NAME, DATA_TYPE, 'MyString1' + COLUMN_NAME + 'MyString2' + m.MyNewDataType + 'MyString3' FROM INFORMATION_SCHEMA.COLUMNS C JOIN #mapDT m on m.SqlDatatype = C.DATA_TYPE WHERE TABLE_NAME = 'MYTABLE';
+                  ")
> formals(print.data.frame)$row.names <- TRUE


来源: stackexchange

问:
How to set background greyscale of multiple line plots in pyopengl?
I have a 2-D numpy array that I have plotted in Pyopengl using Pyqt. Now I want to set The background of the plot greyscale such that when the line moves up or down, its background grey color changes intensity. I am attaching images for the behaviour I want.

but all I am able to create till now is with white background like this

the code that I have written is

```<code>import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys

VS = '''
#version 450

layout(location = 0) in vec2 position;

uniform float right;
uniform float bottom;
uniform float left;
uniform float top;

void main() {
    const float far = 1.0;
    const float near = -1.0;

    mat4 testmat = mat4(
            vec4(2.0 / (right - left), 0, 0, 0),
            vec4(0, 2.0 / (top - bottom), 0, 0),
            vec4(0, 0, -2.0 / (far - near), 0),
            vec4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1)
    );

    gl_Position = testmat * vec4(position.x, position.y, 0., 1.);

}
'''

FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

uniform vec3 triangleColor;
out vec4 outColor;

void main()
{

    outColor = vec4(triangleColor, 1.0);

}

'''

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)

    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

class GLPlotWidget(QGLWidget):

    def __init__(self, *args):
        super(GLPlotWidget, self).__init__()
        self.width, self.height = 100, 100
        self.e = np.load('two.npy', mmap_mode='r')
        self.vbo = glvbo.VBO(self.e)
        self.count = self.vbo.shape[1]
        self.right, self.left, self.top, self.bottom = self.e[0, -1, 0].min(), self.e[0, 0, 0].max(), self.e[0, :,
                                                                                1].max(), self.e[-1,
                                                                                :,
                                                                                1].min()

        # self.data = np.zeros((10, 2))

        self.showMaximized()

    def initializeGL(self):

        vs = compile_vertex_shader(VS)
        fs = compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)

    def ortho_view(self):

        right = gl.glGetUniformLocation(self.shaders_program, "right")
        gl.glUniform1f(right, self.right)

        left = gl.glGetUniformLocation(self.shaders_program, "left")
        gl.glUniform1f(left, self.left)

        top = gl.glGetUniformLocation(self.shaders_program, "top")
        gl.glUniform1f(top, self.top)

        bottom = gl.glGetUniformLocation(self.shaders_program, "bottom")
        gl.glUniform1f(bottom, self.bottom)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glDisable(gl.GL_LINE_STIPPLE)
        gl.glClearColor(1, 1,1, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        self.vbo.bind()
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
        gl.glUseProgram(self.shaders_program)
        self.ortho_view()

        uni_color = gl.glGetUniformLocation(self.shaders_program, "triangleColor")

        for i in range(0, self.vbo.data.shape[0]):
            gl.glUniform3f(uni_color, 0, 0, 0)
            # gl.glLineWidth(1.8)
            gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
        self.vbo.unbind()

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

Can anyone suggest me any method to solve this problem?

file link https://drive.google.com/file/d/1y6w35kuMguR1YczK7yMJpXU86T6qtGSv/view?usp=sharing

edit:- I tried to increase linewidth of points and set color to them but the result is not even close to satisfactory.. and I am unable to understand how to pass color in triangles?

答:
Got it...I have rendered triangles and set color to get the desired result..</p>

```<code>import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys
import copy

VS = '''
#version 450

attribute vec2 position;
attribute vec3 a_Color;

out vec3 g_color;
void main() {

    gl_Position = vec4(position.x, position.y, 0., 1.);
    g_color = a_Color;
}
'''

FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

in vec3 g_color;
out vec4 outColor;

void main()
{

    outColor = vec4(g_color, 1.0);

}

'''

VS1 = '''
#version 450

layout(location = 0) in vec2 position;

void main() {

    gl_Position = vec4(position.x, position.y, 0.0, 1.);

}
'''

FS1 = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

uniform vec3 triangleColor;
out vec4 outColor;

void main()
{

    outColor = vec4(triangleColor, 1.0);

}

'''

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)

    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

class GLPlotWidget(QGLWidget):

    def __init__(self, *args):
        super(GLPlotWidget, self).__init__()
        self.width, self.height = 100, 100
        self.we = np.load('two.npy', mmap_mode='r')
        self.e = copy.deepcopy(self.we[:, :, :])

        self.e[:, :, 1] = np.interp(self.e[:, :, 1], (self.e[:, :, 1].min(), self.e[:, :, 1].max()),
                                                                                (-1, 1))

        self.e[:, :, 0] = np.interp(self.e[:, :, 0], (self.e[:, :, 0].min(), self.e[:, :, 0].max()),
                                                                                (-1, +1))

        self.vbo = glvbo.VBO(self.e)
        self.count = self.vbo.shape[1]

        self.showMaximized()

    def initializeGL(self):

        self.greyscale_data()
        vs = compile_vertex_shader(VS1)
        fs = compile_fragment_shader(FS1)
        self.shaders_program_plot = link_shader_program(vs, fs)

    def greyscale_data(self):
        self.color = np.zeros((self.e.shape[1]*self.e.shape[0], 3), dtype=np.float32)
        for i in range(0, 24):
            a = self.e[i, :, 1].min()
            b = self.e[i, :, 1].max()
            c = np.interp(self.e[i, :, 1], (a, b), (0.15, 0.5))
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 0] = c
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 1] = c
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 2] = c

        self.elems = []
        b = self.e.shape[1]  # number of points per line
        a = self.e.shape[0]  # total number of arms

        for i in range(0, a - 1):
            for j in range(0, b - 1):
                self.elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
                self.elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

        self.elems = np.array(self.elems, dtype=np.int32)
        # print(self.elems[0:100])
        vs = compile_vertex_shader(VS)
        fs = compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)

        self.vertexbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e, gl.GL_DYNAMIC_DRAW)

        self.elementbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.elems, gl.GL_DYNAMIC_DRAW)

        self.colorbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.color, gl.GL_DYNAMIC_DRAW)

    def ortho_view(self, i):

        right = gl.glGetUniformLocation(i, "right")
        gl.glUniform1f(right, self.right)

        left = gl.glGetUniformLocation(i, "left")
        gl.glUniform1f(left, self.left)

        top = gl.glGetUniformLocation(i, "top")
        gl.glUniform1f(top, self.top)

        bottom = gl.glGetUniformLocation(i, "bottom")
        gl.glUniform1f(bottom, self.bottom)

    def greyscale(self):
        gl.glUseProgram(self.shaders_program)

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)

        stride = 0  # 3*self.e.itemsize
        offset = None  # ctypes.c_void_p(0)
        loc = gl.glGetAttribLocation(self.shaders_program, 'position')
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset)

        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)

        loc = gl.glGetAttribLocation(self.shaders_program, 'a_Color')
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)
        gl.glDrawElements(gl.GL_TRIANGLE_STRIP, self.elems.size, gl.GL_UNSIGNED_INT, None)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glClearColor(1, 1, 1, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glEnable(gl.GL_DEPTH_TEST)

        self.vbo.bind()
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
        gl.glUseProgram(self.shaders_program_plot)

        uni_color = gl.glGetUniformLocation(self.shaders_program_plot, "triangleColor")

        for i in range(0, self.vbo.data.shape[0]):
            gl.glUniform3f(uni_color, 0, 0, 0)
            gl.glLineWidth(1)
            gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
        self.vbo.unbind()
        self.greyscale()
        gl.glUseProgram(0)

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a 2-D numpy array that I have plotted in Pyopengl using Pyqt. Now I want to set The background of the plot greyscale such that when the line moves up or down, its background grey color changes intensity. I am attaching images for the behaviour I want.

but all I am able to create till now is with white background like this

the code that I have written is

import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys

VS = '''
#version 450

layout(location = 0) in vec2 position;

uniform float right;
uniform float bottom;
uniform float left;
uniform float top;

void main() {
    const float far = 1.0;
    const float near = -1.0;

    mat4 testmat = mat4(
            vec4(2.0 / (right - left), 0, 0, 0),
            vec4(0, 2.0 / (top - bottom), 0, 0),
            vec4(0, 0, -2.0 / (far - near), 0),
            vec4(-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1)
    );

    gl_Position = testmat * vec4(position.x, position.y, 0., 1.);

}
'''

FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

uniform vec3 triangleColor;
out vec4 outColor;

void main()
{

    outColor = vec4(triangleColor, 1.0);

}

'''

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)

    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

class GLPlotWidget(QGLWidget):

    def __init__(self, *args):
        super(GLPlotWidget, self).__init__()
        self.width, self.height = 100, 100
        self.e = np.load('two.npy', mmap_mode='r')
        self.vbo = glvbo.VBO(self.e)
        self.count = self.vbo.shape[1]
        self.right, self.left, self.top, self.bottom = self.e[0, -1, 0].min(), self.e[0, 0, 0].max(), self.e[0, :,
                                                                                1].max(), self.e[-1,
                                                                                :,
                                                                                1].min()

        # self.data = np.zeros((10, 2))

        self.showMaximized()

    def initializeGL(self):

        vs = compile_vertex_shader(VS)
        fs = compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)

    def ortho_view(self):

        right = gl.glGetUniformLocation(self.shaders_program, "right")
        gl.glUniform1f(right, self.right)

        left = gl.glGetUniformLocation(self.shaders_program, "left")
        gl.glUniform1f(left, self.left)

        top = gl.glGetUniformLocation(self.shaders_program, "top")
        gl.glUniform1f(top, self.top)

        bottom = gl.glGetUniformLocation(self.shaders_program, "bottom")
        gl.glUniform1f(bottom, self.bottom)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glDisable(gl.GL_LINE_STIPPLE)
        gl.glClearColor(1, 1,1, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        self.vbo.bind()
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
        gl.glUseProgram(self.shaders_program)
        self.ortho_view()

        uni_color = gl.glGetUniformLocation(self.shaders_program, "triangleColor")

        for i in range(0, self.vbo.data.shape[0]):
            gl.glUniform3f(uni_color, 0, 0, 0)
            # gl.glLineWidth(1.8)
            gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
        self.vbo.unbind()

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Can anyone suggest me any method to solve this problem?

file link https://drive.google.com/file/d/1y6w35kuMguR1YczK7yMJpXU86T6qtGSv/view?usp=sharing

edit:- I tried to increase linewidth of points and set color to them but the result is not even close to satisfactory.. and I am unable to understand how to pass color in triangles?

Body:
Got it...I have rendered triangles and set color to get the desired result..

import OpenGL.GL as gl
import OpenGL.arrays.vbo as glvbo
from PyQt5.Qt import *
import numpy as np
import sys
import copy

VS = '''
#version 450

attribute vec2 position;
attribute vec3 a_Color;

out vec3 g_color;
void main() {

    gl_Position = vec4(position.x, position.y, 0., 1.);
    g_color = a_Color;
}
'''

FS = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

in vec3 g_color;
out vec4 outColor;

void main()
{

    outColor = vec4(g_color, 1.0);

}

'''

VS1 = '''
#version 450

layout(location = 0) in vec2 position;

void main() {

    gl_Position = vec4(position.x, position.y, 0.0, 1.);

}
'''

FS1 = '''
#version 450
// Output variable of the fragment shader, which is a 4D vector containing the
// RGBA components of the pixel color.

uniform vec3 triangleColor;
out vec4 outColor;

void main()
{

    outColor = vec4(triangleColor, 1.0);

}

'''

def compile_vertex_shader(source):
    """Compile a vertex shader from source."""
    vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertex_shader, source)
    gl.glCompileShader(vertex_shader)
    # check compilation error
    result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(vertex_shader))
    return vertex_shader

def compile_fragment_shader(source):
    """Compile a fragment shader from source."""
    fragment_shader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragment_shader, source)
    gl.glCompileShader(fragment_shader)

    result = gl.glGetShaderiv(fragment_shader, gl.GL_COMPILE_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetShaderInfoLog(fragment_shader))
    return fragment_shader

def link_shader_program(vertex_shader, fragment_shader):
    """Create a shader program with from compiled shaders."""
    program = gl.glCreateProgram()
    gl.glAttachShader(program, vertex_shader)
    gl.glAttachShader(program, fragment_shader)
    gl.glLinkProgram(program)

    result = gl.glGetProgramiv(program, gl.GL_LINK_STATUS)
    if not (result):
        raise RuntimeError(gl.glGetProgramInfoLog(program))
    return program

class GLPlotWidget(QGLWidget):

    def __init__(self, *args):
        super(GLPlotWidget, self).__init__()
        self.width, self.height = 100, 100
        self.we = np.load('two.npy', mmap_mode='r')
        self.e = copy.deepcopy(self.we[:, :, :])

        self.e[:, :, 1] = np.interp(self.e[:, :, 1], (self.e[:, :, 1].min(), self.e[:, :, 1].max()),
                                                                                (-1, 1))

        self.e[:, :, 0] = np.interp(self.e[:, :, 0], (self.e[:, :, 0].min(), self.e[:, :, 0].max()),
                                                                                (-1, +1))

        self.vbo = glvbo.VBO(self.e)
        self.count = self.vbo.shape[1]

        self.showMaximized()

    def initializeGL(self):

        self.greyscale_data()
        vs = compile_vertex_shader(VS1)
        fs = compile_fragment_shader(FS1)
        self.shaders_program_plot = link_shader_program(vs, fs)

    def greyscale_data(self):
        self.color = np.zeros((self.e.shape[1]*self.e.shape[0], 3), dtype=np.float32)
        for i in range(0, 24):
            a = self.e[i, :, 1].min()
            b = self.e[i, :, 1].max()
            c = np.interp(self.e[i, :, 1], (a, b), (0.15, 0.5))
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 0] = c
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 1] = c
            self.color[self.e.shape[1] * i:self.e.shape[1] * (i + 1), 2] = c

        self.elems = []
        b = self.e.shape[1]  # number of points per line
        a = self.e.shape[0]  # total number of arms

        for i in range(0, a - 1):
            for j in range(0, b - 1):
                self.elems += [j + b * i, j + b * i + 1, j + b * (i + 1)]
                self.elems += [j + b * (i + 1), j + b * (i + 1) + 1, j + b * i + 1]

        self.elems = np.array(self.elems, dtype=np.int32)
        # print(self.elems[0:100])
        vs = compile_vertex_shader(VS)
        fs = compile_fragment_shader(FS)
        self.shaders_program = link_shader_program(vs, fs)

        self.vertexbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.e, gl.GL_DYNAMIC_DRAW)

        self.elementbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)
        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, self.elems, gl.GL_DYNAMIC_DRAW)

        self.colorbuffer = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.color, gl.GL_DYNAMIC_DRAW)

    def ortho_view(self, i):

        right = gl.glGetUniformLocation(i, "right")
        gl.glUniform1f(right, self.right)

        left = gl.glGetUniformLocation(i, "left")
        gl.glUniform1f(left, self.left)

        top = gl.glGetUniformLocation(i, "top")
        gl.glUniform1f(top, self.top)

        bottom = gl.glGetUniformLocation(i, "bottom")
        gl.glUniform1f(bottom, self.bottom)

    def greyscale(self):
        gl.glUseProgram(self.shaders_program)

        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertexbuffer)

        stride = 0  # 3*self.e.itemsize
        offset = None  # ctypes.c_void_p(0)
        loc = gl.glGetAttribLocation(self.shaders_program, 'position')
        gl.glEnableVertexAttribArray(loc)
        gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, stride, offset)

        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.elementbuffer)

        loc = gl.glGetAttribLocation(self.shaders_program, 'a_Color')
        gl.glEnableVertexAttribArray(loc)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.colorbuffer)
        gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset)
        gl.glDrawElements(gl.GL_TRIANGLE_STRIP, self.elems.size, gl.GL_UNSIGNED_INT, None)

    def paintGL(self):
        self.resizeGL(self.width, self.height)
        gl.glClearColor(1, 1, 1, 0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glEnable(gl.GL_DEPTH_TEST)

        self.vbo.bind()
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0, None)
        gl.glUseProgram(self.shaders_program_plot)

        uni_color = gl.glGetUniformLocation(self.shaders_program_plot, "triangleColor")

        for i in range(0, self.vbo.data.shape[0]):
            gl.glUniform3f(uni_color, 0, 0, 0)
            gl.glLineWidth(1)
            gl.glDrawArrays(gl.GL_LINE_STRIP, i * self.count, self.count)
        self.vbo.unbind()
        self.greyscale()
        gl.glUseProgram(0)

    def resizeGL(self, width, height):
        self.width, self.height = width, height
        gl.glViewport(0, 0, width, height)

def main():
    app = QApplication(sys.argv)
    editor = GLPlotWidget()
    editor.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


问:
Accessing Honeywell-Box(HICC-P-2100X) IP Camera with c#?
Nowadays I am using Honeywell IP camera for image processing application.But unfortunately I couldn't manage to open it using opencvsharp in c# programming.

So, I would like to share some part of my code and I am using ethernet cable to connect it directly(cable from my notebook to Ip camera).I defined static ip to my laptop and I am able to connect it using default ip configuration via internet explorer.But I am not able to connect and open this camera using c# programming.

I tried all relevant links to make it work as below.Any help would be highly apreciated.

```<code>string v2 = @"http://192.168.0.101:5060/h264";
CvCapture camera = new CvCapture(v2)

string v2 = @"http://admin:admin@192.168.0.101:564/h264";
string v2 = @"rtsp://admin:admin@192.168.0.101:564/h264";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://admin:admin@192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://192.168.0.101:564/img/video.asf";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";
</code>```

All these methods are defined according to related link below(I tried almost all but I couldn be successful
http://www.camera-sdk.com/p_183-how-to-connect-to-your-honeywell-ip-camera-onvif.html``

related image

答:
you can use ONVIF DEVICE MANAGER
then you can find the url of your ip camera
like:
rtsp://192.168.1.188/media?stream=0

ContentLicense: CC BY-SA 3.0

Body:
Nowadays I am using Honeywell IP camera for image processing application.But unfortunately I couldn't manage to open it using opencvsharp in c# programming.

So, I would like to share some part of my code and I am using ethernet cable to connect it directly(cable from my notebook to Ip camera).I defined static ip to my laptop and I am able to connect it using default ip configuration via internet explorer.But I am not able to connect and open this camera using c# programming.

I tried all relevant links to make it work as below.Any help would be highly apreciated.

string v2 = @"http://192.168.0.101:5060/h264";
CvCapture camera = new CvCapture(v2)

string v2 = @"http://admin:admin@192.168.0.101:564/h264";
string v2 = @"rtsp://admin:admin@192.168.0.101:564/h264";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://admin:admin@192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";
string v2 = @"http://192.168.0.101:564/img/video.asf";
string v2 = @"http://192.168.0.101:564/img/video.mjpeg";

All these methods are defined according to related link below(I tried almost all but I couldn be successful
http://www.camera-sdk.com/p_183-how-to-connect-to-your-honeywell-ip-camera-onvif.html``

related image


问:
Splitting strings in Ruby
I want to split a string:

```<code>"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

into two small strings like:

```<code>string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

I tried using arrays but would like to try something new.

答:
You don't need split here.

```<code>sample_string = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
string1, string2 = sample_string[0, 11], sample_string[12..-1]
string1
#=> "00 85 00 04"
string2
#=> "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
</code>```

But it is not clear what "pattern" do you want to use to cut original string.

Title: Splitting strings in Ruby

Body:
I want to split a string:

"00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

into two small strings like:

string1 => "00 85 00 04"
string2 => "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

I tried using arrays but would like to try something new.

Body:
You don't need split here.

sample_string = "00 85 00 04 79 E5 0B B5 82 AE C7 C9 96 37 93 AE"
string1, string2 = sample_string[0, 11], sample_string[12..-1]
string1
#=> "00 85 00 04"
string2
#=> "79 E5 0B B5 82 AE C7 C9 96 37 93 AE"

But it is not clear what "pattern" do you want to use to cut original string.


问:
SwiftUI Textfields inside Lists
I want a list with rows, with each row having 2 Textfields inside of it. Those rows should be saved in an array, so that I can use the data in an other view for further functions. If the text in the Textfield is changed, the text should be saved inside the right entry in the array.
You also can add new rows to the list via a button, which should also change the array for the rows.

The goal is to have a list of key value pairs, each one editable and those entries getting saved with the current text.

Could someone help me and/or give me hint for fixing this problem?

So far I have tried something like this:

```<code>// the array of list entries
@State var list: [KeyValue] = [KeyValue()]
</code>```

```<code>// the List inside of a VStack
List(list) { entry in
    KeyValueRow(list.$key, list.$value)
}
</code>```

```<code>// the single item
struct KeyValue: Identifiable {
    var id = UUID()

    @State var key = ""
    @State var value = ""
}
</code>```

```<code>// one row in the list with view elements
struct KeyValueRow: View {

    var keyBinding: Binding<String>
    var valueBinding: Binding<String>

    init(_ keyBinding: Binding<String>, _ valueBinding: Binding<String>){
        self.keyBinding = keyBinding
        self.valueBinding = valueBinding
    }

    var body: some View {
        HStack() {
            TextField("key", text: keyBinding)
            Spacer()
            TextField("value", text: valueBinding)
            Spacer()
        }
    }
}
</code>```

Also, about the button for adding new entries.
Problem is that if I do the following, my list in the view goes blank and everything is empty again
(maybe related: SwiftUI TextField inside ListView goes blank after filtering list items ?)

```<code>Button("Add", action: {
    self.list.append(KeyValue())
})
</code>```

答:
I am not sure what the best practice is keep a view up to date with state in an array like this, but here is one approach to make it work.

For the models, I added a list class that conforms to Observable object, and each KeyValue item alerts it on changes:

```<code>class KeyValueList: ObservableObject {

    @Published var items = [KeyValue]()

    func update() {
        self.objectWillChange.send()
    }

    func addItem() {
        self.items.append(KeyValue(parent: self))
    }
}
</code>```

```<code>class KeyValue: Identifiable {

    init(parent: KeyValueList) {
        self.parent = parent
    }

    let id = UUID()
    private let parent: KeyValueList

    var key = "" {
        didSet { self.parent.update() }
    }
    var value = "" {
        didSet { self.parent.update() }
    }
}
</code>```

Then I was able to simply the row view to just keep a single piece of state:

```<code>struct KeyValueRow: View {

    @State var item: KeyValue

    var body: some View {
        HStack() {
            TextField("key", text: $item.key)
            Spacer()
            TextField("value", text: $item.value)
            Spacer()
        }
    }
}
</code>```

And for the list view:

```<code>struct TextFieldList: View {

    @ObservedObject var list = KeyValueList()

    var body: some View {

        VStack {
            List(list.items) { item in
                HStack {
                    KeyValueRow(item: item)
                    Text(item.key)
                }
            }
            Button("Add", action: {
                self.list.addItem()
            })

        }
    }
}
</code>```

I just threw an extra Text in there for testing to see it update live.

I did not run into the Add button blanking the view as you described. Does this solve that issue for you as well?

Title: SwiftUI Textfields inside Lists

Body:
I want a list with rows, with each row having 2 Textfields inside of it. Those rows should be saved in an array, so that I can use the data in an other view for further functions. If the text in the Textfield is changed, the text should be saved inside the right entry in the array.
You also can add new rows to the list via a button, which should also change the array for the rows.

The goal is to have a list of key value pairs, each one editable and those entries getting saved with the current text.

Could someone help me and/or give me hint for fixing this problem?

So far I have tried something like this:

// the array of list entries
@State var list: [KeyValue] = [KeyValue()]

// the List inside of a VStack
List(list) { entry in
    KeyValueRow(list.$key, list.$value)
}

// the single item
struct KeyValue: Identifiable {
    var id = UUID()

    @State var key = ""
    @State var value = ""
}

// one row in the list with view elements
struct KeyValueRow: View {

    var keyBinding: Binding<String>
    var valueBinding: Binding<String>

    init(_ keyBinding: Binding<String>, _ valueBinding: Binding<String>){
        self.keyBinding = keyBinding
        self.valueBinding = valueBinding
    }

    var body: some View {
        HStack() {
            TextField("key", text: keyBinding)
            Spacer()
            TextField("value", text: valueBinding)
            Spacer()
        }
    }
}

Also, about the button for adding new entries.
Problem is that if I do the following, my list in the view goes blank and everything is empty again
(maybe related: SwiftUI TextField inside ListView goes blank after filtering list items ?)

Button("Add", action: {
    self.list.append(KeyValue())
})

Body:
I am not sure what the best practice is keep a view up to date with state in an array like this, but here is one approach to make it work.

For the models, I added a list class that conforms to Observable object, and each KeyValue item alerts it on changes:

class KeyValueList: ObservableObject {

    @Published var items = [KeyValue]()

    func update() {
        self.objectWillChange.send()
    }

    func addItem() {
        self.items.append(KeyValue(parent: self))
    }
}

class KeyValue: Identifiable {

    init(parent: KeyValueList) {
        self.parent = parent
    }

    let id = UUID()
    private let parent: KeyValueList

    var key = "" {
        didSet { self.parent.update() }
    }
    var value = "" {
        didSet { self.parent.update() }
    }
}

Then I was able to simply the row view to just keep a single piece of state:

struct KeyValueRow: View {

    @State var item: KeyValue

    var body: some View {
        HStack() {
            TextField("key", text: $item.key)
            Spacer()
            TextField("value", text: $item.value)
            Spacer()
        }
    }
}

And for the list view:

struct TextFieldList: View {

    @ObservedObject var list = KeyValueList()

    var body: some View {

        VStack {
            List(list.items) { item in
                HStack {
                    KeyValueRow(item: item)
                    Text(item.key)
                }
            }
            Button("Add", action: {
                self.list.addItem()
            })

        }
    }
}

I just threw an extra Text in there for testing to see it update live.

I did not run into the Add button blanking the view as you described. Does this solve that issue for you as well?


问:
How do I prevent jQuery from inserting the 'xmlns' attribute in an XML object?
I've been using the new $.parseXML() method with jQuery 1.5.  Whenever I insert a new element into the XML object, that new element automatically gets the 'xmlns' attribute with the value "http://www.w3.org/1999/xhtml".  For example, see the code snippet below:

```<code>var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('three').append($('<five>some value</five>'));
</code>```

The code creates the following element:

```<code><five xmlns="http://www.w3.org/1999/xhtml">some value</five>
</code>```

How do I prevent jQuery from inserting the 'xmlns' attribute?  I've tried using the .removeAttr() method, but not even that seems to work.  Any ideas?

UPDATE:
The suggestion that user nrabinowitz offered was helpful in solving this problem.  Adding an xlmns attribute to the top level element does prevent the xlmns attribute from getting automatically assigned to each new element.  Still, I opted for another solution for my particular program.  I instead used the .replace() method to remove all the xlmns attributes after after I converted the XML object back into a string (to be displayed on a web page).

答:
use this code that work in Chrome also in IE</p>

```<code>var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('three').append($('',$.parseXML('<five>some value</five>')));
</code>```

Body:
I've been using the new $.parseXML() method with jQuery 1.5.  Whenever I insert a new element into the XML object, that new element automatically gets the 'xmlns' attribute with the value "http://www.w3.org/1999/xhtml".  For example, see the code snippet below:

var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('three').append($('<five>some value</five>'));

The code creates the following element:

<five xmlns="http://www.w3.org/1999/xhtml">some value</five>

How do I prevent jQuery from inserting the 'xmlns' attribute?  I've tried using the .removeAttr() method, but not even that seems to work.  Any ideas?

UPDATE:
The suggestion that user nrabinowitz offered was helpful in solving this problem.  Adding an xlmns attribute to the top level element does prevent the xlmns attribute from getting automatically assigned to each new element.  Still, I opted for another solution for my particular program.  I instead used the .replace() method to remove all the xlmns attributes after after I converted the XML object back into a string (to be displayed on a web page).

Body:
use this code that work in Chrome also in IE

var myXml = "<one attr='a'><two attr='b'/><three attr='c'><four attr='d'/></three></one>";
myXml = $.parseXML(myXml);
$(myXml).find('three').append($('',$.parseXML('<five>some value</five>')));


问:
Angular "Http failure during parsing for http://localhost:8000/excel"
I try to send an GET request from Angular to my Laravel backend.

```<code>    Route::get('excel', function () {
    return Excel::download(new PqrsExport, 'products.xlsx');
});
</code>```

I subscribe to this method

```<code>get_excel(){
    this.pqrService.getExcel().subscribe(
      resp => console.log(resp),
      err => console.log(err)
      );
  }
</code>```

And get this

```<code>HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/excel", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:8000/excel"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:8000/excel"
error: {error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "PKVGSPG�D�X�[Content_Types].xml�…heets/_rels/sheet1.xml.relsPK��"}
__proto__: HttpResponseBase
</code>```

答:
I solved it installed FileSaver

```<code>npm i file-saver
</code>```

And use this way

HTML

```<code> <button class="btn btn-success" (click)="get_excel()">Excel</button>
</code>```

TS FILE

```<code>import * as FileSaver from 'file-saver';

 get_excel(){
    return this.http.get('http://localhost:8000/excel',  { responseType: 'blob' })
    .subscribe((resp: any) => {
      FileSaver.saveAs(resp, `filename.xlsx`)
    });
  }
</code>```

Body:
I try to send an GET request from Angular to my Laravel backend.

    Route::get('excel', function () {
    return Excel::download(new PqrsExport, 'products.xlsx');
});

I subscribe to this method

get_excel(){
    this.pqrService.getExcel().subscribe(
      resp => console.log(resp),
      err => console.log(err)
      );
  }

And get this

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8000/excel", ok: false, …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 200
statusText: "OK"
url: "http://localhost:8000/excel"
ok: false
name: "HttpErrorResponse"
message: "Http failure during parsing for http://localhost:8000/excel"
error: {error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "PKVGSPG�D�X�[Content_Types].xml�…heets/_rels/sheet1.xml.relsPK��"}
__proto__: HttpResponseBase

Body:
I solved it installed FileSaver

npm i file-saver

And use this way

HTML

 <button class="btn btn-success" (click)="get_excel()">Excel</button>

TS FILE

import * as FileSaver from 'file-saver';

 get_excel(){
    return this.http.get('http://localhost:8000/excel',  { responseType: 'blob' })
    .subscribe((resp: any) => {
      FileSaver.saveAs(resp, `filename.xlsx`)
    });
  }


问:
PUT request body as application/json instead of plain/text
I'm messing around with react and trying to make a put request to an api. I'm trying to send my body as content-type application/json but it keeps sending as text/plain. If I add the header "Content-Type" : "application/json" I just get this as the return.

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

I'm using this api : http://funtranslations.com/api/yoda

Here is my request:

fetch('http://api.funtranslations.com/translate/yoda.json', {
      method: 'PUT',
      body: JSON.stringify({
        text: this.state.input
      })
    })

      .then(res => {
        return console.log(res.json());
    })
  }

Thank you in advance for attempting to help me :)

答:
I think you are sending data in wrong content-type. According to funtranslation web site content-type should be application/x-www-form-url-encoded

```<code>fetch('http://api.funtranslations.com/translate/yoda.json', {
  method: 'PUT',
  headers: {'Content-Type': 'application/x-www-form-url-encoded', 'Accept': 'application/json'},
  body:"text=hadi"
})
.then(res => {
    return console.log(res.json());
})
</code>```

This address is clearly explaining CORS issue

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

I love this picture to see what is CORS:

Body:
I think you are sending data in wrong content-type. According to funtranslation web site content-type should be application/x-www-form-url-encoded

fetch('http://api.funtranslations.com/translate/yoda.json', {
  method: 'PUT',
  headers: {'Content-Type': 'application/x-www-form-url-encoded', 'Accept': 'application/json'},
  body:"text=hadi"
})
.then(res => {
    return console.log(res.json());
})

This address is clearly explaining CORS issue

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

I love this picture to see what is CORS:


问:
Get aria-expanded value
I didn't find a way to get aria-expanded value from DOM.

```<code><a class="accordion-toggle collapsed" href="#collapse-One" data-parent="#accordion-1" data-toggle="collapse" aria-expanded="false">
    <i class="fa fa-search-plus"></i>
    test
</a>
</code>```

I want to test if it's true then I can change  class to fa-search-minus. I tried this but I always get an undefined value:

```<code>console.log($(this).find('a.aria-expanded').val());
</code>```

答:
In 2020, I could do:

```<code>document.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')
</code>```

to grab the first value and maybe something like:

```<code>Array.from(document.querySelectorAll('[aria-expanded]'))?
  .map(el => el.getAttribute('aria-expanded'))
</code>```

to make an array of all aria-expanded values.

Title: Get aria-expanded value

Body:
I didn't find a way to get aria-expanded value from DOM.

    test

I want to test if it's true then I can change  class to fa-search-minus. I tried this but I always get an undefined value:

console.log($(this).find('a.aria-expanded').val());

Body:
In 2020, I could do:

document.querySelector('[aria-expanded]')?.getAttribute('aria-expanded')

to grab the first value and maybe something like:

Array.from(document.querySelectorAll('[aria-expanded]'))?
  .map(el => el.getAttribute('aria-expanded'))

to make an array of all aria-expanded values.


问:
How to test Angular2's router.navigate?
I've run into missing <router-outlet> messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is logged in for certain actions.

This is the code:

```<code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (!this.authService.isLoggedIn()) {
        this.router.navigate(['/login']);
        return false;
    }
    return true;
}
</code>```

Now I want to write a unit test for this.

This is how I start my test:

```<code>beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule.withRoutes([
                {
                    path: 'login',
                    component: DummyComponent
                }
            ])
        ],
        declarations: [
            DummyComponent
        ],
        providers: [
            AuthGuardService,
            {
                provide: AuthService,
                useClass: MockAuthService
            }
        ]
    });
});
</code>```

I created a DummyComponent that does nothing.
Now my test. Pretend that the service returns false and that it triggers this.router.navigate(['/login']):

```<code>it('should not let users pass when not logged in', (): void => {
    expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});
</code>```

This will throw an exception with "Cannot find primary outlet to load".
Obviously I can use toThrow() instead of toBe(false), but that doesn't seem like a very sensible solution. Since I'm testing a service here, there is no template where I can put the <router-outlet> tag. I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.

答:
```<code>     it(`editTemplate() should navigate to template build module with query params`, inject(
        [Router],
        (router: Router) => {
          let id = 25;
          spyOn(router, "navigate").and.stub();
          router.navigate(["/template-builder"], {
            queryParams: { templateId: id }
          });
          expect(router.navigate).toHaveBeenCalledWith(["/template-builder"], {
            queryParams: { templateId: id }
          });
        }
      ));
</code>```

Title: How to test Angular2's router.navigate?

Body:
I've run into missing <router-outlet> messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is logged in for certain actions.

This is the code:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (!this.authService.isLoggedIn()) {
        this.router.navigate(['/login']);
        return false;
    }
    return true;
}

Now I want to write a unit test for this.

This is how I start my test:

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule.withRoutes([
                {
                    path: 'login',
                    component: DummyComponent
                }
            ])
        ],
        declarations: [
            DummyComponent
        ],
        providers: [
            AuthGuardService,
            {
                provide: AuthService,
                useClass: MockAuthService
            }
        ]
    });
});

I created a DummyComponent that does nothing.
Now my test. Pretend that the service returns false and that it triggers this.router.navigate(['/login']):

it('should not let users pass when not logged in', (): void => {
    expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});

This will throw an exception with "Cannot find primary outlet to load".
Obviously I can use toThrow() instead of toBe(false), but that doesn't seem like a very sensible solution. Since I'm testing a service here, there is no template where I can put the <router-outlet> tag. I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.


问:
How can I show the bit pattern for this type?
For example if I do:

```<code>  let sieve = new Uint32Array(1).fill(1);
</code>```

I would like to look at the bit pattern at index 0 which should be

0000000000000000000000000001

I want to print it out to the console so that I get something like this:

```<code>0 0
1 0
2 0
3 0
.
.
.
31 1
</code>```

Can I simply shift right to grab the 1 using >> or do I have to use a bitwise AND as & as well?

As a side, does it effect things if you switch to a signed representation such as here ...

Int32Array

答:
There is nothing special to do that relates to Uint32Array... You can just deal with sieve[0] as you would with any integer number:

let sieve = new Uint32Array(1).fill(1);

console.log(
    Array.from(sieve[0].toString(2).padStart(32, 0), (bit, i) => `${i} ${bit}`)
         .join("\n")
);```

Body:
For example if I do:

  let sieve = new Uint32Array(1).fill(1);

I would like to look at the bit pattern at index 0 which should be

0000000000000000000000000001

I want to print it out to the console so that I get something like this:

0 0
1 0
2 0
3 0
.
.
.
31 1

Can I simply shift right to grab the 1 using >> or do I have to use a bitwise AND as & as well?

As a side, does it effect things if you switch to a signed representation such as here ...

Int32Array


问:
CruiseControl.rb SVN Access Denied
I'm having a problem where I have been able to add a project to CC.rb perfectly fine but when I start the service I get "Access Denied" messages each time it checks with Subversion for a newer version.

I'm running with --trace and running the exact command it is trying from the project's work directory:

```<code>svn --non-interactive log --limit 1 --revision HEAD:1 --verbose --xml
</code>```

results in a response coming back as expected.

Can anyone point me in the right direction?

Update

Moved onto http as https seems to be the source of a lot of headache but this has not helped.

I've also hacked at the source to get my username and password passed with the above command and that hasn't helped either.

答: Its been a while since I worked with CruiseControl.rb but I do remember that it used common credentials stored on the machine for authentication/access to SVN repositories.  This was nice since they need not be entered each time, but caused a lot of headaches when one of the developers (or some other process) would connect to a SVN repo from that machine using different credentials than what CruiseControl was expecting.  You may what to check to see if this is happening/happened.  I believe this may have been fixed in the latest version or is at least in the queue as a feature/bug fix.</p>

OwnerDisplayName: Garry Shutler

ContentLicense: CC BY-SA 2.5

Title: CruiseControl.rb SVN Access Denied

Body:
I'm having a problem where I have been able to add a project to CC.rb perfectly fine but when I start the service I get "Access Denied" messages each time it checks with Subversion for a newer version.

I'm running with --trace and running the exact command it is trying from the project's work directory:

svn --non-interactive log --limit 1 --revision HEAD:1 --verbose --xml

results in a response coming back as expected.

Can anyone point me in the right direction?

Update

Moved onto http as https seems to be the source of a lot of headache but this has not helped.

I've also hacked at the source to get my username and password passed with the above command and that hasn't helped either.

LastEditorDisplayName: Garry Shutler

OwnerDisplayName: Benjamin Lee


问:
Is there a way to also select the row count from the same following query?
Would I be able to add a rowcount to this same query or would I need to create a separate one?</p>

```<code>SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c
</code>```

答:
Generally, you should avoid running subqueries in SELECT if correlated subqueries is not needed AND you do not have support of window functions, (available in MySQL 8+). Therefore, move subquery to a JOIN as a derived table and to incorporate row counts simply run JOIN INFORMATION_SCHEMA.TABLES:

```<code>SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE,
                t.CONSTRAINT_TYPE, NULL AS DATA_PRECISION,
                NULL AS DATA_SCALE, r.TABLE_ROWS

FROM INFORMATION_SCHEMA.COLUMNS c

INNER JOIN (
   SELECT DISTINCT kcu.TABLE_NAME, kcu.COLUMN_NAME, p.CONSTRAINT_TYPE
   FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
   INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p
       ON p.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
      AND p.CONSTRAINT_TYPE = \'PRIMARY KEY\'
  ) AS t
  ON t.TABLE_NAME = c.TABLE_NAME
  AND t.COLUMN_NAME = c.COLUMN_NAME

INNER JOIN INFORMATION_SCHEMA.TABLES r
  ON r.TABLE_NAME = c.TABLE_NAME
  AND r.TABLE_SCHEMA = c.TABLE_SCHEMA
</code>```

Body:
Would I be able to add a rowcount to this same query or would I need to create a separate one?

SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, \
                ( \
                    SELECT DISTINCT p.CONSTRAINT_TYPE \
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu \
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE=\'PRIMARY KEY\' \
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME \
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE \
                FROM INFORMATION_SCHEMA.COLUMNS c

Body:
Generally, you should avoid running subqueries in SELECT if correlated subqueries is not needed AND you do not have support of window functions, (available in MySQL 8+). Therefore, move subquery to a JOIN as a derived table and to incorporate row counts simply run JOIN INFORMATION_SCHEMA.TABLES:

SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE,
                t.CONSTRAINT_TYPE, NULL AS DATA_PRECISION,
                NULL AS DATA_SCALE, r.TABLE_ROWS

FROM INFORMATION_SCHEMA.COLUMNS c

INNER JOIN (
   SELECT DISTINCT kcu.TABLE_NAME, kcu.COLUMN_NAME, p.CONSTRAINT_TYPE
   FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
   INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p
       ON p.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
      AND p.CONSTRAINT_TYPE = \'PRIMARY KEY\'
  ) AS t
  ON t.TABLE_NAME = c.TABLE_NAME
  AND t.COLUMN_NAME = c.COLUMN_NAME

INNER JOIN INFORMATION_SCHEMA.TABLES r
  ON r.TABLE_NAME = c.TABLE_NAME
  AND r.TABLE_SCHEMA = c.TABLE_SCHEMA


问:
Angular ng2-file-upload Input File Filter not working for PNG in Internet Explorer
I am using the file uploader from ng2-file-upload with filetype restriction.
However everytime i choose a png file with the Internet Explorer 11, it is not added into the queue. All the other allowed filetypes are working.
Here is the code with the file Options:

let uploadOptions: FileUploaderOptions;
if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
  uploadOptions = {
    url: uploadUrl,
    allowedFileType: ['xls', 'xlsx', 'doc', 'docx', 'pdf', 'gif', 'jpg', 'jpeg', 'png', 'odt', 'txt', 'ods'],
    maxFileSize: 10 * 1024 * 1024
  };
} else {
  uploadOptions = {
    url: uploadUrl,
    allowedMimeType: ['application/pdf',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.oasis.opendocument.text',
      'application/vnd.oasis.opendocument.spreadsheet',
      'image/gif',
      'image/jpeg',
      'image/png'
    ],
    maxFileSize: 10 * 1024 * 1024
  };

}

this.uploader = new FileUploader(uploadOptions);
this.uploader.onCompleteAll = () => {
  this.editStateService.documentAdded('player', 'document');
  this.documentListUpdated.emit();
  this.uploader.clearQueue();
};```

Anybody know how to get this working?

答:
After doing a little research I found that older versions IE would return a different set of MIME types for JPEG and PNG image formats. check for the following list:

image/png

image/x-png

image/x-citrix-png

image/x-citrix-jpeg

image/pjpeg

Add to your allowedMimeType list : image/x-png

Body:
I am using the file uploader from ng2-file-upload with filetype restriction.
However everytime i choose a png file with the Internet Explorer 11, it is not added into the queue. All the other allowed filetypes are working.
Here is the code with the file Options:

let uploadOptions: FileUploaderOptions;
if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
  uploadOptions = {
    url: uploadUrl,
    allowedFileType: ['xls', 'xlsx', 'doc', 'docx', 'pdf', 'gif', 'jpg', 'jpeg', 'png', 'odt', 'txt', 'ods'],
    maxFileSize: 10 * 1024 * 1024
  };
} else {
  uploadOptions = {
    url: uploadUrl,
    allowedMimeType: ['application/pdf',
      'application/vnd.ms-excel',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'application/vnd.oasis.opendocument.text',
      'application/vnd.oasis.opendocument.spreadsheet',
      'image/gif',
      'image/jpeg',
      'image/png'
    ],
    maxFileSize: 10 * 1024 * 1024
  };

}

this.uploader = new FileUploader(uploadOptions);
this.uploader.onCompleteAll = () => {
  this.editStateService.documentAdded('player', 'document');
  this.documentListUpdated.emit();
  this.uploader.clearQueue();
};

Anybody know how to get this working?


问:
How to convert ISO 639-1 code to language id
Is there a way to get the primary language id from an language ISO code using the Windows API? I want to use it for my GetDateFormatInt function and I am curious if there is a way without using the constants. Although the function doesn't use the default sublang for english, I'm interested in the primary language id only.</p>

```<code>function GetDateFormatInt(const aLanguageISOCode: string): string;
const
  C_ISO_CODES: array[0..3] of string = (
    'nl', 'en', 'de', 'fr'
  );
  C_LCIDS: array[0..3] of Cardinal = (
    ((SUBLANG_DUTCH shl 10) or LANG_DUTCH) or (SORT_DEFAULT shl 16),
    ((SUBLANG_ENGLISH_UK shl 10) or LANG_ENGLISH) or (SORT_DEFAULT shl 16),
    ((SUBLANG_GERMAN shl 10) or LANG_GERMAN) or (SORT_DEFAULT shl 16),
    ((SUBLANG_FRENCH shl 10) or LANG_FRENCH) or (SORT_DEFAULT shl 16)
  );
var
  i: Integer;
  lLCID: Cardinal;
  lBuffer: array[0..512] of Char;
begin
  i := AnsiIndexText(aLanguageISOCode, C_ISO_CODES);
  if i > -1 then
    lLCID := C_LCIDS[i]
  else
    lLCID := LOCALE_USER_DEFAULT;

  i := GetDateFormat(lLCID, DATE_LONGDATE, nil, nil, lBuffer, 512);
  SetString(Result, lBuffer, i - 1);
end;
</code>```

答:
Disclaimer: I wrote the following solely based on the existence of the LOCALE_SISO639LANGNAME constant. I have no idea if it actually works or is useful in any way. I haven't tested it at all.

```<code>unit Iso639;

interface

uses
  Windows;

function Iso639ToPrimaryLangID(const S: string): LANGID;

implementation

uses
  SysUtils, Classes;

var
  Iso639Languages: TStringList = nil;

function GetLocaleDataW(ID: LCID; Flag: DWORD): WideString;
var
  Buffer: array[0..1023] of WideChar;
begin
  Buffer[0] := #0;
  SetString(Result, Buffer, GetLocaleInfoW(ID, Flag, Buffer, SizeOf(Buffer) div 2));
end;

function LangIDFromLcID(ID: LCID): LANGID;
begin
  Result := LANGID(ID);
end;

function PrimaryLangID(LangID: LANGID): LANGID;
begin
  Result := LangID and $3FF;
end;

procedure InitializeIso639Languages;
var
  I: Integer;
  ALocaleID: LCID;
  ALangID: LANGID;
  S: string;
begin
  Iso639Languages := TStringList.Create;
  try
    Iso639Languages.Sorted := True;
    for I := 0 to Languages.Count - 1 do
    begin
      ALocaleID := Languages.LocaleID[I];
      ALangID := PrimaryLangID(LangIDFromLcID(ALocaleID));
      if Iso639Languages.IndexOfObject(TObject(ALangID)) = -1 then
      begin
        S := GetLocaleDataW(ALocaleID, LOCALE_SISO639LANGNAME);
        Iso639Languages.AddObject(S, TObject(ALangID));
      end;
    end;
  except
    FreeAndNil(Iso639Languages);
    raise;
  end;
end;

function Iso639ToPrimaryLangID(const S: string): LANGID;
var
  I: Integer;
begin
  Result := 0;

  if not Assigned(Iso639Languages) then
    InitializeIso639Languages;

  I := Iso639Languages.IndexOf(S);
  if I <> -1 then
    Result := LANGID(Iso639Languages.Objects[I]);
end;

initialization

finalization
  FreeAndNil(Iso639Languages);

end.
</code>```

Warning for Delphi 7 users:

TLanguages.Create has an issue with DEP and throws an Access Violation when DEP is enabled. So don't use Languages[I].LocaleID and get the LocaleID yourself:

```<code>function EnumLocalesProc(aLocaleString: PChar): Integer; stdcall;
var
  lLocaleID: LCID;
begin
  lLocaleID := StrToInt('$' + Copy(aLocaleString, 5, 4));
  Result := 1;
end;

EnumSystemLocales(@EnumLocalesProc, LCID_SUPPORTED);
</code>```

Body:
Is there a way to get the primary language id from an language ISO code using the Windows API? I want to use it for my GetDateFormatInt function and I am curious if there is a way without using the constants. Although the function doesn't use the default sublang for english, I'm interested in the primary language id only.

function GetDateFormatInt(const aLanguageISOCode: string): string;
const
  C_ISO_CODES: array[0..3] of string = (
    'nl', 'en', 'de', 'fr'
  );
  C_LCIDS: array[0..3] of Cardinal = (
    ((SUBLANG_DUTCH shl 10) or LANG_DUTCH) or (SORT_DEFAULT shl 16),
    ((SUBLANG_ENGLISH_UK shl 10) or LANG_ENGLISH) or (SORT_DEFAULT shl 16),
    ((SUBLANG_GERMAN shl 10) or LANG_GERMAN) or (SORT_DEFAULT shl 16),
    ((SUBLANG_FRENCH shl 10) or LANG_FRENCH) or (SORT_DEFAULT shl 16)
  );
var
  i: Integer;
  lLCID: Cardinal;
  lBuffer: array[0..512] of Char;
begin
  i := AnsiIndexText(aLanguageISOCode, C_ISO_CODES);
  if i > -1 then
    lLCID := C_LCIDS[i]
  else
    lLCID := LOCALE_USER_DEFAULT;

  i := GetDateFormat(lLCID, DATE_LONGDATE, nil, nil, lBuffer, 512);
  SetString(Result, lBuffer, i - 1);
end;

Body:
Disclaimer: I wrote the following solely based on the existence of the LOCALE_SISO639LANGNAME constant. I have no idea if it actually works or is useful in any way. I haven't tested it at all.

unit Iso639;

interface

uses
  Windows;

function Iso639ToPrimaryLangID(const S: string): LANGID;

implementation

uses
  SysUtils, Classes;

var
  Iso639Languages: TStringList = nil;

function GetLocaleDataW(ID: LCID; Flag: DWORD): WideString;
var
  Buffer: array[0..1023] of WideChar;
begin
  Buffer[0] := #0;
  SetString(Result, Buffer, GetLocaleInfoW(ID, Flag, Buffer, SizeOf(Buffer) div 2));
end;

function LangIDFromLcID(ID: LCID): LANGID;
begin
  Result := LANGID(ID);
end;

function PrimaryLangID(LangID: LANGID): LANGID;
begin
  Result := LangID and $3FF;
end;

procedure InitializeIso639Languages;
var
  I: Integer;
  ALocaleID: LCID;
  ALangID: LANGID;
  S: string;
begin
  Iso639Languages := TStringList.Create;
  try
    Iso639Languages.Sorted := True;
    for I := 0 to Languages.Count - 1 do
    begin
      ALocaleID := Languages.LocaleID[I];
      ALangID := PrimaryLangID(LangIDFromLcID(ALocaleID));
      if Iso639Languages.IndexOfObject(TObject(ALangID)) = -1 then
      begin
        S := GetLocaleDataW(ALocaleID, LOCALE_SISO639LANGNAME);
        Iso639Languages.AddObject(S, TObject(ALangID));
      end;
    end;
  except
    FreeAndNil(Iso639Languages);
    raise;
  end;
end;

function Iso639ToPrimaryLangID(const S: string): LANGID;
var
  I: Integer;
begin
  Result := 0;

  if not Assigned(Iso639Languages) then
    InitializeIso639Languages;

  I := Iso639Languages.IndexOf(S);
  if I <> -1 then
    Result := LANGID(Iso639Languages.Objects[I]);
end;

initialization

finalization
  FreeAndNil(Iso639Languages);

end.

Warning for Delphi 7 users:

TLanguages.Create has an issue with DEP and throws an Access Violation when DEP is enabled. So don't use Languages[I].LocaleID and get the LocaleID yourself:

function EnumLocalesProc(aLocaleString: PChar): Integer; stdcall;
var
  lLocaleID: LCID;
begin
  lLocaleID := StrToInt('$' + Copy(aLocaleString, 5, 4));
  Result := 1;
end;

EnumSystemLocales(@EnumLocalesProc, LCID_SUPPORTED);


问:
PARTITION BY row value
I need to partition my output table when a certain row is of a certain value. I have:

```<code>ID|Value|User
-------------
1 |A    |Rick
2 |A    |Rick
3 |B    |Rick
7 |A    |Rick
8 |C    |Rick
4 |A    |Joe
5 |B    |Joe
6 |B    |Joe
</code>```

I need to partition my table for each individual user, and when the value = A, so what I need is:

```<code>Row|ID|Value|User
------------------
1  |1 |A    |Rick
1  |2 |A    |Rick
2  |3 |B    |Rick
1  |7 |A    |Rick
2  |8 |C    |Rick
1  |4 |A    |Joe
2  |5 |B    |Joe
3  |6 |B    |Joe
</code>```

Every value has its own ID.

I've tried things like:

```<code>SELECT ROW_NUMBER() OVER(PARTITION BY User, Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
SELECT ROW_NUMBER() OVER(PARTITION BY User, WHERE Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
etc
</code>```

But I can't seem to figure out how to write it correctly, if it even is possible.

答:
How about this - A is always 1, I wind row back to 1 if an A appears, then I always increment by 1 if it is not A</p>

```<code>With CTE AS (select *, row_number() OVER (order by [user], value) as RN from theTable)

select CASE WHEN C1.Value = 'A' THEN 1 ELSE 1 +  C1.RN - C.RN  END [row] ,  * from
            CTE C1 OUTER APPLY
              (SELECT TOP 1 RN FROM CTE C2
                                WHERE C2.RN < C1.RN AND C2.Value = 'A'
                                ORDER BY C2.RN DESC) C
</code>```

Title: PARTITION BY row value

Body:
I need to partition my output table when a certain row is of a certain value. I have:

ID|Value|User
-------------
1 |A    |Rick
2 |A    |Rick
3 |B    |Rick
7 |A    |Rick
8 |C    |Rick
4 |A    |Joe
5 |B    |Joe
6 |B    |Joe

I need to partition my table for each individual user, and when the value = A, so what I need is:

Row|ID|Value|User
------------------
1  |1 |A    |Rick
1  |2 |A    |Rick
2  |3 |B    |Rick
1  |7 |A    |Rick
2  |8 |C    |Rick
1  |4 |A    |Joe
2  |5 |B    |Joe
3  |6 |B    |Joe

Every value has its own ID.

I've tried things like:

SELECT ROW_NUMBER() OVER(PARTITION BY User, Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
SELECT ROW_NUMBER() OVER(PARTITION BY User, WHERE Value = A ORDER BY ID ASC) AS Row, Value, User FROM...
etc

But I can't seem to figure out how to write it correctly, if it even is possible.

Body:
How about this - A is always 1, I wind row back to 1 if an A appears, then I always increment by 1 if it is not A

With CTE AS (select *, row_number() OVER (order by [user], value) as RN from theTable)

select CASE WHEN C1.Value = 'A' THEN 1 ELSE 1 +  C1.RN - C.RN  END [row] ,  * from
            CTE C1 OUTER APPLY
              (SELECT TOP 1 RN FROM CTE C2
                                WHERE C2.RN < C1.RN AND C2.Value = 'A'
                                ORDER BY C2.RN DESC) C


问:
How would run a bot in PyCharm?
Ok, so I was running my working python script/bot through Terminal using IDLE as a text editor... I realized that PyCharm would be much faster and much more efficient. Though I still do not know a lot about PyCharm. How would I do this?

```<code>from config import keys
from selenium import webdriver
import time

driver = webdriver.Chrome('./chromedriver')

def order(keys):

    driver.get(keys['destination'])

    driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[4]/ul[1]/li[2]').click()
    print('Directed to correct page...')
    driver.switch_to.window(driver.window_handles[1])
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="identifierId"]').send_keys(keys["email"])
    print('Email entered...')
    driver.find_element_by_xpath('//*[@id="identifierNext"]/span/span').click()
    print('Going to next page...')
    time.sleep(2)
    driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys(keys["password"])
    print('Entered password...')
    driver.find_element_by_xpath('//*[@id="passwordNext"]/span/span').click()
    print('Going to next page...')
    time.sleep(2)

if __name__ == '__main__':
    order(keys)

input()
</code>```

That is the code I am using, it works perfectly fine. I just want to use it through PyCharm. Please help!

EDIT: How would I use Selenium through PyCharm? It says that it is an unsolved reference.

EDIT: I got it to work, thank you.

答:
PyCharm won't make your script run faster. It is just an IDE, a tool that allows you to write Python programs. It is not recommended to run it there for production. It is useful to run it there when you are programming and debugging. Use the terminal as usual to run it in production.

What you are probably experiencing is that your PyCharm is pointing to a different Pythonpath. You need to go into PyCharm settings and set your Python interpreter.

You can find out your current Python interpreter through your terminal with the command where python3 (on Windows) or which python3 (on Linux).

Note that python3 may be called python, py or py3 for you.

Title: How would run a bot in PyCharm?

Body:
Ok, so I was running my working python script/bot through Terminal using IDLE as a text editor... I realized that PyCharm would be much faster and much more efficient. Though I still do not know a lot about PyCharm. How would I do this?

from config import keys
from selenium import webdriver
import time

driver = webdriver.Chrome('./chromedriver')

def order(keys):

    driver.get(keys['destination'])

    driver.find_element_by_xpath('/html/body/div[2]/div[1]/div[4]/ul[1]/li[2]').click()
    print('Directed to correct page...')
    driver.switch_to.window(driver.window_handles[1])
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="identifierId"]').send_keys(keys["email"])
    print('Email entered...')
    driver.find_element_by_xpath('//*[@id="identifierNext"]/span/span').click()
    print('Going to next page...')
    time.sleep(2)
    driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys(keys["password"])
    print('Entered password...')
    driver.find_element_by_xpath('//*[@id="passwordNext"]/span/span').click()
    print('Going to next page...')
    time.sleep(2)

if __name__ == '__main__':
    order(keys)

input()

That is the code I am using, it works perfectly fine. I just want to use it through PyCharm. Please help!

EDIT: How would I use Selenium through PyCharm? It says that it is an unsolved reference.

EDIT: I got it to work, thank you.


问:
Checking if two strings are permutations of each other
How to determine if two strings are permutations of each other</p>

答:
Using properties of XOR (Identity, Commutative, and Self-Inverse). Complexity: O(N), programming language C#

```<code>  static bool IsPerm(string word, string targetWord){

    if(word.Length != targetWord.Length){
      return false;
    }

    var xorProduct = 0;
    for(var i = 0; i < word.Length; i++){ // O(N)
      xorProduct ^= word[i] ^ targetWord[i];
    }

    return xorProduct == 0;
  }
</code>```

OwnerDisplayName: Supratim

Body:
Using properties of XOR (Identity, Commutative, and Self-Inverse). Complexity: O(N), programming language C#

  static bool IsPerm(string word, string targetWord){

    if(word.Length != targetWord.Length){
      return false;
    }

    var xorProduct = 0;
    for(var i = 0; i < word.Length; i++){ // O(N)
      xorProduct ^= word[i] ^ targetWord[i];
    }

    return xorProduct == 0;
  }


问:
Make side bars reducing with max-width by degrees
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .container {
            display: grid;
            grid-template-columns: 10% 80% 10%;
            min-height: 100vh;
        }
        .side-right {
            background: red;
        }
        .side-left {
            background: blue;
        }
        .main {
            background: green;
        }
        @media screen and (max-width: 1000px) {
            .container {
                grid-template-columns: 0 100% 0;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="side-right">
    </div>
    <div class="main">
    </div>
    <div class="side-left">
    </div>
</div>
</body>
</html>
</code>```

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?

答:
If I understand your requirement correctly...change the initial grid-template-columns to

```<code>  grid-template-columns: 1fr minmax(1000px, 8fr) 1fr;
</code>```

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

.container {
  display: grid;
  grid-template-columns: 1fr minmax(1000px, 8fr) 1fr;
  min-height: 100vh;
}

.side-right {
  background: red;
}

.side-left {
  background: blue;
}

.main {
  background: green;
}

@media screen and (max-width: 1000px) {
  .container {
    grid-template-columns: 0 1fr 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="side-right">
  </div>
  <div class="main">
  </div>
  <div class="side-left">
  </div>
</div></code>```

Body:
How to make side parts of web page reduce they width with reducing width of whole page by degrees?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

In example below after max-width = 1000px side elements are dissapearing instantly, but I want to make them reducing they width reacting by every pixel changed on max-width. How to make it?

Body:
If I understand your requirement correctly...change the initial grid-template-columns to

  grid-template-columns: 1fr minmax(1000px, 8fr) 1fr;

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

.container {
  display: grid;
  grid-template-columns: 1fr minmax(1000px, 8fr) 1fr;
  min-height: 100vh;
}

.side-right {
  background: red;
}

.side-left {
  background: blue;
}

.main {
  background: green;
}

@media screen and (max-width: 1000px) {
  .container {
    grid-template-columns: 0 1fr 0;
  }
}

<div class="container">
  <div class="side-right">
  </div>
  <div class="main">
  </div>
  <div class="side-left">
  </div>
</div>


问:
Toggle vue-multiselect close/open on button click
When I click on the button, multiselect opens.
But when I click on the button a second time, the true / false values flash and as a result, isOpen remains true.
What am I doing wrong?

template:

```<code><div id="app">
  <button @click="toggle">open and close later
  </button>
    ```{{ isOpen }}```
  <multiselect
    ref="multiselect"
    v-model="value"
    :options="options"
    :multiple="true"
    track-by="library"
    :custom-label="customLabel"
    @close="isOpen = false"
    @open="isOpen = true"
    >
  </multiselect>
</div>
</code>```

js:

```<code>new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    isOpen: false,
    value: { language: 'JavaScript', library: 'Vue-Multiselect' },
    options: [
        {   language: 'JavaScript', library: 'Vue.js' },
      { language: 'JavaScript', library: 'Vue-Multiselect' },
      { language: 'JavaScript', library: 'Vuelidate' }
    ]
    },
  methods: {
    toggle () {
        if (this.isOpen) {
        this.$refs.multiselect.$el.blur();
        this.isOpen = false;
      }
      else {
        this.$refs.multiselect.$el.focus();
        this.isOpen = true;
      }

    }
  }
}).$mount('#app')
</code>```

https://jsfiddle.net/46s5aknt/

答:
The problem here is that VueMultiselect closes when there is a click outside the component.

So when you press the click button (on your mouse) VueMultiselect closes and when you release the click button you are actually reopening VueMultiselect since isOpen was set to false in the close event.

So your button can only be an Open button.

Edit:

The best solution would be to hide the button when the VueMultiselect is open.

Body:
When I click on the button, multiselect opens.
But when I click on the button a second time, the true / false values flash and as a result, isOpen remains true.
What am I doing wrong?

template:

  <button @click="toggle">open and close later
  </button>

{{ isOpen }}

  <multiselect
    ref="multiselect"
    v-model="value"
    :options="options"
    :multiple="true"
    track-by="library"
    :custom-label="customLabel"
    @close="isOpen = false"
    @open="isOpen = true"
    >
  </multiselect>

js:

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    isOpen: false,
    value: { language: 'JavaScript', library: 'Vue-Multiselect' },
    options: [
        {   language: 'JavaScript', library: 'Vue.js' },
      { language: 'JavaScript', library: 'Vue-Multiselect' },
      { language: 'JavaScript', library: 'Vuelidate' }
    ]
    },
  methods: {
    toggle () {
        if (this.isOpen) {
        this.$refs.multiselect.$el.blur();
        this.isOpen = false;
      }
      else {
        this.$refs.multiselect.$el.focus();
        this.isOpen = true;
      }

    }
  }
}).$mount('#app')

https://jsfiddle.net/46s5aknt/


问:
Wordpress - Add comma to all but last item, remove underscore
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

```<code>    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.strtoupper($name).'</a>';
    }
}
?>
</code>```

答:
Try this out:</p>

```<code><?php foreach( get_field('categories') as $category ): ?>
    <a href="/tags/design/<?php echo $category ?>" title="<?php echo ucwords($category) ?>"><?php echo ucwords($category) ?></a>
<?php endforeach; ?>
</code>```

Body:
I'm using the advanced custom field plugin for Wordpress to show the results of checkboxes. I have what I want working, I just want to tidy up the code and add the following:

Remove the underscore from the social media tag (some kind of stripping out???).

If possible I'd like to show a comma after each "tag" but not if it's the last one.

Here's my test page, they're the blue "tags" under the discipline section.

Here's my code:

    <?php
$catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy');

foreach($catNames as $name){
    if(in_array($name, get_field('categories') )){
echo ''.strtoupper($name).'';
    }
}
?>

Body:
Try this out:

<?php foreach( get_field('categories') as $category ): ?>
    <a href="/tags/design/<?php echo $category ?>" title="<?php echo ucwords($category) ?>"><?php echo ucwords($category) ?></a>
<?php endforeach; ?>


问:
Get Max of len(string) in nested dictionary if string can be None
I'm trying to get the max length of a string from a nested dictionary. The field can be a string or None.

When doing this with a list from a nested dictionary, the following works:

max_value = max(dict, key=lambda d: len(dict[d]["list_key"]))

When I run this on the string field, code is:

max_value = max(dict, key=lambda d: len(dict[d]["string_key"]))

because the string can be None, I receive the following error:

TypeError: object of type 'NoneType' has no len()

How can I incorporate is not None into the second function?

答:
If you insist on a single lambda expression, something like:

max_value = max(dict, key=lambda d: len(dict[d]["string_key"]) if dict[d]["string_key"] is not None else 0)

However this starts to look pretty messy. How about

```<code>strs = (dict[d]["string_key"] for d in dict)
maxlen = max(len(s) for s in strs if s is not None)
</code>```

Body:
If you insist on a single lambda expression, something like:

max_value = max(dict, key=lambda d: len(dict[d]["string_key"]) if dict[d]["string_key"] is not None else 0)

However this starts to look pretty messy. How about

strs = (dict[d]["string_key"] for d in dict)
maxlen = max(len(s) for s in strs if s is not None)


答:
```<code>DECLARE @Table AS TABLE
(
    RowNumber   INT
    ,[Value]    CHAR(5)
    ,[User]     VARCHAR(10)
)

INSERT INTO @Table
(
    [Value]
    ,[User]
)
values
 ('A','Rick')
,('A','Rick')
,('B','Rick')
,('C','Rick')
,('A','Joe ')
,('B','Joe ')
,('B','Joe ')

    select
        RowNumber       = DENSE_RANK() OVER(PARTITION BY [User] ORDER BY [Value] ASC)
        ,[User]
        ,[Value]
    from
        @Table
    WHERE
        [Value] = 'A'
UNION ALL
    select
        RowNumber       = ROW_NUMBER() OVER(PARTITION BY [User] ORDER BY [Value] ASC)  + 1
        ,[User]
        ,[Value]
    from
        @Table
    WHERE
        [Value] != 'A'
    Order BY
        [User] DESC
</code>```

Title: PARTITION BY row value


问:
Copy constructor and "Cannot call value of non-function type" error
I have a base class A and three subclasses:

```<code>class A {}
class X : A {}
class Y : A {}
class Z : A {}
</code>```

In my code, I have an instance m which I would like to create a copy of, of the same type.
I can successfully use the following code:

```<code>        let n = type(of: m).init(m)
... and in class A:
        required init(m : A) {
           self.param1 = m.param1
</code>```

I try to simplify things by creating a copy constructor in class A:

```<code>   func copy() {
      return type(of: self).init(self)
   }
</code>```

but this declaration generates the error: Cannot call value of non-function type 'AType'

Two questions: What am I doing wrong? and Is there a simpler way to create a copy constructor involving subclasses?

答:
Try the Prototype desing pattern:

```<code>     public protocol Copying: class {

    init(_ prototype: Self)
}

extension Copying {
    public func copy() -> Self {
        return type(of: self).init(self)
    }
}

public class A: Copying {

    public var value1: Int
    public var value2: Int

    public init(value1: Int, value2: Int) {
        self.value1 = value1
        self.value2 = value2
    }

    public required convenience init(_ a: A) {
        self.init(value1: a.value1, value2: a.value2)
    }
}
</code>```

and you can use it like:

```<code>let a = A(value1: 700, value2: 37)

let aCopy = a.copy()
</code>```

Body:
I have a base class A and three subclasses:

class A {}
class X : A {}
class Y : A {}
class Z : A {}

In my code, I have an instance m which I would like to create a copy of, of the same type.
I can successfully use the following code:

        let n = type(of: m).init(m)
... and in class A:
        required init(m : A) {
           self.param1 = m.param1

I try to simplify things by creating a copy constructor in class A:

   func copy() {
      return type(of: self).init(self)
   }

but this declaration generates the error: Cannot call value of non-function type 'AType'

Two questions: What am I doing wrong? and Is there a simpler way to create a copy constructor involving subclasses?

Body:
Try the Prototype desing pattern:

     public protocol Copying: class {

    init(_ prototype: Self)
}

extension Copying {
    public func copy() -> Self {
        return type(of: self).init(self)
    }
}

public class A: Copying {

    public var value1: Int
    public var value2: Int

    public init(value1: Int, value2: Int) {
        self.value1 = value1
        self.value2 = value2
    }

    public required convenience init(_ a: A) {
        self.init(value1: a.value1, value2: a.value2)
    }
}

and you can use it like:

let a = A(value1: 700, value2: 37)

let aCopy = a.copy()


问:
Deleting an image from android device?
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

```<code>switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }
</code>```

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

```<code>content://com.android.providers.media.documents/document/image%3A5793
</code>```

答:
If you want to delete the image the user selected with ACTION_GET_CONTENT:</p>

```<code>Uri uri = data.getData();

DocumentFile docfile = DocumentFile.fromSingleUri(context, uri);

docfile.delete();
</code>```

Title: Deleting an image from android device?

Body:
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

content://com.android.providers.media.documents/document/image%3A5793

Body:
If you want to delete the image the user selected with ACTION_GET_CONTENT:

Uri uri = data.getData();

DocumentFile docfile = DocumentFile.fromSingleUri(context, uri);

docfile.delete();