问:
WebGL FPS camera movement along the local axis instead of the world axis with glMatrix.js
I'm trying to make a FPS camera in WebGL.
When I move the camera from the initial position and then rotate, the camera moves along the start position instead of the new position.
The translation and rotation are made with glMatrix.js library.

I have the variables:

```<code>var rotateY = 0;  // For rotating along the Y axis
var fronBackMovement = 0;   // Front and back movement
var sideMovement  = 0;  // Movement from side to side
</code>```

Keyboard events:

```<code>// Movement
if( key.w == true ){
    fronBackMovement += 5;
}
if( key.a == true ){
    sideMovement += 5;
}
if( key.s == true ){
    fronBackMovement -= 5;
}
if( key.d == true ){
    sideMovement -= 5;
}
</code>```

Mouse movement:

```<code>// Rotation
if( mouse.movementX != 0 ){
    rotateY += mouse.movementX;  // mouse.movementX is screen movement of the cursor
}
</code>```

Translation and rotation:

```<code>camera.matrix = mat4.fromTranslation( mat4.create() ,vec3.fromValues(sideMovement,0,fronBackMovement) )
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY )
</code>```

答:
The camera generally looks down the -Z axis so to move forward you just add the camera's Z axis to your position. If you don't want to move vertically then zero out the Y component and normalize. Finally multiply by your desired speed.

The camera's x-axis contains the side movement direction so you can do the same for that.

```<code>const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();
...

tempForwardDirection[0] = camera.matrix[8];
tempForwardDirection[1] = 0;  // camera.matrix[9];
tempForwardDirection[2] = camera.matrix[10];
vec3.normalize(tempForwardDirection, tempForwardDirection)

tempSideDirection[0] = camera.matrix[0];
tempSideDirection[1] = camera.matrix[1];
tempSideDirection[2] = camera.matrix[2];

vec3.scaleAndAdd(
    cameraPosition,
    cameraPosition,
    tempForwardDirection,
    -fronBackMovement);
vec3.scaleAndAdd(
    cameraPosition,
    cameraPosition,
    tempSideDirection,
    sideMovement)

camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);
</code>```

let rotateY = 0;  // For rotating along the Y axis
let fronBackMovement = 0;   // Front and back movement
let sideMovement  = 0;  // Movement from side to side

const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();

const camera = {
  matrix: mat4.create(),
};
const mouse = {
  movementX: 0,
};

const gl = document.querySelector("canvas").getContext("webgl");
const vs = `
uniform mat4 u_worldViewProjection;
uniform mat4 u_worldInverseTranspose;

attribute vec4 position;
attribute vec3 normal;

varying vec3 v_normal;

void main() {
  gl_Position = u_worldViewProjection * position;
  v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;
}
`;
const fs = `
precision mediump float;

varying vec3 v_normal;
uniform vec3 u_lightDir;
uniform vec4 u_color;

void main() {
  vec3 norm = normalize(v_normal);
  float light = dot(u_lightDir, norm) * .5 + .5;
  gl_FragColor = vec4(u_color.rgb * light, u_color.a);
}
`;

const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
const bufferInfo = twgl.primitives.createCubeBufferInfo(gl, 1);

const projection = mat4.create();
const view = mat4.create();
const viewProjection = mat4.create();
const world = mat4.create();
const worldViewProjection = mat4.create();
const worldInverse = mat4.create();
const worldInverseTranspose = mat4.create();

const fov = degToRad(90);
const zNear = 0.1;
const zFar = 100;

const lightDir = vec3.normalize(vec3.create(), [1, 2, 3]);

const key = {};

let px = 0;
let py = 0;
let pz = 0;
let elev = 0;
let ang = 0;
let roll = 0;
const speed = 1;
const turnSpeed = 90;

let then = 0;
function render(now) {
  now *= 0.001;  // seconds;
  const deltaTime = now - then;
  then = now;

  twgl.resizeCanvasToDisplaySize(gl.canvas);
  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

  gl.enable(gl.DEPTH_TEST);
  gl.enable(gl.CULL_FACE);

  gl.useProgram(progInfo.program);

  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  mat4.perspective(projection, fov, aspect, zNear, zFar);

  fronBackMovement = 0;
  sideMovement = 0;

  if( key.w == true ){
      fronBackMovement = 5 * deltaTime;
  }
  if( key.a == true ){
      sideMovement = -5 * deltaTime;
  }
  if( key.s == true ){
      fronBackMovement = -5 * deltaTime;
  }
  if( key.d == true ){
      sideMovement = 5 * deltaTime;
  }

  // Rotation
  if( mouse.movementX != 0 ){
      rotateY += mouse.movementX / 200;  // mouse.movementX is screen movement of the cursor
      mouse.movementX = 0;
  }

  tempForwardDirection[0] = camera.matrix[8];
  tempForwardDirection[1] = 0;  // camera.matrix[9];
  tempForwardDirection[2] = camera.matrix[10];
  vec3.normalize(tempForwardDirection, tempForwardDirection)

  tempSideDirection[0] = camera.matrix[0];
  tempSideDirection[1] = camera.matrix[1];
  tempSideDirection[2] = camera.matrix[2];

  vec3.scaleAndAdd(
      cameraPosition,
      cameraPosition,
      tempForwardDirection,
      -fronBackMovement);
  vec3.scaleAndAdd(
      cameraPosition,
      cameraPosition,
      tempSideDirection,
      sideMovement)

  camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
  camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);

  mat4.invert(view, camera.matrix);

  mat4.multiply(viewProjection, projection, view);

  for (let z = -1; z <= 1; ++z) {
    for (let y = -1; y <= 1; ++y) {
      for (let x = -1; x <= 1; ++x) {
        if (x === 0 && y === 0 && z === 0) {
          continue;
        }

        mat4.identity(world);
        mat4.translate(world, world, [x * 3, y * 3, z * 3]);

        mat4.multiply(worldViewProjection, viewProjection, world);
        mat4.invert(worldInverse, world);
        mat4.transpose(worldInverseTranspose, worldInverse);

        twgl.setBuffersAndAttributes(gl, progInfo, bufferInfo);
        twgl.setUniforms(progInfo, {
          u_worldViewProjection: worldViewProjection,
          u_worldInverseTranspose: worldInverseTranspose,
          u_color: [(x + 2) / 3, (y + 2) / 3, (z + 2) / 3, 1],
          u_lightDir: lightDir,
        });
        twgl.drawBufferInfo(gl, bufferInfo);
      }
    }
  }

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

window.addEventListener('keydown', (e) => {
  key[e.key] = true;
  e.preventDefault();
});
window.addEventListener('keyup', (e) => {
  key[e.key] = false;
  e.preventDefault();
});
window.addEventListener('mousemove', (e) => {
  mouse.movementX = e.movementX;
});

function degToRad(d) {
  return d * Math.PI / 180;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
pre { position: absolute; left: 1em; top: 0; }</code>```

<canvas></canvas>
```
A = left
D = right
W = forward
S = down
``````

Body:
I'm trying to make a FPS camera in WebGL.
When I move the camera from the initial position and then rotate, the camera moves along the start position instead of the new position.
The translation and rotation are made with glMatrix.js library.

I have the variables:

var rotateY = 0;  // For rotating along the Y axis
var fronBackMovement = 0;   // Front and back movement
var sideMovement  = 0;  // Movement from side to side

Keyboard events:

// Movement
if( key.w == true ){
    fronBackMovement += 5;
}
if( key.a == true ){
    sideMovement += 5;
}
if( key.s == true ){
    fronBackMovement -= 5;
}
if( key.d == true ){
    sideMovement -= 5;
}

Mouse movement:

// Rotation
if( mouse.movementX != 0 ){
    rotateY += mouse.movementX;  // mouse.movementX is screen movement of the cursor
}

Translation and rotation:

camera.matrix = mat4.fromTranslation( mat4.create() ,vec3.fromValues(sideMovement,0,fronBackMovement) )
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY )

Body:
The camera generally looks down the -Z axis so to move forward you just add the camera's Z axis to your position. If you don't want to move vertically then zero out the Y component and normalize. Finally multiply by your desired speed.

The camera's x-axis contains the side movement direction so you can do the same for that.

const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();
...

tempForwardDirection[0] = camera.matrix[8];
tempForwardDirection[1] = 0;  // camera.matrix[9];
tempForwardDirection[2] = camera.matrix[10];
vec3.normalize(tempForwardDirection, tempForwardDirection)

tempSideDirection[0] = camera.matrix[0];
tempSideDirection[1] = camera.matrix[1];
tempSideDirection[2] = camera.matrix[2];

vec3.scaleAndAdd(
    cameraPosition,
    cameraPosition,
    tempForwardDirection,
    -fronBackMovement);
vec3.scaleAndAdd(
    cameraPosition,
    cameraPosition,
    tempSideDirection,
    sideMovement)

camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);

let rotateY = 0;  // For rotating along the Y axis
let fronBackMovement = 0;   // Front and back movement
let sideMovement  = 0;  // Movement from side to side

const cameraPosition = vec3.create();
const tempForwardDirection = vec3.create();
const tempSideDirection = vec3.create();

const camera = {
  matrix: mat4.create(),
};
const mouse = {
  movementX: 0,
};

const gl = document.querySelector("canvas").getContext("webgl");
const vs = `
uniform mat4 u_worldViewProjection;
uniform mat4 u_worldInverseTranspose;

attribute vec4 position;
attribute vec3 normal;

varying vec3 v_normal;

void main() {
  gl_Position = u_worldViewProjection * position;
  v_normal = (u_worldInverseTranspose * vec4(normal, 0)).xyz;
}
`;
const fs = `
precision mediump float;

varying vec3 v_normal;
uniform vec3 u_lightDir;
uniform vec4 u_color;

void main() {
  vec3 norm = normalize(v_normal);
  float light = dot(u_lightDir, norm) * .5 + .5;
  gl_FragColor = vec4(u_color.rgb * light, u_color.a);
}
`;

const progInfo = twgl.createProgramInfo(gl, [vs, fs]);
const bufferInfo = twgl.primitives.createCubeBufferInfo(gl, 1);

const projection = mat4.create();
const view = mat4.create();
const viewProjection = mat4.create();
const world = mat4.create();
const worldViewProjection = mat4.create();
const worldInverse = mat4.create();
const worldInverseTranspose = mat4.create();

const fov = degToRad(90);
const zNear = 0.1;
const zFar = 100;

const lightDir = vec3.normalize(vec3.create(), [1, 2, 3]);

const key = {};

let px = 0;
let py = 0;
let pz = 0;
let elev = 0;
let ang = 0;
let roll = 0;
const speed = 1;
const turnSpeed = 90;

let then = 0;
function render(now) {
  now *= 0.001;  // seconds;
  const deltaTime = now - then;
  then = now;

  twgl.resizeCanvasToDisplaySize(gl.canvas);
  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

  gl.enable(gl.DEPTH_TEST);
  gl.enable(gl.CULL_FACE);

  gl.useProgram(progInfo.program);

  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  mat4.perspective(projection, fov, aspect, zNear, zFar);

  fronBackMovement = 0;
  sideMovement = 0;

  if( key.w == true ){
      fronBackMovement = 5 * deltaTime;
  }
  if( key.a == true ){
      sideMovement = -5 * deltaTime;
  }
  if( key.s == true ){
      fronBackMovement = -5 * deltaTime;
  }
  if( key.d == true ){
      sideMovement = 5 * deltaTime;
  }

  // Rotation
  if( mouse.movementX != 0 ){
      rotateY += mouse.movementX / 200;  // mouse.movementX is screen movement of the cursor
      mouse.movementX = 0;
  }

  tempForwardDirection[0] = camera.matrix[8];
  tempForwardDirection[1] = 0;  // camera.matrix[9];
  tempForwardDirection[2] = camera.matrix[10];
  vec3.normalize(tempForwardDirection, tempForwardDirection)

  tempSideDirection[0] = camera.matrix[0];
  tempSideDirection[1] = camera.matrix[1];
  tempSideDirection[2] = camera.matrix[2];

  vec3.scaleAndAdd(
      cameraPosition,
      cameraPosition,
      tempForwardDirection,
      -fronBackMovement);
  vec3.scaleAndAdd(
      cameraPosition,
      cameraPosition,
      tempSideDirection,
      sideMovement)

  camera.matrix = mat4.fromTranslation(camera.matrix, cameraPosition);
  camera.matrix = mat4.rotateY(camera.matrix,camera.matrix,rotateY);

  mat4.invert(view, camera.matrix);

  mat4.multiply(viewProjection, projection, view);

  for (let z = -1; z <= 1; ++z) {
    for (let y = -1; y <= 1; ++y) {
      for (let x = -1; x <= 1; ++x) {
        if (x === 0 && y === 0 && z === 0) {
          continue;
        }

        mat4.identity(world);
        mat4.translate(world, world, [x * 3, y * 3, z * 3]);

        mat4.multiply(worldViewProjection, viewProjection, world);
        mat4.invert(worldInverse, world);
        mat4.transpose(worldInverseTranspose, worldInverse);

        twgl.setBuffersAndAttributes(gl, progInfo, bufferInfo);
        twgl.setUniforms(progInfo, {
          u_worldViewProjection: worldViewProjection,
          u_worldInverseTranspose: worldInverseTranspose,
          u_color: [(x + 2) / 3, (y + 2) / 3, (z + 2) / 3, 1],
          u_lightDir: lightDir,
        });
        twgl.drawBufferInfo(gl, bufferInfo);
      }
    }
  }

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

window.addEventListener('keydown', (e) => {
  key[e.key] = true;
  e.preventDefault();
});
window.addEventListener('keyup', (e) => {
  key[e.key] = false;
  e.preventDefault();
});
window.addEventListener('mousemove', (e) => {
  mouse.movementX = e.movementX;
});

function degToRad(d) {
  return d * Math.PI / 180;
}

body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
pre { position: absolute; left: 1em; top: 0; }

<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"></script>
<canvas></canvas>
<pre>
A = left
D = right
W = forward
S = down
</pre>


来源: stackexchange

问:
JS Script for validating dochub pdf
Is it possible to add javascript validations to pdf in dochub. I am not sure how can I integrate js script with dochub. Any help would be appreciated</p>

答: Verified with dochub support, currently it's not possible to add JS</p>

ContentLicense: CC BY-SA 4.0

Title: JS Script for validating dochub pdf


问:
Merge two Git repositories without breaking file history
I need to merge two Git repositories into a brand new, third repository.  I've found many descriptions of how to do this using a subtree merge (for example Jakub Narębski's answer on How do you merge two Git repositories?) and following those instructions mostly works, except that when I commit the subtree merge all of the files from the old repositories are recorded as new added files.  I can see the commit history from the old repositories when I do git log, but if I do git log <file> it shows only one commit for that file - the subtree merge.  Judging from the comments on the above answer, I'm not alone in seeing this problem but I've found no published solutions for it.

Is there any way do merge repositories and leave individual file history intact?

答:
Say you want to merge repository a into b (I'm assuming they're located alongside one another):

```<code>cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a
</code>```

In case you want to put a into a subdirectory do the following before the commands above:

```<code>cd a
git filter-repo --to-subdirectory-filter a
cd ..
</code>```

For this you need git-filter-repo installed (filter-branch is discouraged).

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

More on it here.

ContentLicense: CC BY-SA 3.0

Body:
Say you want to merge repository a into b (I'm assuming they're located alongside one another):

cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a

In case you want to put a into a subdirectory do the following before the commands above:

cd a
git filter-repo --to-subdirectory-filter a
cd ..

For this you need git-filter-repo installed (filter-branch is discouraged).

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

More on it here.


问:
Open Source / Free alternative of Typemock Isolator
Is there any F/OSS alternative of Typemock Isolator .NET?</p>

答:
I have created one - AutoFake. So you can replace whatever you want without a need to pay some money and with an opportunity to have a fast support from the opensource community. Here is a short example of what you can do:</p>
```<code>public class Calendar
{
    public static DateTime Yesterday => DateTime.Now.AddDays(-1);
}

[Fact]
public void Yesterday_SomeDay_ThePrevDay()
{
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.Yesterday);
    sut.Replace(() => DateTime.Now).Return(new DateTime(2016, 8, day: 8));

    Assert.Equal(new DateTime(2016, 8, 7), sut.Execute());
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have created one - AutoFake. So you can replace whatever you want without a need to pay some money and with an opportunity to have a fast support from the opensource community. Here is a short example of what you can do:

public class Calendar
{
    public static DateTime Yesterday => DateTime.Now.AddDays(-1);
}

[Fact]
public void Yesterday_SomeDay_ThePrevDay()
{
    var fake = new Fake<Calendar>();

    var sut = fake.Rewrite(() => Calendar.Yesterday);
    sut.Replace(() => DateTime.Now).Return(new DateTime(2016, 8, day: 8));

    Assert.Equal(new DateTime(2016, 8, 7), sut.Execute());
}


问:
Having a network output as another network parameters
I have y = Y(x;theta) and theta = M(t;omega), where x and t are input variables (given from the dataset), and theta and omega trainable parameters. I need to have theta as function of omega. Then, I have a loss function over y and need to backpropagate the gradient through M up to Y. How can I create such a structure in pytorch?

Currently, my network is built as follows (sizes is a list of integers, defined as sizes = [input_size, hidden1_size, hidden2_size, ..., output_size])

```<code>import torch
import torch.nn as nn
import torch.nn.functional as F

class M(nn.Module):
    def __init__(self, sizes):
        super(Y, self).__init__()
        self.layers = nn.ModuleList()
        for i in range(0, len(sizes) - 1):
            self.layers.append(nn.Linear(sizes[i], sizes[i+1]))

    def forward(self, x):
        for l in self.layers[:-1]:
            x = F.relu(l(x))
        x = self.layers[-1](x)

        return x
</code>```

答:
I think it is quite simple or I didn't get your query correctly.

x, t are your input variables.

Now let us define a network M that will take input t and output theta.

```<code>M = nn.Sequential(....) # declare network here
</code>```

Next, we define a network Y. This here might be tricky as you want to use theta as parameters. It might be easier and intuitive to work with functional counterparts of the modules declared in nn (see https://pytorch.org/docs/stable/nn.functional.html). I will try to give an example of this assuming theta are params of a linear module.

```<code>class Y(nn.Module):
    def __init__(self):
        # declare any modules here

    def forward(self, theta, x):
        return nn.functional.linear(input=x, weight=theta, bias=None)
</code>```

The overall forward pass would be

```<code>def forward(t, x, M, Y):
    theta = M(t)
    output = Y(theta, x)
    return output
</code>```

Body:
I have y = Y(x;theta) and theta = M(t;omega), where x and t are input variables (given from the dataset), and theta and omega trainable parameters. I need to have theta as function of omega. Then, I have a loss function over y and need to backpropagate the gradient through M up to Y. How can I create such a structure in pytorch?

Currently, my network is built as follows (sizes is a list of integers, defined as sizes = [input_size, hidden1_size, hidden2_size, ..., output_size])

import torch
import torch.nn as nn
import torch.nn.functional as F

class M(nn.Module):
    def __init__(self, sizes):
        super(Y, self).__init__()
        self.layers = nn.ModuleList()
        for i in range(0, len(sizes) - 1):
            self.layers.append(nn.Linear(sizes[i], sizes[i+1]))

    def forward(self, x):
        for l in self.layers[:-1]:
            x = F.relu(l(x))
        x = self.layers[-1](x)

        return x

Body:
I think it is quite simple or I didn't get your query correctly.

x, t are your input variables.

Now let us define a network M that will take input t and output theta.

M = nn.Sequential(....) # declare network here

Next, we define a network Y. This here might be tricky as you want to use theta as parameters. It might be easier and intuitive to work with functional counterparts of the modules declared in nn (see https://pytorch.org/docs/stable/nn.functional.html). I will try to give an example of this assuming theta are params of a linear module.

class Y(nn.Module):
    def __init__(self):
        # declare any modules here

    def forward(self, theta, x):
        return nn.functional.linear(input=x, weight=theta, bias=None)

The overall forward pass would be

def forward(t, x, M, Y):
    theta = M(t)
    output = Y(theta, x)
    return output


问:
Materialze Input bottom border-bottom color not changing on focus
I have the following html:

          <form class="col">
            <input type="text" class="input-field"></input>
            Email

              <button className="btn" type="submit">Submit</button>

          </form>

```

<p>and the following css:</p>

<pre class="lang-css prettyprint-override"><code>.input-field input[type=text]:focus {
  border-bottom: 1px solid #4ec632;
  box-shadow: 0 1px 0 0 #4ec632;
}
</code>```

The bottom outline of the input when focused is still the default blue-ish color instead of the green #4ec632. I've tried multiple solutions and referred to the materialize documentation, but nothing has seemed to work thus far. Any ideas on what I should try?

答:
I have modified your CSS selector to make it change the style when the input field is focused. I have also changed the border and shadow width to 10px to make it shown obvious.

For your info, you might want to change the outline instead of the border. Outline only can apply to the whole element and not able to just change the outline bottom.

/*.input-field input[type=text]:focus {*/
input[type=text].input-field:focus {
  border-bottom: 10px solid #4ec632;
  box-shadow: 0 10px 0 0 #4ec632;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="centered">
          <form class="col">
            <input type="text" class="input-field"></input>
            <span class="helper-text">Email</span>
            <div className="button-wrapper">
              <button className="btn" type="submit">Submit</button>
            </div>
          </form>
        </div></code>```

Body:
I have the following html:

          <form class="col">
            <input type="text" class="input-field"></input>
            Email

              <button className="btn" type="submit">Submit</button>

          </form>

and the following css:

.input-field input[type=text]:focus {
  border-bottom: 1px solid #4ec632;
  box-shadow: 0 1px 0 0 #4ec632;
}

The bottom outline of the input when focused is still the default blue-ish color instead of the green #4ec632. I've tried multiple solutions and referred to the materialize documentation, but nothing has seemed to work thus far. Any ideas on what I should try?

Body:
I have modified your CSS selector to make it change the style when the input field is focused. I have also changed the border and shadow width to 10px to make it shown obvious.

For your info, you might want to change the outline instead of the border. Outline only can apply to the whole element and not able to just change the outline bottom.

/*.input-field input[type=text]:focus {*/
input[type=text].input-field:focus {
  border-bottom: 10px solid #4ec632;
  box-shadow: 0 10px 0 0 #4ec632;
}

<div class="centered">
          <form class="col">
            <input type="text" class="input-field"></input>
            <span class="helper-text">Email</span>
            <div className="button-wrapper">
              <button className="btn" type="submit">Submit</button>
            </div>
          </form>
        </div>


问:
How do I change the body background with CSS depending on the screen size, and if a file exists with PHP?
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

```<code> <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />
</code>```

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

```<code> <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />
</code>```

Any help would be appreciated. Thanks in advance :)

答:
Managed to fix it. I think because I had another style sheet linked to the page, I had to put my code after that link so that it overwrote the css file. Here's the code that worked in case it helps anyone (thanks Adam for rewriting it so it's easier to read)</p>

```<code><style>
<?php
$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    $image = "images/bg/$row[project_id].jpg";
} else {
   $image = "images/bg.jpg";
}
?>
@media only screen and (max-width: 767px) {
body {
background: #FFFFFF url('images/bg-mob-380.jpg') repeat-x;
}
}
@media only screen and (min-width: 768px) {
body {
background: #FFFFFF url('<?php echo $image ?>') repeat-x;
}
}
</style>
</code>```

Body:
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

 <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

 <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />

Any help would be appreciated. Thanks in advance :)

Body:
Managed to fix it. I think because I had another style sheet linked to the page, I had to put my code after that link so that it overwrote the css file. Here's the code that worked in case it helps anyone (thanks Adam for rewriting it so it's easier to read)

<style>
<?php
$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    $image = "images/bg/$row[project_id].jpg";
} else {
   $image = "images/bg.jpg";
}
?>
@media only screen and (max-width: 767px) {
body {
background: #FFFFFF url('images/bg-mob-380.jpg') repeat-x;
}
}
@media only screen and (min-width: 768px) {
body {
background: #FFFFFF url('<?php echo $image ?>') repeat-x;
}
}
</style>


问:
How to execute Selenium Chrome WebDriver in silent mode?
When using Chrome Selenium WebDriver, it  will output diagnostic output when the servers are started:

Started ChromeDriver (v2.0) on port 9515

I do not want to see these messages, how can I suppress them?

I do this

```<code>ChromeOptions options = new ChromeOptions();
options.AddArgument("--silent");
IWebDriver Driver = new ChromeDriver(options);
</code>```

But diagnostic output is not suppress.

答:
For anyone finding themselves here wanting a Java solution, there is a thread here:

Selenium chromedriver disable logging or redirect it java

Body:
When using Chrome Selenium WebDriver, it  will output diagnostic output when the servers are started:

Started ChromeDriver (v2.0) on port 9515

I do not want to see these messages, how can I suppress them?

I do this

ChromeOptions options = new ChromeOptions();
options.AddArgument("--silent");
IWebDriver Driver = new ChromeDriver(options);

But diagnostic output is not suppress.


问:
how to print slide number on controlNav in flexslider

I want slide number on each navigation bar bullet points

HTML code

```<code><div id="slideshow">
  <div class="container">
    <div class="flexslider showOnMouseover ">
      <ul class="slides">
        <li> <img src="sliders/images/1.png" alt="" /> <div class="flex-caption"><img src="sliders/images/1-1.png" alt=""></div></li>
        <li> <img src="sliders/images/2.png" alt="" /> <div class="flex-caption"><img src="sliders/images/1-2.png" alt=""></div></li>
      </ul>
    </div>
</code>```

答:
Anyone still looking for the solution to this as I was, it can be solved simply by modifying the style sheet 'flexslider.css'.

The script already gives each nav link a number, but hides the number from view using a text-indent of -9999px.  To get the numbers back, modify the class '.flex-control-paging li a'.  As an example, here's the original:

```<code>.flex-control-paging li a {
  width: 11px;
  height: 11px;
  display: block;
  background: #666;
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
  text-indent: -9999px;
  -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -o-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
}
</code>```

Modify it to:

```<code>.flex-control-paging li a {
  width: 20px;
  height: 20px;
  font-size: 20px;
  display: block;
  background: #ddd;
  cursor: pointer;
}
</code>```

And...

```<code>.flex-control-paging li a:hover {
  background: #333;
  color:#eee;
}
.flex-control-paging li a.flex-active {
  background: #333;
  color:#FFF;
  cursor: default;
}
</code>```

Should give you a good starting point to add your own style to.

Body:
Anyone still looking for the solution to this as I was, it can be solved simply by modifying the style sheet 'flexslider.css'.

The script already gives each nav link a number, but hides the number from view using a text-indent of -9999px.  To get the numbers back, modify the class '.flex-control-paging li a'.  As an example, here's the original:

.flex-control-paging li a {
  width: 11px;
  height: 11px;
  display: block;
  background: #666;
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
  text-indent: -9999px;
  -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -o-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.3);
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;
}

Modify it to:

.flex-control-paging li a {
  width: 20px;
  height: 20px;
  font-size: 20px;
  display: block;
  background: #ddd;
  cursor: pointer;
}

And...

.flex-control-paging li a:hover {
  background: #333;
  color:#eee;
}
.flex-control-paging li a.flex-active {
  background: #333;
  color:#FFF;
  cursor: default;
}

Should give you a good starting point to add your own style to.


问:
How do I call the following?
```<code>    public class MyReportRenderer
    {

        private rs2005.ReportingService2005 rs;
        private rs2005Execution.ReportExecutionService rsExec;
        //string casenumberKey;

        public void RenderTest()
        {
            string HistoryID = null;
            string deviceInfo = null;
            string encoding = String.Empty;
            string mimeType = String.Empty;
            string extension = String.Empty;
            rs2005Execution.Warning[] warnings = null;
            string[] streamIDs = null;

            rs = new rs2005.ReportingService2005();
            rsExec = new rs2005Execution.ReportExecutionService();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rs.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportService2005.asmx";
            rsExec.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";

            //// pass parameters

            try
            {
                // Get if any parameters needed.

                // Load the selected report.

                rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);

                // Prepare report parameter.

                // Set the parameters for the report needed.

                rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[3];
                parameters[0] = new rs2005Execution.ParameterValue();
                parameters[0].Name = "CaseNumberKey";
                parameters[0].Value = "000002";
                //parameters[1] = new rs2005Execution.ParameterValue();
                //parameters[1].Name = "ReportMonth";
                //parameters[1].Value = "6"; // June
                //parameters[2] = new rs2005Execution.ParameterValue();
                //parameters[2].Name = "ReportYear";
                //parameters[2].Value = "2004";
                rsExec.SetExecutionParameters(parameters, "en-us");

                // get pdf of report
                Byte[] results = rsExec.Render("PDF", deviceInfo,
                out extension, out encoding,
                out mimeType, out warnings, out streamIDs);

                MailMessage message = new MailMessage("george.greiner@gmail.com", "george.greiner@gmail.com", "Hello", "This is a test");
                SmtpClient emailClient = new SmtpClient("localhost");
                message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}_DocumentSavingsReport.pdf", "ReportName")));
                emailClient.Send(message);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
    }
</code>```

<p>I would I call this when I need it to be executed?? </p>

Title: How do I call the following?

Body:
    public class MyReportRenderer
    {

        private rs2005.ReportingService2005 rs;
        private rs2005Execution.ReportExecutionService rsExec;
        //string casenumberKey;

        public void RenderTest()
        {
            string HistoryID = null;
            string deviceInfo = null;
            string encoding = String.Empty;
            string mimeType = String.Empty;
            string extension = String.Empty;
            rs2005Execution.Warning[] warnings = null;
            string[] streamIDs = null;

            rs = new rs2005.ReportingService2005();
            rsExec = new rs2005Execution.ReportExecutionService();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rs.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportService2005.asmx";
            rsExec.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";

            //// pass parameters

            try
            {
                // Get if any parameters needed.

                // Load the selected report.

                rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);

                // Prepare report parameter.

                // Set the parameters for the report needed.

                rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[3];
                parameters[0] = new rs2005Execution.ParameterValue();
                parameters[0].Name = "CaseNumberKey";
                parameters[0].Value = "000002";
                //parameters[1] = new rs2005Execution.ParameterValue();
                //parameters[1].Name = "ReportMonth";
                //parameters[1].Value = "6"; // June
                //parameters[2] = new rs2005Execution.ParameterValue();
                //parameters[2].Name = "ReportYear";
                //parameters[2].Value = "2004";
                rsExec.SetExecutionParameters(parameters, "en-us");

                // get pdf of report
                Byte[] results = rsExec.Render("PDF", deviceInfo,
                out extension, out encoding,
                out mimeType, out warnings, out streamIDs);

                MailMessage message = new MailMessage("george.greiner@gmail.com", "george.greiner@gmail.com", "Hello", "This is a test");
                SmtpClient emailClient = new SmtpClient("localhost");
                message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}_DocumentSavingsReport.pdf", "ReportName")));
                emailClient.Send(message);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
    }

I would I call this when I need it to be executed??

Body: (new MyReportRenderer()).RenderTest();


问:
Create Comma Seperated List from MySQL PHP
I have a list of users in my table.  How would I go about taking that list and returning it as one PHP variable with each user name separated by a comma?</p>

答:
The best way I was able to figure this out was by storing the results from each col, or field, and then echoing the implode:

```<code>      $result = mysqli_query($conn, $sql) //store the result
      $cols = array(); //instantiate an array
      while($col = mysqli_fetch_array($result)) {
          $cols[] = $col['username']; //step through results and save each username in array
      }
      echo implode(",",$cols); //turn the array into a comma separated string and echo it
</code>```

This took me a while to figure out exactly how to do this. Hope it helps!

Body:
The best way I was able to figure this out was by storing the results from each col, or field, and then echoing the implode:

      $result = mysqli_query($conn, $sql) //store the result
      $cols = array(); //instantiate an array
      while($col = mysqli_fetch_array($result)) {
          $cols[] = $col['username']; //step through results and save each username in array
      }
      echo implode(",",$cols); //turn the array into a comma separated string and echo it

This took me a while to figure out exactly how to do this. Hope it helps!


问:
android app crashes when uploading to google play
My application worked well when I run it through Android Studio but it crashes when I download it from Google Play store.
It used to work well but suddenly this happened without changing anything
this is the google play crash log:

```<code>      java.lang.NoClassDefFoundError:
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.Support.<clinit> (Support.java)
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.addStatement (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkLocal (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkOpen (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.getSybaseInfo (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.parseBooleanProperty (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.setCollation (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.TdsCore.z (TdsCore.java)
      at net.sourceforge.jtds.jdbc.TdsCore.nextToken (TdsCore.java:4)
      at net.sourceforge.jtds.jdbc.TdsCore.login (TdsCore.java:43)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init> (ConnectionJDBC2.java:16)
      at net.sourceforge.jtds.jdbc.Driver.connect (Driver.java:2)
      at java.sql.DriverManager.getConnection (DriverManager.java:569)
      at java.sql.DriverManager.getConnection (DriverManager.java:219)
      at info.xyz.yourapplication2.ConnectSQL.Run (ConnectSQL.java)
      at info.xyz.yourapplication2.ConnectSQL.connectionclass (ConnectSQL.java)
      at info.xyz.yourapplication2.getproducttype.a (getproducttype.java)
      at info.xyz.yourapplication2.MainActivity.onCreate (MainActivity.java:5)
      at android.app.Activity.performCreate (Activity.java:6942)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1126)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2880)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2988)
      at android.app.ActivityThread.-wrap14 (ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1631)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:154)
      at android.app.ActivityThread.main (ActivityThread.java:6682)
      at java.lang.reflect.Method.invoke (Method.java)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
</code>```

Any idea what may have caused that?

Here is my proguard-rules.pro.

```<code># Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
</code>```

Thank you in advance

答:
It looks like a proguard error to me. Let's add the following in your proguard-rules.pro and check if this fixes the issue.

```<code>-keep class net.sourceforge.jtds.jdbc.**
-keepclassmembers class net.sourceforge.jtds.jdbc.** { *; }
</code>```

Body:
My application worked well when I run it through Android Studio but it crashes when I download it from Google Play store.
It used to work well but suddenly this happened without changing anything
this is the google play crash log:

      java.lang.NoClassDefFoundError:
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.Support.<clinit> (Support.java)
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.addStatement (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkLocal (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkOpen (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.getSybaseInfo (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.parseBooleanProperty (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.setCollation (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.TdsCore.z (TdsCore.java)
      at net.sourceforge.jtds.jdbc.TdsCore.nextToken (TdsCore.java:4)
      at net.sourceforge.jtds.jdbc.TdsCore.login (TdsCore.java:43)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init> (ConnectionJDBC2.java:16)
      at net.sourceforge.jtds.jdbc.Driver.connect (Driver.java:2)
      at java.sql.DriverManager.getConnection (DriverManager.java:569)
      at java.sql.DriverManager.getConnection (DriverManager.java:219)
      at info.xyz.yourapplication2.ConnectSQL.Run (ConnectSQL.java)
      at info.xyz.yourapplication2.ConnectSQL.connectionclass (ConnectSQL.java)
      at info.xyz.yourapplication2.getproducttype.a (getproducttype.java)
      at info.xyz.yourapplication2.MainActivity.onCreate (MainActivity.java:5)
      at android.app.Activity.performCreate (Activity.java:6942)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1126)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2880)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2988)
      at android.app.ActivityThread.-wrap14 (ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1631)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:154)
      at android.app.ActivityThread.main (ActivityThread.java:6682)
      at java.lang.reflect.Method.invoke (Method.java)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

Any idea what may have caused that?

Here is my proguard-rules.pro.

# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

Thank you in advance

Body:
It looks like a proguard error to me. Let's add the following in your proguard-rules.pro and check if this fixes the issue.

-keep class net.sourceforge.jtds.jdbc.**
-keepclassmembers class net.sourceforge.jtds.jdbc.** { *; }


问:
SSO implementation for GAE web application
I am trying to integrate the single sign on for my application running on Google app engine platform.
I am using SAML 2.0 protocol to get this done. My organization already have the identity provider using LDAP, which configured in such a format (https://sso-companyname/appname). For this configuration, its took following details

XML metadata for their assertion consumer service (ACS) (https://www.google/companyname/a/acs),

a list of the LDAP attributes to be sent (email),

which attribute is to be used as the subject of the assertion (company enterprise id),

the RelayState URL at the relying party site to send the user after the SAML Response assertion has been validated, (application target URL form GAE deployment. like (https://appname-dot-projectid.appspot.com)

a short name (less than 7 characters) of the application to be used in the URL, (given as app name)

According to this configuration, the ACS is not for a particular GAE application, so I am getting 400 error from the google server.

Can some one help me on how to create ACS for a single GAE application and would able to explain the SSO for GAE web application would be grateful.

The web application using Python jinja2 frame-work for the UI, webapp2 for the routing. It will call the google-big-query to populate the data to UI, currently, it is using Python standard environment of GAE, and OAuth 2 method to authenticate and call the big-query API to get data. So some people don't have the GCP/Project access, doesn't able to view the data. to resolve this we trying to implement SSO on top of the application.

答: I think the easiest way to integrate GAE with SSO/SAML is to use Google Identity Platform (GIP) which uses Firebase under the hood.  This lets you use the firebase-admin Python package to easily interact with JWTs, and lets you use the GIP console to set up an SAML server.


问:
Will Django UUIDFIeld unique=True, blank=True and null=True behave correctly?
I am adding a field to a database:

identifier = models.UUIDField(unique=True, null=True, blank=True)

but I am curious if this will behave like a CharField or a number field when someone saves an instance in the admin without a value. Will it try to save the value as an empty string "" or will it be smart and save it as null? I am using Postgres for the database. I've seen other answers for CharField, but nothing that speaks to UUIDField.

My end goal is to have a field that is guaranteed to be unique, and will default to null. would it be more appropriate to write it as:

identifier = models.UUIDField(unique=True, null=True, default=None) or will the admin form validation complain if no value is provided?

答:
The Django documentation doesn't specify how UUIDField handles null values.

However, a look at the source code shows that it's not a subset of CharField, and that it has explicit support for handling null values.

So it appears that the field will indeed store None values as NULL, and since such values are always unique on PostgreSQL your approach should work on that database.


问:
I'm attempting to render an array as a series of links
I'm trying to do this in a view file:

```<code><td><%= obj.user_ids.values.each {|user_id| link_to results_path(user_id)} %></td>
</code>```

But it is displayed as the unchanged array.  Why is this?

答:
Try this:</p>

```<code><td>
  <% obj.user_ids.values.each do |user_id| -%>
    <%= link_to results_path(user_id) %>
  <% end -%>
</td>
</code>```

Body:
I'm trying to do this in a view file:

<%= obj.user_ids.values.each {|user_id| link_to results_path(user_id)} %>

But it is displayed as the unchanged array.  Why is this?

Body:
Try this:

<td>
  <% obj.user_ids.values.each do |user_id| -%>
    <%= link_to results_path(user_id) %>
  <% end -%>
</td>


问:
replacing \n with new line
I have a string consisting of text that can contain multiple \ and n.

In php, with preg_replace, I want to replace \n with [NewLine] ONLY where needed. By saying replacing \n i mean replacing the characters backslash-n (\ and n).

I browsed similar questions but didn't find one to handle the case of \\n which should not be replaced with new line.

For example, the string hello\nworld should be hello[NewLine]world,

and the string hello\\nworld should be hello\nworld.

Meaning :

<?php
$source1 = <<<'EOD'
\n
EOD;

$source2 = <<<'EOD'
\\n
EOD;

$source3 = <<<'EOD'
\\\n
EOD;
//$source4 with 4 backslaskes , 5 with 5 etc.

//preg_replace `$source1` so it ends up as `[NewLine]`
//preg_replace `$source2` to `\\n`
//preg_replace `$source3` to `\\[NewLine]`
//etc
//....
//even number of consecutive \ followed by n means no [NewLine]
//odd number of consecutive \ followed by n means new [NewLine]
```

<p>I had a wrong replacement code</p>

<pre class="lang-php prettyprint-override"><code>$a = preg_replace('{([^{\\\}])\\\n}', "$1\n", $string);
//work as expected when $string is "first-line\\nsecond-line";
//doesn't work as expected when $string is "first-line\\\nsecond-line";
</code>```

Anyone knows what needs to be done in a regular expression to have this working ?

Title: replacing \n with new line

Body:
I have a string consisting of text that can contain multiple \ and n.

In php, with preg_replace, I want to replace \n with [NewLine] ONLY where needed. By saying replacing \n i mean replacing the characters backslash-n (\ and n).

I browsed similar questions but didn't find one to handle the case of \\n which should not be replaced with new line.

For example, the string hello\nworld should be hello[NewLine]world,

and the string hello\\nworld should be hello\nworld.

Meaning :

<?php
$source1 = <<<'EOD'
\n
EOD;

$source2 = <<<'EOD'
\\n
EOD;

$source3 = <<<'EOD'
\\\n
EOD;
//$source4 with 4 backslaskes , 5 with 5 etc.

//preg_replace `$source1` so it ends up as `[NewLine]`
//preg_replace `$source2` to `\\n`
//preg_replace `$source3` to `\\[NewLine]`
//etc
//....
//even number of consecutive \ followed by n means no [NewLine]
//odd number of consecutive \ followed by n means new [NewLine]

I had a wrong replacement code

$a = preg_replace('{([^{\\\}])\\\n}', "$1\n", $string);
//work as expected when $string is "first-line\\nsecond-line";
//doesn't work as expected when $string is "first-line\\\nsecond-line";

Anyone knows what needs to be done in a regular expression to have this working ?

Body:
Found a easier solution. Like knittl said, pair matching \ was the key, and regxp no really needed.

strtr($input, ['\\\\' => '\\','\\n' => "[NL]"]);

Tested at https://3v4l.org/5tebZ

$um = [
        '\\\\' => '\\',
        '\\n' => "[NL]",
    ];

$inputs = [];
for ($i=1;$i<=14;$i++) {
   $inputs[] = ''.str_repeat("\\", $i)."n";
}

foreach ($inputs as $input) {
    $results[] = strtr($input, $um);
}

foreach ($inputs as $key=>$value)
{
    echo str_pad($value, 15, ' ',STR_PAD_LEFT)." =======> ".$results[$key]."\n";
}

Output

             \n =======> [NL]
            \\n =======> \n
           \\\n =======> \[NL]
          \\\\n =======> \\n
         \\\\\n =======> \\[NL]
        \\\\\\n =======> \\\n
       \\\\\\\n =======> \\\[NL]
      \\\\\\\\n =======> \\\\n
     \\\\\\\\\n =======> \\\\[NL]
    \\\\\\\\\\n =======> \\\\\n
   \\\\\\\\\\\n =======> \\\\\[NL]
  \\\\\\\\\\\\n =======> \\\\\\n
 \\\\\\\\\\\\\n =======> \\\\\\[NL]
\\\\\\\\\\\\\\n =======> \\\\\\\n


问:
flask+react website using App Engine, url not found
A simple flask+ react website that i have deployed to App Engine works fine locally.
When I serve main.py locally and go to /hello it returns "hello world" as it should. However when deployed to app engine and using the provided URL with /hello it returns "The requested URL /hello was not found on this server."

below is main.py

```<code>from flask import Flask, render_template
app = Flask(__name__, static_folder="./build/static", template_folder="./build")
 @app.route("/")
 def index():
     return render_template("index.html")
@app.route("/hello")
def hello():
    return "Hello World!"
if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8080, debug=True)

</code>```

here's my app.yaml

```<code>runtime: python37
entrypoint: gunicorn -b :$PORT main:app

handlers:
- url: /
  static_files: build/index.html
  upload: build/index.html
- url: /
  static_dir: build
- url: /(.*)
  script: auto
</code>```

```<code>project_root/
build/
   static/
   index.html
app.yaml
main.py
</code>```

It also returns index.html fine on app engine when entering [provided-url].com/

答:
Your url handlers in app.yaml are short-circuiting.  The first / matches, and it never gets to the 2nd / handler.  I think you want something like:

```<code>handlers:
- url: /static
  static_dir: build/static/
- url: /(.*)
  script: auto
</code>```

then let your Flask handlers do all the work.  Then, send all your calls to static files to /static/somefile.jpg etc.

EDIT: If you want to make your life easier, don't serve index.html as a static file.  Serve it from main.py, as you have that set up.  All of your React urls get handled in main.py, and all separately render index.html.  All of your React routing and components get called from inside index.html. Your API calls get handled in main.py as well.

```<code>@app.route("/")
def index():
    template_context = {
        'msg'      : "you are on my home page",
    }
    return render_template("index.html", **template_context)

@app.route("/profile")
def profile():
    template_context = {
        'msg'      : "this is your user profile",
    }
    return render_template("index.html", **template_context)

@app.route("/hello")
def hello():
    return "Hello World!"
</code>```

EDIT #2: If you insist on serving index.html as a static file, you could set up your app.yaml like this:

```<code>handlers:
- url: /
  static_files: build/index.html
  upload: build/index.html
- url: /static
  static_dir: build/static/
- url: /(.*)
  script: auto
</code>```

and you would delete the @app.route("/") handler from main.py, as it will never get there.

Body:
A simple flask+ react website that i have deployed to App Engine works fine locally.
When I serve main.py locally and go to /hello it returns "hello world" as it should. However when deployed to app engine and using the provided URL with /hello it returns "The requested URL /hello was not found on this server."

below is main.py

from flask import Flask, render_template
app = Flask(__name__, static_folder="./build/static", template_folder="./build")
 @app.route("/")
 def index():
     return render_template("index.html")
@app.route("/hello")
def hello():
    return "Hello World!"
if __name__ == "__main__":
    app.run(host='127.0.0.1', port=8080, debug=True)

here's my app.yaml

runtime: python37
entrypoint: gunicorn -b :$PORT main:app

handlers:
- url: /
  static_files: build/index.html
  upload: build/index.html
- url: /
  static_dir: build
- url: /(.*)
  script: auto

project_root/
build/
   static/
   index.html
app.yaml
main.py

It also returns index.html fine on app engine when entering [provided-url].com/

Body:
Your url handlers in app.yaml are short-circuiting.  The first / matches, and it never gets to the 2nd / handler.  I think you want something like:

handlers:
- url: /static
  static_dir: build/static/
- url: /(.*)
  script: auto

then let your Flask handlers do all the work.  Then, send all your calls to static files to /static/somefile.jpg etc.

EDIT: If you want to make your life easier, don't serve index.html as a static file.  Serve it from main.py, as you have that set up.  All of your React urls get handled in main.py, and all separately render index.html.  All of your React routing and components get called from inside index.html. Your API calls get handled in main.py as well.

@app.route("/")
def index():
    template_context = {
        'msg'      : "you are on my home page",
    }
    return render_template("index.html", **template_context)

@app.route("/profile")
def profile():
    template_context = {
        'msg'      : "this is your user profile",
    }
    return render_template("index.html", **template_context)

@app.route("/hello")
def hello():
    return "Hello World!"

EDIT #2: If you insist on serving index.html as a static file, you could set up your app.yaml like this:

handlers:
- url: /
  static_files: build/index.html
  upload: build/index.html
- url: /static
  static_dir: build/static/
- url: /(.*)
  script: auto

and you would delete the @app.route("/") handler from main.py, as it will never get there.


问:
Adding drop-down menu to chrome extension icon
I know that I can associate a popup.html to clicks on the extension button. However, I want it to be a menu, like the one popping up after clicking on Chrome's own "Customize and control Google Chrome" button (located to the right of your extension icons). I tried to Google it but no one seemed to be talking about that. Am I missing any common sense about Chrome extension development?

答:
A practical example, since the documentation isn't actually that clarifying:

manifest.js

```<code>{
  "name": "Foo menu",
  "description": "Demonstrating context menus on browser actions",
  "manifest_version": 2,
  "version": "1.0",
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_title": "Click me"
  },
  "icons": {
    "16": "icon.png",
  },
  "permissions": ["contextMenus"]
}
</code>```

background.js

```<code>chrome.contextMenus.removeAll();
chrome.contextMenus.create({
  id: "FOO_ACTION",
  title: "Foo",
  contexts: ["browser_action"],
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "FOO_ACTION") {
    // Execute foo using tab id
    foo(tab.id);
  }
});

const foo = (tabId) => { console.log(`Foo called on tab with id ${tabId}`) };
</code>```

Body:
A practical example, since the documentation isn't actually that clarifying:

manifest.js

{
  "name": "Foo menu",
  "description": "Demonstrating context menus on browser actions",
  "manifest_version": 2,
  "version": "1.0",
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_title": "Click me"
  },
  "icons": {
    "16": "icon.png",
  },
  "permissions": ["contextMenus"]
}

background.js

chrome.contextMenus.removeAll();
chrome.contextMenus.create({
  id: "FOO_ACTION",
  title: "Foo",
  contexts: ["browser_action"],
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === "FOO_ACTION") {
    // Execute foo using tab id
    foo(tab.id);
  }
});

const foo = (tabId) => { console.log(`Foo called on tab with id ${tabId}`) };


答:
If you're asking how to invoke the method RenderTest on the class MyReportRenderer, you'd need to instantiate an instance of MyReportRenderer and then call that method from the instantiated object:

```<code>namespace ReportProgram
{
  class Program
  {
    static void Main(string [] args)
    {
      var rr = new MyReportRenderer();
      rr.RenderTest();
    }
  }
}
</code>```

Title: How do I call the following?

Body:
If you're asking how to invoke the method RenderTest on the class MyReportRenderer, you'd need to instantiate an instance of MyReportRenderer and then call that method from the instantiated object:

namespace ReportProgram
{
  class Program
  {
    static void Main(string [] args)
    {
      var rr = new MyReportRenderer();
      rr.RenderTest();
    }
  }
}


问:
Delete last 3 characters if they are equal to something
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

```<code>Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub
</code>```

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

答:
Try,</p>

```<code>Sub test()
    Dim rngDB As Range, rng As Range
    Dim i As Integer, x As Integer
    Dim vWhat As Variant, vReplace As Variant
    Dim s As String

    Set rngDB = Selection
    vWhat = Array("abc", ", ,", ", (", ", [", ", -")
    vReplace = Array("", ",", " (", " [", " -")

    For Each rng In rngDB
        x = Len(rng) - 2
        s = rng
        If x > 0 Then
            For i = 0 To UBound(vWhat)
                If Mid(s, x, 3) = vWhat(i) Then
                    rng.Characters(x, 3).Text = vReplace(i)
                End If
            Next i
        End If
    Next rng

End Sub
</code>```

Body:
(without affecting the char level formatting in the cell)

I've already posted a similar question, but I unfortunately I realized I couldn't use any of the solutions because all of them removed all the formatting in the cells :(

I have a code that replaces various text strings. It looks like this (+ some more IFs):

Sub Fix()
  Dim X As Long, Cell As Range
  For Each Cell In Selection
    For X = Len(Cell.Text) To 1 Step -1
      If Cell.Characters(X, 3).Text = ", ," Then Cell.Characters(X, 3).Text = ","
      If Cell.Characters(X, 3).Text = ", (" Then Cell.Characters(X, 3).Text = " ("
      If Cell.Characters(X, 3).Text = ", [" Then Cell.Characters(X, 3).Text = " ["
      If Cell.Characters(X, 3).Text = ", -" Then Cell.Characters(X, 3).Text = " -"
      If Cell.Characters(1, 3).Text = "abc" Then Cell.Characters(1, 3).Text = ""
    Next
  Next
End Sub

The last line of my code deletes abc if this is contained at the beginning of the selected cell(s).

I am looking to find out how to delete abc when this is contained at the end of the selected cell(s).

But it's really important for me to preserve all the original formatting in the cells (text size, colors, bold/italic/underline letters etc).

Please bear in mind that I am a complete beginner and I don't know anything about programming. I've copied the code above from the internet and just changed the values.

Thank you in advance for your help.

Body:
Try,

Sub test()
    Dim rngDB As Range, rng As Range
    Dim i As Integer, x As Integer
    Dim vWhat As Variant, vReplace As Variant
    Dim s As String

    Set rngDB = Selection
    vWhat = Array("abc", ", ,", ", (", ", [", ", -")
    vReplace = Array("", ",", " (", " [", " -")

    For Each rng In rngDB
        x = Len(rng) - 2
        s = rng
        If x > 0 Then
            For i = 0 To UBound(vWhat)
                If Mid(s, x, 3) = vWhat(i) Then
                    rng.Characters(x, 3).Text = vReplace(i)
                End If
            Next i
        End If
    Next rng

End Sub


问:
How can we create asynchronous API in django?
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

```<code>import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()
</code>```

I have tried celery for the same as follows where I am waiting for celery response in view itself:

```<code>import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)
</code>```

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?

答:
As mentioned in @Blusky's answer:
The asynchronous API will exist in django 3.X. not before.

If this is not an option, then the answer is just no.

Please note as well, that even with django 3.X any django code, that accesses the database will not be asynchronous it had to be executed in a thread (thread pool)

Celery is intended for background tasks or deferred tasks, but celery will never return an  HTTP response as it didn't receive the HTTP request to which it should respond to. Celery is also not asyncio friendly.

You might have to think of changing your architecture / implementation.
Look at your overall problem and ask yourself whether you really need an asynchronous API with Django.

Is this API intended for browser applications or for machine to machine applications?

Could your client's use web sockets and wait for the answer?

Could you separate blocking and non blocking parts on your server side?
Use django for everything non blocking, for everything periodic / deferred (django + celelry) and implement the asynchronous part with web server plugins or python ASGI code or web sockets.

Some ideas

Use Django + nginx nchan (if your web server is nginx)

Link to nchan: https://nchan.io/
your API call would create a task id, start a celery task, return immediately the task id or a polling url.

The polling URL would be handled for example via an nchan  long polling channel.
your client connects to the url corresponding to an nchan long polling channel and celery deblocks it whenever you're  task is finished (the 10s are over)

Use Django + an ASGI server + one handcoded view and use strategy similiar to nginx nchan

Same logic as above, but you don't use nginx nchan, but implement it yourself

Use an ASGI server + a non blocking framework (or just some hand coded ASGI views) for all blocking urls and Django for the rest.

They might exchange data via the data base, local files or via local http requests.

Just stay blocking and throw enough worker processes / threads at your server

This is probably the worst suggestion, but if it is just for personal use,
and you know how many requests you will have in parallel then just make sure you have enough Django workers, so that you can afford to be blocking.
I this case you would block an entire Django worker for each slow request.

Use websockets. e.g. with the channels module for Django

Websockets can be implemented with earlier versions of django (>= 2.2) with the django channels module (pip install channels) ( https://github.com/django/channels )

You need an ASGI server to server the asynchronous part. You could use for example Daphne ot uvicorn (The channel doc explains this rather well)

Addendum 2020-06-01: simple async example calling synchronous django code

Following code uses the starlette module as it seems quite simple and small

miniasyncio.py

```<code>import asyncio
import concurrent.futures
import os
import django
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pjt.settings')
django.setup()

from django_app.xxx import synchronous_func1
from django_app.xxx import synchronous_func2

executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)

async def simple_slow(request):
    """ simple function, that sleeps in an async matter """
    await asyncio.sleep(5)
    return Response('hello world')

async def call_slow_dj_funcs(request):
    """ slow django code will be called in a thread pool """
    loop = asyncio.get_running_loop()
    future_func1 = executor.submit(synchronous_func1)
    func1_result = future_func1.result()
    future_func2 = executor.submit(synchronous_func2)
    func2_result = future_func2.result()
    response_txt = "OK"
    return Response(response_txt, media_type="text/plain")

routes = [
    Route("/simple", endpoint=simple_slow),
    Route("/slow_dj_funcs", endpoint=call_slow_dj_funcs),
]

app = Starlette(debug=True, routes=routes)
</code>```

you could for example run this code with

```<code>pip install uvicorn
uvicorn --port 8002 miniasyncio:app
</code>```

then on your web server route these specific urls to uvicorn and not to your django application server.

Body:
I want to create a third party chatbot API which is asynchronous and replies "ok" after 10 seconds pause.

import time

def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    return wait()

I have tried celery for the same as follows where I am waiting for celery response in view itself:

import time
from celery import shared_task

@shared_task
def wait():
    time.sleep(10)
    return "ok"

# views.py
def api(request):
    a = wait.delay()
    work = AsyncResult(a.id)
    while True:
        if work.ready():
           return work.get(timeout=1)

But this solution works synchronously and makes no difference. How can we make it asynchronous without asking our user to keep on requesting until the result is received?

Body:
As mentioned in @Blusky's answer:
The asynchronous API will exist in django 3.X. not before.

If this is not an option, then the answer is just no.

Please note as well, that even with django 3.X any django code, that accesses the database will not be asynchronous it had to be executed in a thread (thread pool)

Celery is intended for background tasks or deferred tasks, but celery will never return an  HTTP response as it didn't receive the HTTP request to which it should respond to. Celery is also not asyncio friendly.

You might have to think of changing your architecture / implementation.
Look at your overall problem and ask yourself whether you really need an asynchronous API with Django.

Is this API intended for browser applications or for machine to machine applications?

Could your client's use web sockets and wait for the answer?

Could you separate blocking and non blocking parts on your server side?
Use django for everything non blocking, for everything periodic / deferred (django + celelry) and implement the asynchronous part with web server plugins or python ASGI code or web sockets.

Some ideas

Use Django + nginx nchan (if your web server is nginx)

Link to nchan: https://nchan.io/
your API call would create a task id, start a celery task, return immediately the task id or a polling url.

The polling URL would be handled for example via an nchan  long polling channel.
your client connects to the url corresponding to an nchan long polling channel and celery deblocks it whenever you're  task is finished (the 10s are over)

Use Django + an ASGI server + one handcoded view and use strategy similiar to nginx nchan

Same logic as above, but you don't use nginx nchan, but implement it yourself

Use an ASGI server + a non blocking framework (or just some hand coded ASGI views) for all blocking urls and Django for the rest.

They might exchange data via the data base, local files or via local http requests.

Just stay blocking and throw enough worker processes / threads at your server

This is probably the worst suggestion, but if it is just for personal use,
and you know how many requests you will have in parallel then just make sure you have enough Django workers, so that you can afford to be blocking.
I this case you would block an entire Django worker for each slow request.

Use websockets. e.g. with the channels module for Django

Websockets can be implemented with earlier versions of django (>= 2.2) with the django channels module (pip install channels) ( https://github.com/django/channels )

You need an ASGI server to server the asynchronous part. You could use for example Daphne ot uvicorn (The channel doc explains this rather well)

Addendum 2020-06-01: simple async example calling synchronous django code

Following code uses the starlette module as it seems quite simple and small

miniasyncio.py

import asyncio
import concurrent.futures
import os
import django
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pjt.settings')
django.setup()

from django_app.xxx import synchronous_func1
from django_app.xxx import synchronous_func2

executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)

async def simple_slow(request):
    """ simple function, that sleeps in an async matter """
    await asyncio.sleep(5)
    return Response('hello world')

async def call_slow_dj_funcs(request):
    """ slow django code will be called in a thread pool """
    loop = asyncio.get_running_loop()
    future_func1 = executor.submit(synchronous_func1)
    func1_result = future_func1.result()
    future_func2 = executor.submit(synchronous_func2)
    func2_result = future_func2.result()
    response_txt = "OK"
    return Response(response_txt, media_type="text/plain")

routes = [
    Route("/simple", endpoint=simple_slow),
    Route("/slow_dj_funcs", endpoint=call_slow_dj_funcs),
]

app = Starlette(debug=True, routes=routes)

you could for example run this code with

pip install uvicorn
uvicorn --port 8002 miniasyncio:app

then on your web server route these specific urls to uvicorn and not to your django application server.


问:
ASP.NET MVC 3 getting values from dynamic radiobuttons
I have a VERY similar question to this question:

ASP.NET MVC C# dynamic radiobuttons getting formcollection

However, the only difference is, instead of naming the names as:

name="radios[0]" and name="radios[1]", with an 0 and 1, respectively, I need to start mine at 1.

When it comes into public ActionResult Update(string[] radios), it is null because it does not start at 0.  I am trying to get this to work using a Dictionary<int, int> radios, and having my names as:

name="radios[1][1 through 3]" and then name="radios[2][1 through 3]" but it doesn't seem to  be working.  Any ideas?  I can not just subtract 1 from all the values because that's not necessarily the case, I said I am using 1 as an example.  Thanks, any help would be great!!

答:
Take a look at phil haacked blog entry, specifically the part: Non-Sequential Indices

To summerise, you need to add 3 new hidden fields, all called radios.Index, one with the value 1 , one with value 2 and the other with the value of 3

e.g.

```<code><input type="hidden" name="radios.Index" value="1" />
<input type="hidden" name="radios.Index" value="2" />
<input type="hidden" name="radios.Index" value="3" />
</code>```

Martin

Body:
Take a look at phil haacked blog entry, specifically the part: Non-Sequential Indices

To summerise, you need to add 3 new hidden fields, all called radios.Index, one with the value 1 , one with value 2 and the other with the value of 3

e.g.

<input type="hidden" name="radios.Index" value="1" />
<input type="hidden" name="radios.Index" value="2" />
<input type="hidden" name="radios.Index" value="3" />

Martin


问:
Sorting and grouping a mutlidimensional array in php
I need some help with sorting a multidimensional array in php. I need the array to be grouped into months, and then sorted by month. Here's my original array:

```<code>Array
(
    [0] => Array
        (
            [IdEvent] => 5
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 08
        )

    [1] => Array
        (
            [IdEvent] => 7
            [EventName] => Copy of Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 07
        )

    [2] => Array
        (
            [IdEvent] => 1
            [EventName] => Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )

    [3] => Array
        (
            [IdEvent] => 6
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )

)
</code>```

And here's what I'm hoping to get:

```<code>Array
(

    [0] => Array (

        [0] => Array
            (
                [IdEvent] => 1
                [EventName] => Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )

        [1] => Array
            (
                [IdEvent] => 6
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )

    )

    [1] => Array (

        [0] => Array
            (
                [IdEvent] => 7
                [EventName] => Copy of Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 07
            )

    )

    [2] => Array (

        [0] => Array
            (
                [IdEvent] => 5
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 08
            )
    )

)
</code>```

答:
I would use an easily sortable key for each month-container, then just use ksort

```<code>$months = array();
foreach ($input_array AS $arr) {
  $months[$arr['Month']][] = $arr;
}
ksort($months);
</code>```

if you want, you can then use array_values to turn it into a standard integer-key array

Body:
I need some help with sorting a multidimensional array in php. I need the array to be grouped into months, and then sorted by month. Here's my original array:

Array
(
    [0] => Array
        (
            [IdEvent] => 5
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 08
        )

    [1] => Array
        (
            [IdEvent] => 7
            [EventName] => Copy of Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 07
        )

    [2] => Array
        (
            [IdEvent] => 1
            [EventName] => Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )

    [3] => Array
        (
            [IdEvent] => 6
            [EventName] => Copy of Opening snow weekend
            [Year] => 2011
            [Month] => 05
        )

)

And here's what I'm hoping to get:

Array
(

    [0] => Array (

        [0] => Array
            (
                [IdEvent] => 1
                [EventName] => Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )

        [1] => Array
            (
                [IdEvent] => 6
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 05
            )

    )

    [1] => Array (

        [0] => Array
            (
                [IdEvent] => 7
                [EventName] => Copy of Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 07
            )

    )

    [2] => Array (

        [0] => Array
            (
                [IdEvent] => 5
                [EventName] => Copy of Opening snow weekend
                [Year] => 2011
                [Month] => 08
            )
    )

)

Body:
I would use an easily sortable key for each month-container, then just use ksort

$months = array();
foreach ($input_array AS $arr) {
  $months[$arr['Month']][] = $arr;
}
ksort($months);

if you want, you can then use array_values to turn it into a standard integer-key array


问:
Lazy-loading is not supported for detached entities EF
I need help to my new project for learning. i am using linq and EF and getting data from db. but it's show subjected error my code are below

Class Have Many subjects : Class 1 have these Subjects list  English, Science , Mathematics
ERROR:

InvalidOperationException: Error generated for warning
  'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning':
  An attempt was made to lazy-load navigation property 'ClassSubject' on
  detached entity of type 'SubjectProxy'. Lazy-loading is not supported
  for detached entities or entities that are loaded with
  'AsNoTracking()'. This exception can be suppressed or logged by
  passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the
  'ConfigureWarnings' method in 'DbContext.OnConfiguring' or
  'AddDbContext'.
  pri

```<code>vate readonly IGenericRepository<Subject> _subject;
        private readonly IGenericRepository<ClassSubject> _classSubject;
        public SubjectService(IGenericRepository<Subject> subject, IGenericRepository<ClassSubject> classSubject)
        {
            _subject = subject;
            _classSubject = classSubject;

        }
   public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
    {
        var _dbs = await _classSubject.AllAsync().ConfigureAwait(false);
        return _dbs.Select(x => new ClassSubjectLib
        {
            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
            SubjectId = Convert.ToString(x.SubjectId),
            SubjectInfo = _subject.FindBy(s => s.SubjectId == x.SubjectId)

        });
    }
    public class ClassSubjectLib
    {
        public int ClassSubjectId { get; set; }
        public string ClassDetailsId{ get; set; }
        public string SubjectId { get; set; }
        public IEnumerable<Subject> SubjectInfo { get; set; }
    }

 public  class Subject
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int SubjectId { get; set; }
        [Column(TypeName = "VARCHAR(100)")]
        public string SubjectName { get; set; }
        public bool IsShow { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual ICollection<ClassSubject> ClassSubject { get; set; }
    }

public class ClassSubject
    {
        [Key]
        public int ClassSubjectId { get; set; }
        public int ClassDetailsId { get; set; }
        public int SubjectId { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual Subject Subject { get; set; }
        public virtual ClassDetails ClassDetails { get; set; }

    }
</code>```

I need data Like

```<code>{
    "ClassSubjectId": 1,
    "ClassDetailsId": 1,
    "SubjectInfo": [{
        "SubjectName": "Abc",
        "SubjectId": 1
    }, {
        "SubjectName": "cfd",
        "SubjectId": 2
    }]
}
</code>```

 Data of database

答: As the error message says once you use AsNoTracking() lazy loading doesn't work since your navigation properties cannot be loaded anymore. Try removing AsNoTracking() from the query in the repository.

Body:
I need help to my new project for learning. i am using linq and EF and getting data from db. but it's show subjected error my code are below

Class Have Many subjects : Class 1 have these Subjects list  English, Science , Mathematics
ERROR:

InvalidOperationException: Error generated for warning
  'Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning':
  An attempt was made to lazy-load navigation property 'ClassSubject' on
  detached entity of type 'SubjectProxy'. Lazy-loading is not supported
  for detached entities or entities that are loaded with
  'AsNoTracking()'. This exception can be suppressed or logged by
  passing event ID 'CoreEventId.DetachedLazyLoadingWarning' to the
  'ConfigureWarnings' method in 'DbContext.OnConfiguring' or
  'AddDbContext'.
  pri

vate readonly IGenericRepository<Subject> _subject;
        private readonly IGenericRepository<ClassSubject> _classSubject;
        public SubjectService(IGenericRepository<Subject> subject, IGenericRepository<ClassSubject> classSubject)
        {
            _subject = subject;
            _classSubject = classSubject;

        }
   public async Task<IEnumerable<ClassSubjectLib>> GetClassSubject()
    {
        var _dbs = await _classSubject.AllAsync().ConfigureAwait(false);
        return _dbs.Select(x => new ClassSubjectLib
        {
            ClassDetailsId = Convert.ToString(x.ClassDetailsId),
            SubjectId = Convert.ToString(x.SubjectId),
            SubjectInfo = _subject.FindBy(s => s.SubjectId == x.SubjectId)

        });
    }
    public class ClassSubjectLib
    {
        public int ClassSubjectId { get; set; }
        public string ClassDetailsId{ get; set; }
        public string SubjectId { get; set; }
        public IEnumerable<Subject> SubjectInfo { get; set; }
    }

 public  class Subject
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int SubjectId { get; set; }
        [Column(TypeName = "VARCHAR(100)")]
        public string SubjectName { get; set; }
        public bool IsShow { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual ICollection<ClassSubject> ClassSubject { get; set; }
    }

public class ClassSubject
    {
        [Key]
        public int ClassSubjectId { get; set; }
        public int ClassDetailsId { get; set; }
        public int SubjectId { get; set; }

        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
        public virtual Subject Subject { get; set; }
        public virtual ClassDetails ClassDetails { get; set; }

    }

I need data Like

{
    "ClassSubjectId": 1,
    "ClassDetailsId": 1,
    "SubjectInfo": [{
        "SubjectName": "Abc",
        "SubjectId": 1
    }, {
        "SubjectName": "cfd",
        "SubjectId": 2
    }]
}

 Data of database


问:
How to generate random numbers and compare them with token inputs?
So i'm trying to make a function def number_guess(num): in order to generate some random integers and compare them with certain inputs() and print some statements.

For ex if i input:

```<code>32 45 48 80
</code>```

My target output is

```<code>32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct!
80 is too low. Random number was 97.
</code>```

We are also using the seed value 900, which will cause the computer to choose the same random number every time the program runs.

So far my code is:

```<code># TODO: Import the random module
import random

def number_guess(num):
    # TODO: Get a random number between 1-100

    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for token in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(user_input[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(user_input[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)

    # Convert the string tokens into integers
    user_input = input()
    tokens = user_input.split()
    for token in tokens:
        num = int(token)
        number_guess(num)
</code>```

I tried:
def number_guess(num):
        # TODO: Get a random number between 1-100

```<code>    randint = ['']
    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for num in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(num[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(num[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))
</code>```

But i'm not really understanding the format and how the functions for this should work. Any help is appreciated!

答:
You need to store your random.randint() call to memory.

Use a variable like randint = random.randint(), since it will work in your code now.

Body:
So i'm trying to make a function def number_guess(num): in order to generate some random integers and compare them with certain inputs() and print some statements.

For ex if i input:

32 45 48 80

My target output is

32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct!
80 is too low. Random number was 97.

We are also using the seed value 900, which will cause the computer to choose the same random number every time the program runs.

So far my code is:

# TODO: Import the random module
import random

def number_guess(num):
    # TODO: Get a random number between 1-100

    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for token in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(user_input[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(user_input[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)

    # Convert the string tokens into integers
    user_input = input()
    tokens = user_input.split()
    for token in tokens:
        num = int(token)
        number_guess(num)

I tried:
def number_guess(num):
        # TODO: Get a random number between 1-100

    randint = ['']
    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for num in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(num[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(num[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

But i'm not really understanding the format and how the functions for this should work. Any help is appreciated!