问:
GPU Picking inconsistent across devices
I’m trying to implement GPU picking with Points using code I modified from the latter half of this article https://threejsfundamentals.org/threejs/lessons/threejs-picking.html

It’s been working fine for me on desktop, but I started testing different browsers and devices and it doesn’t work consistently. I made a Codepen to illustrate https://codepen.io/deklanw/pen/OJVVmEd?editors=1111

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas>
<script type="module">
// Three.js - Picking - RayCaster w/Transparency
// from https://threejsfundamentals.org/threejs/threejs-picking-gpu.html

import * as THREE from "https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.module.js";

function main() {
  const canvas = document.querySelector("#c");
  const renderer = new THREE.WebGLRenderer({ canvas });

  const fov = 60;
  const aspect = 2; // the canvas default
  const near = 0.1;
  const far = 200;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 30;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0);
  const pickingScene = new THREE.Scene();
  pickingScene.background = new THREE.Color(0);

  // put the camera on a pole (parent it to an object)
  // so we can spin the pole to move the camera around the scene
  const cameraPole = new THREE.Object3D();
  scene.add(cameraPole);
  cameraPole.add(camera);

  function randomNormalizedColor() {
    return Math.random();
  }

  function getRandomInt(n) {
    return Math.floor(Math.random() * n);
  }

  function getCanvasRelativePosition(e) {
    const rect = canvas.getBoundingClientRect();
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  }

  const textureLoader = new THREE.TextureLoader();
  const particleTexture =
    "https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/ball.png";

  const vertexShader = `
    attribute float size;
    attribute vec3 customColor;

    varying vec3 vColor;

    void main() {
        vColor = customColor;
        vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
        gl_PointSize = size * ( 100.0 / length( mvPosition.xyz ) );
        gl_Position = projectionMatrix * mvPosition;
    }
`;

  const fragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;

    void main() {
        vec4 tColor = texture2D( texture, gl_PointCoord );
        if (tColor.a < 0.5) discard;
        gl_FragColor = mix( vec4( vColor.rgb, 1.0 ), tColor, 0.1 );
    }
`;

  const pickFragmentShader = `
    uniform sampler2D texture;
    varying vec3 vColor;

    void main() {
      vec4 tColor = texture2D( texture, gl_PointCoord );
      if (tColor.a < 0.25) discard;
      gl_FragColor = vec4( vColor.rgb, 1.0);
    }
`;

  const materialSettings = {
    uniforms: {
      texture: {
        type: "t",
        value: textureLoader.load(particleTexture)
      }
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
    blending: THREE.NormalBlending,
    depthTest: true,
    transparent: false
  };

  const createParticleMaterial = () => {
    const material = new THREE.ShaderMaterial(materialSettings);
    return material;
  };

  const createPickingMaterial = () => {
    const material = new THREE.ShaderMaterial({
      ...materialSettings,
      fragmentShader: pickFragmentShader,
      blending: THREE.NormalBlending
    });
    return material;
  };

  const geometry = new THREE.BufferGeometry();
  const pickingGeometry = new THREE.BufferGeometry();
  const colors = [];
  const sizes = [];
  const pickingColors = [];
  const pickingColor = new THREE.Color();
  const positions = [];

  for (let i = 0; i < 30; i++) {
    colors[3 * i] = randomNormalizedColor();
    colors[3 * i + 1] = randomNormalizedColor();
    colors[3 * i + 2] = randomNormalizedColor();

    const rgbPickingColor = pickingColor.setHex(i + 1);
    pickingColors[3 * i] = rgbPickingColor.r;
    pickingColors[3 * i + 1] = rgbPickingColor.g;
    pickingColors[3 * i + 2] = rgbPickingColor.b;

    sizes[i] = getRandomInt(20);

    positions[3 * i] = getRandomInt(20);
    positions[3 * i + 1] = getRandomInt(20);
    positions[3 * i + 2] = getRandomInt(20);
  }

  geometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 3)
  );
  geometry.setAttribute(
    "customColor",
    new THREE.Float32BufferAttribute(colors, 3)
  );
  geometry.setAttribute("size", new THREE.Float32BufferAttribute(sizes, 1));

  geometry.computeBoundingBox();

  const material = createParticleMaterial();
  const points = new THREE.Points(geometry, material);

  // setup geometry and material for GPU picking
  pickingGeometry.setAttribute(
    "position",
    new THREE.Float32BufferAttribute(positions, 3)
  );
  pickingGeometry.setAttribute(
    "customColor",
    new THREE.Float32BufferAttribute(pickingColors, 3)
  );
  pickingGeometry.setAttribute(
    "size",
    new THREE.Float32BufferAttribute(sizes, 1)
  );

  pickingGeometry.computeBoundingBox();

  const pickingMaterial = createPickingMaterial();
  const pickingPoints = new THREE.Points(pickingGeometry, pickingMaterial);

  scene.add(points);
  pickingScene.add(pickingPoints);

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  class GPUPickHelper {
    constructor() {
      // create a 1x1 pixel render target
      this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
      this.pixelBuffer = new Uint8Array(4);
    }
    pick(cssPosition, pickingScene, camera) {
      const { pickingTexture, pixelBuffer } = this;

      // set the view offset to represent just a single pixel under the mouse
      const pixelRatio = renderer.getPixelRatio();
      camera.setViewOffset(
        renderer.getContext().drawingBufferWidth, // full width
        renderer.getContext().drawingBufferHeight, // full top
        (cssPosition.x * pixelRatio) | 0, // rect x
        (cssPosition.y * pixelRatio) | 0, // rect y
        1, // rect width
        1 // rect height
      );
      // render the scene
      renderer.setRenderTarget(pickingTexture);
      renderer.render(pickingScene, camera);
      renderer.setRenderTarget(null);
      // clear the view offset so rendering returns to normal
      camera.clearViewOffset();
      //read the pixel
      renderer.readRenderTargetPixels(
        pickingTexture,
        0, // x
        0, // y
        1, // width
        1, // height
        pixelBuffer
      );

      const id =
        (pixelBuffer[0] << 16) | (pixelBuffer[1] << 8) | pixelBuffer[2];

      console.log(`You clicked sphere number ${id}`);

      return id;
    }
  }

  const pickHelper = new GPUPickHelper();

  function render(time) {
    time *= 0.001; // convert to seconds;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    cameraPole.rotation.y = time * 0.1;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

  function onClick(e) {
    const pickPosition = getCanvasRelativePosition(e);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  function onTouch(e) {
    const touch = e.touches[0];
    const pickPosition = getCanvasRelativePosition(touch);
    const pickedID = pickHelper.pick(pickPosition, pickingScene, camera);
  }

  window.addEventListener("mousedown", onClick);
  window.addEventListener("touchstart", onTouch);
}

main();
</script></code>```

If you click (or tap) on the nodes their IDs should pop up in the console. On some devices I’m just getting 0, as in picking the background.

Anyone know why?

Also, if there’s a way to do picking in this case (Point mesh with variable size points via ShaderMaterial) with an easier method that’s still performant, I’m curious about how

EDIT:

I removed the 1x1 render target optimization and it seems to have fixed it. Now I'd like to know what about that optimization causes the problem..

答:
the problem is you can't use Points this way across devices.

Whether a point is drawn when its center is offscreen or not is device independent (the OpenGL ES / WebGL spec says it's still supposed to be drawn, the OpenGL spec says it's not. There are no tests for it so each driver is different) and it would be too much work for WebGL implentations to work around so they don't. AFAIK Intel and NVidia do draw them. AMD and PowerVR based (iPhone) do not draw them.

You can see this problem if you make the circles large and you make sure they go offscreen (and you may need to make your canvas small). On some devices they will smoothly go offscreen, on other devices as soon as their center goes offscreen they will disappear (often depending on the size of the point and the size of the viewport)

This means your example does not really work in either case, with or without the 1x1 pixel render target it's just that with the 1x1 pixel render target pretty much all of the circles have their center outside that 1x1 pixel area so they don't get drawn on some devices. When you make the render target match the size of the canvas then most of the circles' centers are inside but you'll still get picking errors at the edges.

To solve this you'll need to draw your points using quads instead of points. There are many ways to do that. Draw each quad as a separate mesh or sprite, or merge all the quads into another mesh, or use InstancedMesh where you'll need a matrix per point, or write custom shaders to do points (see the last example on this article)

Note that points have other issues too. By default they don't scale relative to the canvas size (of course you can fix this in your shader and three.js has this option as well). They also have a device independent maximum size which according to the spec can be as low as 1 pixel. They don't respond well to device pixel ratio settings (though you could fix that in code as well). For all those reasons points have a limited uses. The large circles the code is drawing is arguably beyond that limit.

Title: GPU Picking inconsistent across devices

Body:
I’m trying to implement GPU picking with Points using code I modified from the latter half of this article https://threejsfundamentals.org/threejs/lessons/threejs-picking.html

It’s been working fine for me on desktop, but I started testing different browsers and devices and it doesn’t work consistently. I made a Codepen to illustrate https://codepen.io/deklanw/pen/OJVVmEd?editors=1111

body {
  margin: 0;
}
#c {
  width: 100vw;
  height: 100vh;
  display: block;
}

<canvas id="c"></canvas>

If you click (or tap) on the nodes their IDs should pop up in the console. On some devices I’m just getting 0, as in picking the background.

Anyone know why?

Also, if there’s a way to do picking in this case (Point mesh with variable size points via ShaderMaterial) with an easier method that’s still performant, I’m curious about how

EDIT:

I removed the 1x1 render target optimization and it seems to have fixed it. Now I'd like to know what about that optimization causes the problem..


来源: stackexchange

问:
PHP encourage loop part way through the loop
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

```<code>foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}
</code>```

答:
Use continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

ContentLicense: CC BY-SA 3.0

Body:
I am wanting to get a loop to loop without going through all the code for the loop. For instance in the example code I want to continue the loop without have to go through any of the if statements below the one that matches.

NOTE: I know something similar to this example would be better done using a switch statement but my set of if statements are not as simple as this.

foreach($array as $key=>$value){
    if(is_varchar($value)){loop;}
    if(is_text($value)){loop;}
    if(is_mediumText($value)){loop;}
    if(is_boolean($value)){loop;}
    if(is_integer($value)){loop;}
    if(is_float($value)){loop;}
    if(is_double($value)){loop;}
}


问:
Optimizing Script Pulling Data From Multiple Google Sheets
I want a script to search multiple Google Sheets files and pull specific information from each file to create a master status page that my boss can easily see.  The following code works, it's just really slow (and I'm probably not doing it the easiest way).  What's the best way to speed it up? I'm sure there's some way to set up an array, but I'm lost trying to find it.</p>

```<code>  var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById()

// Sets up the rules for what to search
  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while (files.hasNext()) {
    var file = files.next()
    var filelog = file.getId()
    var tickets = SpreadsheetApp.openById(file.getId())

//Gets Values from Each File
    var ticketno = tickets.getRange('Form!C1').getValue()
    var jobname = tickets.getRange('Form!C3').getValue()
    var status = tickets.getRange('Form!H1').getValue()
    var assigned = tickets.getRange('Form!C22').getValue()
    var description = tickets.getRange('Form!A18').getValue()

//Sets Values to Master Spreadsheet
    var ssh = ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1)
    ss.getRange('Order Status!A2').setValue(ticketno)
    ss.getRange('Order Status!B2').setValue(jobname)
    ss.getRange('Order Status!C2').setValue(status)
    ss.getRange('Order Status!D2').setValue(assigned)
    ss.getRange('Order Status!E2').setValue(description)
</code>```

答:
This is faster but really the largest slice in time is probably just opening up the files.

```<code>function faster() {
  var ss=SpreadsheetApp.getActive();
  var folder=DriveApp.getFolderById();
  var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  while (files.hasNext()) {
    var file=files.next();
    var tss=SpreadsheetApp.openById(file.getId());
    var vA=tss.getSheetByName('Form').getRange(1,1,22,8).getValues();
    var ssh=ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1);//you could avoid this by creating a sheet that you could append to and that would be a little faster
    SpreadsheetApp.flush();//not sure if this is needed but this has to complete before the next operation takes place
    ssh.getRange(2,1,1,5).setValues([[vA[0][2],vA[2][2],vA[0][7],vA[21][2],vA[17][0]]]);
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want a script to search multiple Google Sheets files and pull specific information from each file to create a master status page that my boss can easily see.  The following code works, it's just really slow (and I'm probably not doing it the easiest way).  What's the best way to speed it up? I'm sure there's some way to set up an array, but I'm lost trying to find it.

  var ss = SpreadsheetApp.getActive()
  var folder = DriveApp.getFolderById()

// Sets up the rules for what to search
  var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while (files.hasNext()) {
    var file = files.next()
    var filelog = file.getId()
    var tickets = SpreadsheetApp.openById(file.getId())

//Gets Values from Each File
    var ticketno = tickets.getRange('Form!C1').getValue()
    var jobname = tickets.getRange('Form!C3').getValue()
    var status = tickets.getRange('Form!H1').getValue()
    var assigned = tickets.getRange('Form!C22').getValue()
    var description = tickets.getRange('Form!A18').getValue()

//Sets Values to Master Spreadsheet
    var ssh = ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1)
    ss.getRange('Order Status!A2').setValue(ticketno)
    ss.getRange('Order Status!B2').setValue(jobname)
    ss.getRange('Order Status!C2').setValue(status)
    ss.getRange('Order Status!D2').setValue(assigned)
    ss.getRange('Order Status!E2').setValue(description)

Body:
This is faster but really the largest slice in time is probably just opening up the files.

function faster() {
  var ss=SpreadsheetApp.getActive();
  var folder=DriveApp.getFolderById();
  var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
  while (files.hasNext()) {
    var file=files.next();
    var tss=SpreadsheetApp.openById(file.getId());
    var vA=tss.getSheetByName('Form').getRange(1,1,22,8).getValues();
    var ssh=ss.getSheetByName("Order Status")
    ssh.insertRowAfter(1);//you could avoid this by creating a sheet that you could append to and that would be a little faster
    SpreadsheetApp.flush();//not sure if this is needed but this has to complete before the next operation takes place
    ssh.getRange(2,1,1,5).setValues([[vA[0][2],vA[2][2],vA[0][7],vA[21][2],vA[17][0]]]);
  }
}


问:
Evaluate random function for each row
I have the following sql:

SELECT SERIES.TIME AS TIME
FROM GENERATE_SERIES(
             CAST('now' AS TIMESTAMP) - cast('1 month' AS INTERVAL),
             CAST('now' AS TIMESTAMP),
             CAST('1 day' AS INTERVAL)
         ) AS SERIES (TIME)
         CROSS JOIN
         (SELECT * FROM GENERATE_SERIES(1, (floor(random() * 10)::int))) as RANDOM_TABLE
```

<p>This should generate a series of dates with an interval of one hour in it. What I now try to get is each day to be randomly fanned out. I have noticed that in the above sql statement <code>random()</code> is only evaluated once even though it is in a subquery.</p>

<p>Now without the <code>CROSS JOIN</code> I get:</p>

```| 2019-02-13 |
| 2019-02-14 |
| 2019-02-15 |
```

<p>and with the <code>CROSS JOIN</code> I now get for example:</p>

```| 2019-02-13 |
| 2019-02-13 |
| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |
```

<p>What I would like to have is a random number each time I fan out. E.g.:</p>

```| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |
```

How do I need to modify my query to achieve that?

答:
You can do it like this: </p>

```<code>SELECT t.time
FROM (
  SELECT series.time as time, (floor(random() * 10)::int) as num_days
  FROM generate_series(now() - interval '1 month', now(), interval '1 day') AS series (time)
) t
  CROSS JOIN generate_series(1, num_days)
</code>```

Title: Evaluate random function for each row

Body:
I have the following sql:

SELECT SERIES.TIME AS TIME
FROM GENERATE_SERIES(
             CAST('now' AS TIMESTAMP) - cast('1 month' AS INTERVAL),
             CAST('now' AS TIMESTAMP),
             CAST('1 day' AS INTERVAL)
         ) AS SERIES (TIME)
         CROSS JOIN
         (SELECT * FROM GENERATE_SERIES(1, (floor(random() * 10)::int))) as RANDOM_TABLE

This should generate a series of dates with an interval of one hour in it. What I now try to get is each day to be randomly fanned out. I have noticed that in the above sql statement random() is only evaluated once even though it is in a subquery.

Now without the CROSS JOIN I get:

| 2019-02-13 |
| 2019-02-14 |
| 2019-02-15 |

and with the CROSS JOIN I now get for example:

| 2019-02-13 |
| 2019-02-13 |
| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |

What I would like to have is a random number each time I fan out. E.g.:

| 2019-02-13 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-14 |
| 2019-02-15 |
| 2019-02-15 |
| 2019-02-15 |

How do I need to modify my query to achieve that?

Body:
You can do it like this:

SELECT t.time
FROM (
  SELECT series.time as time, (floor(random() * 10)::int) as num_days
  FROM generate_series(now() - interval '1 month', now(), interval '1 day') AS series (time)
) t
  CROSS JOIN generate_series(1, num_days)


问:
How to suppress console error/warning/info messages when executing selenium python scripts using chrome canary
I am running python script (complete script link below) for selenium test using Chrome Canary. The test seems to be running fine, however, there are lots of error/warning/info messages displayed on the console.

Is there a way to suppress these messages? I have tried:
 chrome_options.add_argument("--silent"), but does not help. I am not able to find the right solution. Appreciate any help.

Python script : Example script provided here

Python: 3.6.3
Selenium: 3.6.0
Chrome Canary: 63.0.3239.5 (64 bit)
ChromeDriver : 2.33

答:
Works for me in Python/Chrome...

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--log-level=3')
```


问:
Internal error when publishing coursework with student copies in google classroom API Possible bug?
When I use Classroom API to publish an assignment with student copies. I get API call to classroom.courses.courseWork failed with error: Internal error encountered.

This occurs when I post a Draft successfully, then attempt to use the API to publish the assignment, or when I try to publish a new assignment directly.

Changing the assignment to "view only" solves the publishing problem in both cases but then you do not get student copies and you can not change it back after publishing and student copies are almost always required.

I can manually publish in google classroom after posting a draft with no problems.  I assume it is connected to the reason you can not make student copies after posting assignment.

I have probed before publishing and the student folder id is available but has not been created yet.

var assignment =  {
  title: "Test File",
  materials: [
    {
      driveFile:{
        driveFile: {
          id: "11klBA-80IQPaJHrpSyJHqVsK7BUWWAtoLFdwG0uJGfo",
          title: "Sample Document"
        },
        shareMode: "STUDENT_COPY"
        }
    }
  ],
  state: "PUBLISH",
  workType: "ASSIGNMENT"
};

var id = Classroom.Courses.CourseWork.create(assignment, 24551294261)
Logger.log(id);
```

<p>or</p>

<pre class="lang-js prettyprint-override"><code>Classroom.Courses.CourseWork.patch( {"state": "PUBLISHED"},24551294261,46981225150,{updateMask:'state'});
</code>```

API call to classroom.courses.courseWork.patch failed with error is returned with either program code.  The code works fine if Student_COPY is changed to view.  I believe it is a bug, the API does not have some publishing protocol that manually hitting publish does.  So it fails.  My guess would be the creation of the google folder to store the documents.

I teach 8 classes publishing each assignment manually takes a long time and if I make errors students may miss an assignment.

Hoping for a workaround or a bug fix. I am using the API to post in part to save time grading and in part to keep all 8 classes the same. I can Updating due dates or instructions without accidentally leaving anyone out. I need the API to post the assignment so it has access to the assignment for changes.

答:
I found a workaround.  You can not publish an assignment with student copy using the API.
You can use scheduledTime: for 5 min in the future and the system will publish it for you.

Instead of patching state to publish an existing assignment you can patch schedule it to open it in 5 min.  I bit of a pain but publishing 3 assignments for 8 class was taking me half an hour.  A 5 min wait is not a bad trade.  I have not tested how close to present you can set the time.  I use 5 min to allow for any lag.

By the way, patch only works on title, description, state, dueDate, dueTime, maxPoints, scheduledTime, submissionModificationMode, topicId.  Materials is not on the list.  You can not change the link or the document associated with the assignment.

Body:
When I use Classroom API to publish an assignment with student copies. I get API call to classroom.courses.courseWork failed with error: Internal error encountered.

This occurs when I post a Draft successfully, then attempt to use the API to publish the assignment, or when I try to publish a new assignment directly.

Changing the assignment to "view only" solves the publishing problem in both cases but then you do not get student copies and you can not change it back after publishing and student copies are almost always required.

I can manually publish in google classroom after posting a draft with no problems.  I assume it is connected to the reason you can not make student copies after posting assignment.

I have probed before publishing and the student folder id is available but has not been created yet.

var assignment =  {
  title: "Test File",
  materials: [
    {
      driveFile:{
        driveFile: {
          id: "11klBA-80IQPaJHrpSyJHqVsK7BUWWAtoLFdwG0uJGfo",
          title: "Sample Document"
        },
        shareMode: "STUDENT_COPY"
        }
    }
  ],
  state: "PUBLISH",
  workType: "ASSIGNMENT"
};

var id = Classroom.Courses.CourseWork.create(assignment, 24551294261)
Logger.log(id);

or

Classroom.Courses.CourseWork.patch( {"state": "PUBLISHED"},24551294261,46981225150,{updateMask:'state'});

API call to classroom.courses.courseWork.patch failed with error is returned with either program code.  The code works fine if Student_COPY is changed to view.  I believe it is a bug, the API does not have some publishing protocol that manually hitting publish does.  So it fails.  My guess would be the creation of the google folder to store the documents.

I teach 8 classes publishing each assignment manually takes a long time and if I make errors students may miss an assignment.

Hoping for a workaround or a bug fix. I am using the API to post in part to save time grading and in part to keep all 8 classes the same. I can Updating due dates or instructions without accidentally leaving anyone out. I need the API to post the assignment so it has access to the assignment for changes.


问:
How to retry a NUnit TestCase?
I want to acheive a setup where I can set a desired retry count for each test, so that I can for example, retry all my failing tests once before actually failing them. I've structured my tests this way:

```<code>    [TestCase(“Some parameter”, Category = “Test category”, TestName = “Name of test”, Description = “Description of test”)]
    public void SomeTestName(string browser) {
    //Test script
    }
</code>```

If I had used [Test] instead of [TestCase] I could have just added a [Retry(1)] attribute, but how do I achieve the same behavior with [TestCase]? I've already glanced at NUnit retry dynamic attribute which has a quite neat solution, but unfortunately it has no effect when I try to apply it to a [TestCase]

答:
Per the docs: "RetryAttribute is used on a test method to specify that it should be rerun if it fails, up to a maximum number of times."

That is, the argument is not the number of retries as you might think but the total number of attempts to run the test and [Retry(1)] has no effect at all, no matter where you use it. Since this is a possible point of confusion, I just edited that page to give an explicit warning.

If you were to try to use RetryAttribute on a class, you would get a compiler warning because it can only be used on methods. However, in NUnit, a method may represent either a single test or a group of parameterized tests. In the case of a parameterized test, the attribute currently has no effect.

It would be possible for the NUnit team to decide that this attribute applies to each individual test case and modify nunit accordingly. It would also be possible for TestCaseAttribute to take an optional parameter specifying a retry count. For a long-term solution, you might want to ask them for one or the other of those options.

In the shorter term, as a workaround, you could consider deriving your own attribute from TestCaseAttribute. Here is some (untested) code to get you started...

```<code>using System;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Commands;

namespace NUnit.Framework
{
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
  public class RetryTestCaseAttribute : TestCaseAttribute, IRepeatTest
  {
    // You may not need all these constructors, but use at least the first two
    public RetryTestCaseAttribute(params object[] arguments) : base(arguments) { }
    public RetryTestCaseAttribute(object arg) : base(arg) { }
    public RetryTestCaseAttribute(object arg1, object arg2) : base(arg1, arg2) { }
    public RetryTestCaseAttribute(object arg1, object arg2, object arg3) : base(arg1, arg2, arg3) { }

    public int MaxTries { get; set; }

    // Should work, because NUnit only calls through the interface
    // Otherwise, you would delegate to a `new` non-interface `Wrap` method.
    TestCommand ICommandWrapper.Wrap(TestCommand command)
    {
      return new RetryAttribute.RetryCommand(command, MaxTries);
    }
  }
}
</code>```

You would use this as follows

```<code>[RetryTestCase("some parameter", MaxTries=3)]
public void SomeTestName(string browser)
{
  // Your test code
}
</code>```

Some Notes about the above:

I have compiled this code but haven't tested it. Please post a comment if you try it out, especially if it needs modifications.

The code relies on some knowledge of NUnit internals and could break in the future. A more comprehensive implementation would be needed to make it future-proof. In particular, I used the fact that IRepeatTest is based on ICommandWrapper but adds no methods. I believe that each of the two interfaces is needed where I put them because NUnit examines them at different points in its code.

This code is about three times as many lines of code compared to what would be needed to add a retry count to TestCaseAttribute! Ask the NUnit Project if you would like that feature - or contribute it yourself!

Title: How to retry a NUnit TestCase?

Body:
I want to acheive a setup where I can set a desired retry count for each test, so that I can for example, retry all my failing tests once before actually failing them. I've structured my tests this way:

    [TestCase(“Some parameter”, Category = “Test category”, TestName = “Name of test”, Description = “Description of test”)]
    public void SomeTestName(string browser) {
    //Test script
    }

If I had used [Test] instead of [TestCase] I could have just added a [Retry(1)] attribute, but how do I achieve the same behavior with [TestCase]? I've already glanced at NUnit retry dynamic attribute which has a quite neat solution, but unfortunately it has no effect when I try to apply it to a [TestCase]

Body:
Per the docs: "RetryAttribute is used on a test method to specify that it should be rerun if it fails, up to a maximum number of times."

That is, the argument is not the number of retries as you might think but the total number of attempts to run the test and [Retry(1)] has no effect at all, no matter where you use it. Since this is a possible point of confusion, I just edited that page to give an explicit warning.

If you were to try to use RetryAttribute on a class, you would get a compiler warning because it can only be used on methods. However, in NUnit, a method may represent either a single test or a group of parameterized tests. In the case of a parameterized test, the attribute currently has no effect.

It would be possible for the NUnit team to decide that this attribute applies to each individual test case and modify nunit accordingly. It would also be possible for TestCaseAttribute to take an optional parameter specifying a retry count. For a long-term solution, you might want to ask them for one or the other of those options.

In the shorter term, as a workaround, you could consider deriving your own attribute from TestCaseAttribute. Here is some (untested) code to get you started...

using System;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Commands;

namespace NUnit.Framework
{
  [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
  public class RetryTestCaseAttribute : TestCaseAttribute, IRepeatTest
  {
    // You may not need all these constructors, but use at least the first two
    public RetryTestCaseAttribute(params object[] arguments) : base(arguments) { }
    public RetryTestCaseAttribute(object arg) : base(arg) { }
    public RetryTestCaseAttribute(object arg1, object arg2) : base(arg1, arg2) { }
    public RetryTestCaseAttribute(object arg1, object arg2, object arg3) : base(arg1, arg2, arg3) { }

    public int MaxTries { get; set; }

    // Should work, because NUnit only calls through the interface
    // Otherwise, you would delegate to a `new` non-interface `Wrap` method.
    TestCommand ICommandWrapper.Wrap(TestCommand command)
    {
      return new RetryAttribute.RetryCommand(command, MaxTries);
    }
  }
}

You would use this as follows

[RetryTestCase("some parameter", MaxTries=3)]
public void SomeTestName(string browser)
{
  // Your test code
}

Some Notes about the above:

I have compiled this code but haven't tested it. Please post a comment if you try it out, especially if it needs modifications.

The code relies on some knowledge of NUnit internals and could break in the future. A more comprehensive implementation would be needed to make it future-proof. In particular, I used the fact that IRepeatTest is based on ICommandWrapper but adds no methods. I believe that each of the two interfaces is needed where I put them because NUnit examines them at different points in its code.

This code is about three times as many lines of code compared to what would be needed to add a retry count to TestCaseAttribute! Ask the NUnit Project if you would like that feature - or contribute it yourself!


问:
Why isn't my updated .gitignore working for files that are being tracked?
I have the following .gitignore file

```<code># file named .gitignore

system/application/config/database.php
system/application/config/config.php
system/logs
modules/recaptcha/config/*
</code>```

However when I add any changes in config and recapcha.php, git status warns me as following.
When I add any changes to database.php. it does not show it in status

```<code>shin@shin-Latitude-E5420:/var/www/myapp$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   modules/recaptcha/config/recaptcha.php
#   modified:   system/application/config/config.php
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

How can I fix this?

I am using git version 1.7.5.1 on Ubuntu 11.04

答: If your file is already in git before you add the directory to .gitignore git will keep tracking it. If you don't want it, do a "git rm" to remove it first. </p>

Body:
I have the following .gitignore file

# file named .gitignore

system/application/config/database.php
system/application/config/config.php
system/logs
modules/recaptcha/config/*

However when I add any changes in config and recapcha.php, git status warns me as following.
When I add any changes to database.php. it does not show it in status

shin@shin-Latitude-E5420:/var/www/myapp$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   modules/recaptcha/config/recaptcha.php
#   modified:   system/application/config/config.php
#
no changes added to commit (use "git add" and/or "git commit -a")

How can I fix this?

I am using git version 1.7.5.1 on Ubuntu 11.04


问:
Distributing data with lower and upper boundaries in Excel
Here's a link to a screenshot with the formula used in Column B and some sample data

I have a spreadsheet with 48 rows of data in column A

The values range from 0 to 19

The average of these 48 rows = 8.71

the standard deviation of the population = 3.77

I've used the STANDARDIZE function in excel in column B to return the Z-score of each item in column A given that I know the mean (8.71), std dev (3.77), and x (whatever is in column A).

For example (row 2) has:

x = 2

z = -1.779

Using the z value, I want to create an lower (4) and upper (24) boundary and calculate what the value would be in this 3rd column.

Essentially, if x = 0 (min value), then z = -2.3096, and columnC = 4 (lower boundary condition)

Conversely, if x = 19 (max value), then z = 2.9947, and columnC = 19 (upper boundary condition)

and then all other values between 0 to 19 would be calculated....

Any ideas how I can accomplish this with a formula in the column C?

答:
So if your lowest original value is 0 and your highest is 19 and you want to re-distribute them from 4 to 24 and we assume that both are linear that means:

Since both are linear we have to use these formulas:

we develope the first to c so we get

and replace the c in the second equation with that so we get

and develope this to m as follows

If we put this togeter with our third equation above we get:

So we finally have equations for m = and c = and we can use the numbers from our old and new lower and upper bound to get:

you can use these values with

where x is are your old values in column A and y is the new distributed value in column B:

Some visualization if you change the boundaries:

Idea for a non-linear solution

If you want 4 and 24 as boundaries and the mean should be 12 the solution cannot be linear of course. But you could use for example any other formula like

So you can use this formula for column D y2 with the following values a, b, c as well as calculating the mean, min and max over column D y2.

Then use the solver:

Goal is: Mean $M$15 should be 12

secondary conditions: $M$16 = 4 (lower boundary) and $M$17 = 24 (upper boundary)

variable cells are a, b and c: $M$11:$M$13

The solver will now adjust the values a, b and c so that you get very close to your goal and to get these results:

The min is 4 the max is almost 24 and the mean is almost 12 that is probably the closest you can get with a numeric method.


问:
Saving output of lapply to respective data frames
I am pretty new to R. This seems like a simple question, but I just don't know the best way to approach it. I have checked similar questions but have not found the answer I am looking for.

I have a list for data frames (actually tibbles) that I want to run through the convert() function from the hablar package to convert all of the data types for each variable in the data frames. I then want to overwrite the original data frames. Here is a simplified example data frame (N.B. all of the variables are currently factors). For simplicity I have made adm2 and adm3 the same as adm1, but there are different in my real data.

```<code>adm1 <- data.frame(admV1 = as.factor(c("male", "female", "male", "female")),
                  admV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
                  admV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
                  admV4 = as.factor(c("2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00")))

adm1 <- as_tibble(adm1)
adm2 <- adm1
adm3 <- adm1

dis1 <- data.frame(disV1 = as.factor(c("yes", "no", "yes", "no")),
                   disV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
                   disV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
                   disV4 = as.factor(c("2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00")))

dis1 <- as_tibble(dis1)
dis2 <- dis1
dis3 <- dis1
</code>```

I have two 'types' of data frames: admissions and discharges. I defined the variables that need to be converted to each data type (N.B. In my real example each is a character vector containing more than one variable name):

```<code># Define data types
adm_chr<- admV3
adm_num<- admV2
adm_fct<- admV1
adm_dte<- admV4

dis_chr<- disV3
dis_num<- disV2
dis_fct<- disV1
dis_dte<- disV4
</code>```

I have then created a list of the datasets:

```<code># Define datasets
adm_dfs<- list(adm1, adm2, adm2)
dis_dfs<- list(dis1, dis2, dis3)
</code>```

This is what I have managed so far:

```<code># Write function
convertDataTypes<- function(dfs, type = c("adm", "dis")){
  outputs1<- dfs %>% lapply(convert(chr(paste0(type, "_chr")),
                                    num(paste0(type, "_num")),
                                    fct(paste0(type, "_fct"))))
  outputs2<- dfs %>% mutate_at(vars(paste0(type, "_dte")),
                               ymd_hms, tz = "GMT")
}

# Run function
convertDataTypes(adm_dfs, "adm")
</code>```

I think I need to then use lapply over outputs1 and outputs2 to assign the variables, but there is probably a much better way of approaching this. I would be very grateful for your input.

答:
If the 'dfs' are a list of data.frames, then

```<code>library(hablar)
library(purrr)
library(dplyr)
</code>```

If the 'type' corresponds to each data.frame in the list use map2

```<code>convertDataTypes <- function(dfs, type = c("adm", "dis")) {

   map2(dfs, type, ~ {
               .type <- .y
               map(.x, ~ .x %>%
                 convert(chr(str_c(.type, "_chr")),
                         num(str_c(.type, "_num")),
                         fct(str_c(.type, "_fct"))) %>%
                 mutate_at(vars(str_c(.type,  "_dte")),
                     ymd_hms, tz = "GMT"))

           })

}

dfsN <- list(adm_dfs, dis_dfs)
</code>```

Body:
I am pretty new to R. This seems like a simple question, but I just don't know the best way to approach it. I have checked similar questions but have not found the answer I am looking for.

I have a list for data frames (actually tibbles) that I want to run through the convert() function from the hablar package to convert all of the data types for each variable in the data frames. I then want to overwrite the original data frames. Here is a simplified example data frame (N.B. all of the variables are currently factors). For simplicity I have made adm2 and adm3 the same as adm1, but there are different in my real data.

adm1 <- data.frame(admV1 = as.factor(c("male", "female", "male", "female")),
                  admV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
                  admV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
                  admV4 = as.factor(c("2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00", "2019-01-01T12:00:00")))

adm1 <- as_tibble(adm1)
adm2 <- adm1
adm3 <- adm1

dis1 <- data.frame(disV1 = as.factor(c("yes", "no", "yes", "no")),
                   disV2 = as.factor(c("12.2", "13.0", "14.0", "15.1")),
                   disV3 = as.factor(c("free text", "more free text", "even more free text", "free text again")),
                   disV4 = as.factor(c("2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00", "2019-01-01+T12:00:00")))

dis1 <- as_tibble(dis1)
dis2 <- dis1
dis3 <- dis1

I have two 'types' of data frames: admissions and discharges. I defined the variables that need to be converted to each data type (N.B. In my real example each is a character vector containing more than one variable name):

# Define data types
adm_chr<- admV3
adm_num<- admV2
adm_fct<- admV1
adm_dte<- admV4

dis_chr<- disV3
dis_num<- disV2
dis_fct<- disV1
dis_dte<- disV4

I have then created a list of the datasets:

# Define datasets
adm_dfs<- list(adm1, adm2, adm2)
dis_dfs<- list(dis1, dis2, dis3)

This is what I have managed so far:

# Write function
convertDataTypes<- function(dfs, type = c("adm", "dis")){
  outputs1<- dfs %>% lapply(convert(chr(paste0(type, "_chr")),
                                    num(paste0(type, "_num")),
                                    fct(paste0(type, "_fct"))))
  outputs2<- dfs %>% mutate_at(vars(paste0(type, "_dte")),
                               ymd_hms, tz = "GMT")
}

# Run function
convertDataTypes(adm_dfs, "adm")

I think I need to then use lapply over outputs1 and outputs2 to assign the variables, but there is probably a much better way of approaching this. I would be very grateful for your input.

Body:
If the 'dfs' are a list of data.frames, then

library(hablar)
library(purrr)
library(dplyr)

If the 'type' corresponds to each data.frame in the list use map2

convertDataTypes <- function(dfs, type = c("adm", "dis")) {

   map2(dfs, type, ~ {
               .type <- .y
               map(.x, ~ .x %>%
                 convert(chr(str_c(.type, "_chr")),
                         num(str_c(.type, "_num")),
                         fct(str_c(.type, "_fct"))) %>%
                 mutate_at(vars(str_c(.type,  "_dte")),
                     ymd_hms, tz = "GMT"))

           })

}

dfsN <- list(adm_dfs, dis_dfs)


问:
Getting seconds until the start of the next hour?
I'm writing a small API call which returns the current amount of seconds left until the end of the hour, the end of the day, and the end of the week.

Getting the end of day/week was easy, in just using strtotime('tomorrow') or strtotime('next sunday') and subtracting with time(). However, I'm not seeing any available function that would allow me to get the timestamp of the start of the next hour.

strtime('next hour') just returns back the current timestamp +1 hour - rather than the time remaining until the next hour starts.

Is there any simple way of accomplishing this?

答:
I'd encourage you to consider the Carbon date library for this sort of math. It makes things quite trivial:</p>

```<code>Carbon\Carbon::now()->endOfHour()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfDay()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfWeek()->diffInSeconds(Carbon\Carbon::now())
</code>```

Body:
I'd encourage you to consider the Carbon date library for this sort of math. It makes things quite trivial:

Carbon\Carbon::now()->endOfHour()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfDay()->diffInSeconds(Carbon\Carbon::now())
Carbon\Carbon::now()->endOfWeek()->diffInSeconds(Carbon\Carbon::now())


问:
Django deleted DDBB table and cannot migrate anymore: no such table error
I've deleted a table from the sqlite DDBB because I wanted to make some changes and wasn't able to do those with a simple update of the models in Django. Since then, I am not able to perform migrations again and get a new table for my models, getting the error "django.db.utils.OperationalError: no such table: shop_productitem".

I've tried to follow many hints in other similar threads with no luck. I've tried this and this for example and I cannot solve the issue. My understanding is that if I run makemigrations and then migrate the models the ddbb should update itself with the new specifications, but I'm probably mistaken in this specific case.

Can someone address me where the problem would sit? I fear I have not the necessary knowledge to figure this out of my own, I've been looking for ages.

Please find below the whole error message I'm getting:

```<code>    Applying shop.0002_auto_20200218_1958...Traceback (most recent call last):
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: shop_productitem

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 133, in alter_field
    super().alter_field(model, old_field, new_field, strict=strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 330, in _alter_fi
eld
    self._remake_table(model, alter_field=(old_field, new_field))
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 260, in _remake_t
able
    disable_constraints=False,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 95, in alter_db_t
able
    super().alter_db_table(model, old_db_table, new_db_table)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 383, in alter_db_tab
le
    "new_table": self.quote_name(new_db_table),
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrapp
ers
    return executor(sql, params, many, context)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: shop_productitem
</code>```

Thank you so much,
Askew

答: Have you tried deleting every migration from the migrations folder (everyone but the init one), and then running makemigrations and migrate?

Body:
I've deleted a table from the sqlite DDBB because I wanted to make some changes and wasn't able to do those with a simple update of the models in Django. Since then, I am not able to perform migrations again and get a new table for my models, getting the error "django.db.utils.OperationalError: no such table: shop_productitem".

I've tried to follow many hints in other similar threads with no luck. I've tried this and this for example and I cannot solve the issue. My understanding is that if I run makemigrations and then migrate the models the ddbb should update itself with the new specifications, but I'm probably mistaken in this specific case.

Can someone address me where the problem would sit? I fear I have not the necessary knowledge to figure this out of my own, I've been looking for ages.

Please find below the whole error message I'm getting:

    Applying shop.0002_auto_20200218_1958...Traceback (most recent call last):
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: shop_productitem

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 133, in alter_field
    super().alter_field(model, old_field, new_field, strict=strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 509, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 330, in _alter_fi
eld
    self._remake_table(model, alter_field=(old_field, new_field))
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 260, in _remake_t
able
    disable_constraints=False,
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 95, in alter_db_t
able
    super().alter_db_table(model, old_db_table, new_db_table)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 383, in alter_db_tab
le
    "new_table": self.quote_name(new_db_table),
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 117, in execute
    cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrapp
ers
    return executor(sql, params, many, context)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "/home/EconopecoWebApp/.virtualenvs/django2/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: shop_productitem

Thank you so much,
Askew


答:
```<code>foreach($x as $y){
    if($y==0){continue;}
    if($y==1){continue;}
    if($y==2){continue;}
    if($y==3){continue;} }
</code>```

<p>?</p>

Title: PHP encourage loop part way through the loop

Body:
foreach($x as $y){
    if($y==0){continue;}
    if($y==1){continue;}
    if($y==2){continue;}
    if($y==3){continue;} }

?


问:
Nested if loop not firing in python
I have a python question and I can't figure out why this is not firing. Below is the code:

```<code>import re
sfname='C:\python_Script\Testmain.txt'
i=0
Var1='AS'
Var2=''
Var3=''

with open("C:\python_Script\Testmain.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
        if line.startswith('create view [dbo].'):
            print (lines[i])
        if not line.startswith('create view [dbo].'):
            lines[i]=lines[i].replace("_"," ")
            lines[i]= re.sub(r"\bid","key",lines[i])
            Var2=lines[i]
            Var2=re.sub(r"\bkey","Dimension",Var2)
            if not line.endswith("Dimension"):
                Var2='Fact Table'
            Var3=lines[i] +"    "+Var1+"    "+Var2

            print(Var3)
        i+=1
</code>```

the text file I'm reading from is relatively simple it has these attributes in it:

```<code>create view [dbo].Ignore_table
communication_channel_id
user_id
bounce_count
assignment_override_id
create view [dbo].test1
id
test1
</code>```

basically I want to ignore anything with 'create view[dbo].' and create a print statement which replaces the word 'ID' with 'Key' adds an AS and then does 1 of 2 things:
if) Var2 ends with 'Key' replace with the word 'Dimension'.
if) var2 does not end with 'Key' then rename the whole thing 'Fact table'

but for some reason this second if the loop will fire even if it does not end with 'dimension' and it will always be 'Fact Table' Why?

答:
there is some couple of variable that you do not need, like for example your variable i and the list lines which you are using them to manipulate the value of variable line during one-time iteration inside your for loop, you can use the variable line without keeping her value in a list; also you have to care that at the end of each line is the new line character \n

regarding your issue, why Var2 value is always 'Fact Table' is mainly because you are looking in the variable line instead of looking in the variable Var2 which you are modifying

here is a version of what you are trying to achive:

```<code>sfname='C:\python_Script\Testmain.txt'
Var1='AS'
Var2=''
Var3=''

with open(sfname) as file_in:
    for line in file_in:
        line = line.strip()
        if line.startswith('create view [dbo].'):
            print(line)

        else:
            line = line.replace("_", " ")

            # replaces the word 'ID' with 'Key'
            line = line.replace("id","key")
            Var2 = line

            # if) Var2 ends with 'Key' replace with the word 'Dimension'.
            if Var2.endswith("key"):
                Var2 = 'Dimension'
            else:
                Var2 = 'Fact Table'

            Var3 = line + "    " + Var1 + "    " + Var2

            print(Var3)
</code>```

output:

```<code>create view [dbo].Ignore_table
communication channel key    AS    Dimension
user key    AS    Dimension
bounce count    AS    Fact Table
assignment overrkeye key    AS    Dimension
create view [dbo].test1
key    AS    Dimension
test1    AS    Fact Table
</code>```

Title: Nested if loop not firing in python

Body:
I have a python question and I can't figure out why this is not firing. Below is the code:

import re
sfname='C:\python_Script\Testmain.txt'
i=0
Var1='AS'
Var2=''
Var3=''

with open("C:\python_Script\Testmain.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
        if line.startswith('create view [dbo].'):
            print (lines[i])
        if not line.startswith('create view [dbo].'):
            lines[i]=lines[i].replace("_"," ")
            lines[i]= re.sub(r"\bid","key",lines[i])
            Var2=lines[i]
            Var2=re.sub(r"\bkey","Dimension",Var2)
            if not line.endswith("Dimension"):
                Var2='Fact Table'
            Var3=lines[i] +"    "+Var1+"    "+Var2

            print(Var3)
        i+=1

the text file I'm reading from is relatively simple it has these attributes in it:

create view [dbo].Ignore_table
communication_channel_id
user_id
bounce_count
assignment_override_id
create view [dbo].test1
id
test1

basically I want to ignore anything with 'create view[dbo].' and create a print statement which replaces the word 'ID' with 'Key' adds an AS and then does 1 of 2 things:
if) Var2 ends with 'Key' replace with the word 'Dimension'.
if) var2 does not end with 'Key' then rename the whole thing 'Fact table'

but for some reason this second if the loop will fire even if it does not end with 'dimension' and it will always be 'Fact Table' Why?

Body:
there is some couple of variable that you do not need, like for example your variable i and the list lines which you are using them to manipulate the value of variable line during one-time iteration inside your for loop, you can use the variable line without keeping her value in a list; also you have to care that at the end of each line is the new line character \n

regarding your issue, why Var2 value is always 'Fact Table' is mainly because you are looking in the variable line instead of looking in the variable Var2 which you are modifying

here is a version of what you are trying to achive:

sfname='C:\python_Script\Testmain.txt'
Var1='AS'
Var2=''
Var3=''

with open(sfname) as file_in:
    for line in file_in:
        line = line.strip()
        if line.startswith('create view [dbo].'):
            print(line)

        else:
            line = line.replace("_", " ")

            # replaces the word 'ID' with 'Key'
            line = line.replace("id","key")
            Var2 = line

            # if) Var2 ends with 'Key' replace with the word 'Dimension'.
            if Var2.endswith("key"):
                Var2 = 'Dimension'
            else:
                Var2 = 'Fact Table'

            Var3 = line + "    " + Var1 + "    " + Var2

            print(Var3)

output:

create view [dbo].Ignore_table
communication channel key    AS    Dimension
user key    AS    Dimension
bounce count    AS    Fact Table
assignment overrkeye key    AS    Dimension
create view [dbo].test1
key    AS    Dimension
test1    AS    Fact Table


问:
(Vue.js) error: 'token' is not defined (no-undef) with axios
```<code>axios.post(`${this.url}/auth/login`, {
    email: this.email,
    pw: this.pw
  })
  .then( response => {
    if (response.status === 200) {
      this.$swal('환영합니다!','로그인에 성공하였습니다.','success')
      this.$store.state.login = true
      console.log(response.data.data.x-access-token)
      this.$router.push({ name: 'home' })
    }
  })
  .catch( error => {
    if (error.response.status === 401 || error.response.status === 400) {
      this.$swal('오류','이메일 또는 비밀번호가 올바르지 않습니다.','error')
    }
  })
</code>```

An error occurs when this code is executed.

error: 'token' is not defined (no-undef)

The value of response at login is

```<code>data:
  is_student: true
  is_worker: false
  x-access-token: "token"
message: "로그인 성공."
status: 200
</code>```

But I can't access token by using response.data.data.x-access-token.
 How can I do?

答: You must use: response.data.data['x-access-token']

Body:
axios.post(`${this.url}/auth/login`, {
    email: this.email,
    pw: this.pw
  })
  .then( response => {
    if (response.status === 200) {
      this.$swal('환영합니다!','로그인에 성공하였습니다.','success')
      this.$store.state.login = true
      console.log(response.data.data.x-access-token)
      this.$router.push({ name: 'home' })
    }
  })
  .catch( error => {
    if (error.response.status === 401 || error.response.status === 400) {
      this.$swal('오류','이메일 또는 비밀번호가 올바르지 않습니다.','error')
    }
  })

An error occurs when this code is executed.

error: 'token' is not defined (no-undef)

The value of response at login is

data:
  is_student: true
  is_worker: false
  x-access-token: "token"
message: "로그인 성공."
status: 200

But I can't access token by using response.data.data.x-access-token.
 How can I do?


问:
How do I remove a temporary folder on exit in groovy?
I am looking for a solution that would recursively remove a folder created with Files.createTempDirectory() when my (Jenkins) Groovy script ends.

If you read the documentation createTempDirectory() does not remove folder and even if you try to use the delete-on-exit, it will fail if the folder has other files inside.

Please note that I am looking for a solution that would not have to add extra code at the end of the Groovy script or to add try/catch methods. That's because these Groovy codes are compiled from multiple re-usable parts.

A working solution should not need to add extra code at the end of the script, probably using a hooking mechanism to register the directory removal operation.

```<code>import java.nio.file.Files
x = Files.createTempDirectory()
// <-- add some magic hook to tell to remove 'x' folder recursively on exit
// a lot of code I cannot touch
</code>```

References

Does Files.createTempDirectory remove the directory after JVM exits normally?

答:
How about finally?

```<code>def tmp = Files.createTempDirectory()
try {
  // do something with tmp
}
finally {
  tmp.toFile().deleteDir()
}
</code>```

Body:
I am looking for a solution that would recursively remove a folder created with Files.createTempDirectory() when my (Jenkins) Groovy script ends.

If you read the documentation createTempDirectory() does not remove folder and even if you try to use the delete-on-exit, it will fail if the folder has other files inside.

Please note that I am looking for a solution that would not have to add extra code at the end of the Groovy script or to add try/catch methods. That's because these Groovy codes are compiled from multiple re-usable parts.

A working solution should not need to add extra code at the end of the script, probably using a hooking mechanism to register the directory removal operation.

import java.nio.file.Files
x = Files.createTempDirectory()
// <-- add some magic hook to tell to remove 'x' folder recursively on exit
// a lot of code I cannot touch

References

Does Files.createTempDirectory remove the directory after JVM exits normally?

Body:
How about finally?

def tmp = Files.createTempDirectory()
try {
  // do something with tmp
}
finally {
  tmp.toFile().deleteDir()
}


问:
openlink virtuoso installation ./config throwing error
I'm trying to install virtuoso's stable/7 branch manually from https://github.com/openlink/virtuoso-opensource. However, when I run ./configure, I get this error message after about 30 seconds:

checking OpenSSL version... configure: error: OpenSSL version 0.9.8e or greater is required.

The thing is, I do have OpenSSL. When I type openssl version -a in my terminal, I get this output:

benjhatch@benjamins-mbp virtuoso-opensource-stable-7 % openssl version -a

LibreSSL 2.8.3

built on: date not available

platform: information not available

options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)

compiler: information not available

OPENSSLDIR: "/private/etc/ssl"

Why is it saying I need an openssl version of 0.9.8e or greater? Is there any way to fix this?
This is on a Mac that runs MacOS Catalina version 10.15.3.

答:
The issues has been resolved in the default Virtuoso open source develop/7 branch from:

```<code>https://github.com/openlink/virtuoso-opensource/tree/develop/7
</code>```

which now supports LibreSSL  which is what is shipped as the only SSL library available for the the latest macOS versions ...

Body:
The issues has been resolved in the default Virtuoso open source develop/7 branch from:

https://github.com/openlink/virtuoso-opensource/tree/develop/7

which now supports LibreSSL  which is what is shipped as the only SSL library available for the the latest macOS versions ...


问:
How to convert a (x, y) position to an angle in PHP?
Using PHP 7.3,

I have the position of a point with X-Y coordinates that I need to convert to an angle from 0 to 360.

Assuming (123, 0) is angle 0, (0, 123) is angle 90, (-123, 0) is angle 180, etc.

Is there some function to do that ?

Thx.

答:
I wrote that:</p>

```<code>$angle = 180 * atan2($y, $x) / M_PI;
if($angle < 0) {
  $angle += 360;
}
</code>```

Body:
I wrote that:

$angle = 180 * atan2($y, $x) / M_PI;
if($angle < 0) {
  $angle += 360;
}


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答:
Here are some procedures I made to handle checking the duration of a function. I stuck them in a unit I called uTesting and then just throw into the uses clause during my testing.

Declaration

```<code>  Procedure TST_StartTiming(Index : Integer = 1);
    //Starts the timer by storing now in Time
    //Index is the index of the timer to use. 100 are available

  Procedure TST_StopTiming(Index : Integer = 1;Display : Boolean = True; DisplaySM : Boolean = False);
    //Stops the timer and stores the difference between time and now into time
    //Displays the result if Display is true
    //Index is the index of the timer to use. 100 are available

  Procedure TST_ShowTime(Index : Integer = 1;Detail : Boolean = True; DisplaySM : Boolean = False);
    //In a ShowMessage displays time
    //Uses DateTimeToStr if Detail is false else it breaks it down (H,M,S,MS)
    //Index is the index of the timer to use. 100 are available
</code>```

variables declared

```<code>var
  Time : array[1..100] of TDateTime;
</code>```

Implementation

```<code>  Procedure TST_StartTiming(Index : Integer = 1);
  begin
    Time[Index] := Now;
  end;

  Procedure TST_StopTiming(Index : Integer = 1;Display : Boolean = True; DisplaySM : Boolean = False);
  begin
    Time[Index] := Now - Time[Index];
    if Display then TST_ShowTime;
  end;

  Procedure TST_ShowTime(Index : Integer = 1;Detail : Boolean = True; DisplaySM : Boolean = False);
  var
    H,M,S,MS : Word;
  begin
    if Detail then
      begin
        DecodeTime(Time[Index],H,M,S,MS);
        if DisplaySM then
        ShowMessage('Hour   =   ' + FloatToStr(H)  + #13#10 +
                    'Min     =   ' + FloatToStr(M)  + #13#10 +
                    'Sec      =   ' + FloatToStr(S)  + #13#10 +
                    'MS      =   ' + FloatToStr(MS) + #13#10)
        else
        OutputDebugString(PChar('Hour   =   ' + FloatToStr(H)  + #13#10 +
                    'Min     =   ' + FloatToStr(M)  + #13#10 +
                    'Sec      =   ' + FloatToStr(S)  + #13#10 +
                    'MS      =   ' + FloatToStr(MS) + #13#10));
      end
    else
      ShowMessage(TimeToStr(Time[Index]));
      OutputDebugString(Pchar(TimeToStr(Time[Index])));
  end;
</code>```

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.

Body:
Here are some procedures I made to handle checking the duration of a function. I stuck them in a unit I called uTesting and then just throw into the uses clause during my testing.

Declaration

  Procedure TST_StartTiming(Index : Integer = 1);
    //Starts the timer by storing now in Time
    //Index is the index of the timer to use. 100 are available

  Procedure TST_StopTiming(Index : Integer = 1;Display : Boolean = True; DisplaySM : Boolean = False);
    //Stops the timer and stores the difference between time and now into time
    //Displays the result if Display is true
    //Index is the index of the timer to use. 100 are available

  Procedure TST_ShowTime(Index : Integer = 1;Detail : Boolean = True; DisplaySM : Boolean = False);
    //In a ShowMessage displays time
    //Uses DateTimeToStr if Detail is false else it breaks it down (H,M,S,MS)
    //Index is the index of the timer to use. 100 are available

variables declared

var
  Time : array[1..100] of TDateTime;

Implementation

  Procedure TST_StartTiming(Index : Integer = 1);
  begin
    Time[Index] := Now;
  end;

  Procedure TST_StopTiming(Index : Integer = 1;Display : Boolean = True; DisplaySM : Boolean = False);
  begin
    Time[Index] := Now - Time[Index];
    if Display then TST_ShowTime;
  end;

  Procedure TST_ShowTime(Index : Integer = 1;Detail : Boolean = True; DisplaySM : Boolean = False);
  var
    H,M,S,MS : Word;
  begin
    if Detail then
      begin
        DecodeTime(Time[Index],H,M,S,MS);
        if DisplaySM then
        ShowMessage('Hour   =   ' + FloatToStr(H)  + #13#10 +
                    'Min     =   ' + FloatToStr(M)  + #13#10 +
                    'Sec      =   ' + FloatToStr(S)  + #13#10 +
                    'MS      =   ' + FloatToStr(MS) + #13#10)
        else
        OutputDebugString(PChar('Hour   =   ' + FloatToStr(H)  + #13#10 +
                    'Min     =   ' + FloatToStr(M)  + #13#10 +
                    'Sec      =   ' + FloatToStr(S)  + #13#10 +
                    'MS      =   ' + FloatToStr(MS) + #13#10));
      end
    else
      ShowMessage(TimeToStr(Time[Index]));
      OutputDebugString(Pchar(TimeToStr(Time[Index])));
  end;


问:
how can I convert rows with date range to rows with each date in rage?
Lets say I have the following data pulled from a database:

```<code>data = [
    {'db_id': 1, 'start': '2020-02-02', 'end': '2020-02-05'},
    {'db_id': 2, 'start': '2020-02-04', 'end': '2020-02-06'},
    {'db_id': 3, 'start': '2020-02-02', 'end': '2020-02-04'}
]
df = pd.DataFrame(data)
</code>```

I want to convert this into a row for each date/db_id combination, inclusive of the start and end date.  So I want to end up with the following DataFrame:

```<code>result_data = [
    {'db_id': 1, 'date': '2020-02-02'},
    {'db_id': 1, 'date': '2020-02-03'},
    {'db_id': 1, 'date': '2020-02-04'},
    {'db_id': 1, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-04'},
    {'db_id': 2, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-06'},
    {'db_id': 3, 'date': '2020-02-02'},
    {'db_id': 3, 'date': '2020-02-03'},
    {'db_id': 3, 'date': '2020-02-04'},
]

result_df = pd.DataFrame(result_data)
</code>```

What is an efficient way to do this in pandas (the data set has several hundred thousand rows).

答:
You can do resample, but first you need to make sure that your date are of datetime type:

```<code>df['start'], df['end'] = pd.to_datetime(df['start']), pd.to_datetime(df['end'])

(df.melt(id_vars='db_id', value_name='date')
   .set_index('date')
   .groupby('db_id')['variable'].resample('D').ffill()
   .reset_index()
   .drop('variable',axis=1)
)
</code>```

Output:

```<code>   db_id       date
0      1 2020-02-02
1      1 2020-02-03
2      1 2020-02-04
3      1 2020-02-05
4      2 2020-02-04
5      2 2020-02-05
6      2 2020-02-06
7      3 2020-02-02
8      3 2020-02-03
</code>```

Or you can also do a simple for loop:

```<code>pd.concat(pd.DataFrame({'db_id':x['db_id'],
                        'date':pd.date_range(x['start'], x['end'], freq='D')}
                        )
          for _, x in df.iterrows()
         )
</code>```

Body:
Lets say I have the following data pulled from a database:

data = [
    {'db_id': 1, 'start': '2020-02-02', 'end': '2020-02-05'},
    {'db_id': 2, 'start': '2020-02-04', 'end': '2020-02-06'},
    {'db_id': 3, 'start': '2020-02-02', 'end': '2020-02-04'}
]
df = pd.DataFrame(data)

I want to convert this into a row for each date/db_id combination, inclusive of the start and end date.  So I want to end up with the following DataFrame:

result_data = [
    {'db_id': 1, 'date': '2020-02-02'},
    {'db_id': 1, 'date': '2020-02-03'},
    {'db_id': 1, 'date': '2020-02-04'},
    {'db_id': 1, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-04'},
    {'db_id': 2, 'date': '2020-02-05'},
    {'db_id': 2, 'date': '2020-02-06'},
    {'db_id': 3, 'date': '2020-02-02'},
    {'db_id': 3, 'date': '2020-02-03'},
    {'db_id': 3, 'date': '2020-02-04'},
]

result_df = pd.DataFrame(result_data)

What is an efficient way to do this in pandas (the data set has several hundred thousand rows).

Body:
You can do resample, but first you need to make sure that your date are of datetime type:

df['start'], df['end'] = pd.to_datetime(df['start']), pd.to_datetime(df['end'])

(df.melt(id_vars='db_id', value_name='date')
   .set_index('date')
   .groupby('db_id')['variable'].resample('D').ffill()
   .reset_index()
   .drop('variable',axis=1)
)

Output:

   db_id       date
0      1 2020-02-02
1      1 2020-02-03
2      1 2020-02-04
3      1 2020-02-05
4      2 2020-02-04
5      2 2020-02-05
6      2 2020-02-06
7      3 2020-02-02
8      3 2020-02-03

Or you can also do a simple for loop:

pd.concat(pd.DataFrame({'db_id':x['db_id'],
                        'date':pd.date_range(x['start'], x['end'], freq='D')}
                        )
          for _, x in df.iterrows()
         )


问:
Initialising darknet opencv
I get this error when trying to initialize darknet.

Error: Assertion failed (separator_index < line.size()) in cv::dnn::darknet::ReadDarknetFromCfgStream, file c:\build\master_winpack-build-win64-vc15\opencv\modules\dnn\src\darknet\darknet_io.cpp, line 507

Anyone know what may be happening?

I'm using yolov3.weights and yolov3.cfg

piece of code below.

I've tried absolute file paths

```<code>// Load names of classes
string classesFile = "B:/coco.names";
ifstream ifs(classesFile.c_str());
string line;
while (getline(ifs, line)) classes.push_back(line);

// Give the configuration and weight files for the model
String modelConfiguration = "B:/yolov3a.cfg";
String modelWeights = "B:/yolov3.weights";

// Load the network
Net net = readNetFromDarknet(modelConfiguration, modelWeights);
net.setPreferableBackend(DNN_BACKEND_OPENCV);
net.setPreferableTarget(DNN_TARGET_CPU);

//---------------

return 0;
</code>```

Any help is appreciated

答:
Line parser in darknet_io.cpp seems to fail if there are commented lines without whitespace immidiately after the '#' in the .cfg file.</p>

```<code>[net]
# This is OK!
# Testing
# batch=1
# subdivisions=1
# Training
batch=64
subdivisions=16
width=416
height=416
...

[net]
#This would FAIL!
#batch=1
#subdivisions=1
#Training
batch=64
...
</code>```

Title: Initialising darknet opencv

Body:
I get this error when trying to initialize darknet.

Error: Assertion failed (separator_index < line.size()) in cv::dnn::darknet::ReadDarknetFromCfgStream, file c:\build\master_winpack-build-win64-vc15\opencv\modules\dnn\src\darknet\darknet_io.cpp, line 507

Anyone know what may be happening?

I'm using yolov3.weights and yolov3.cfg

piece of code below.

I've tried absolute file paths

// Load names of classes
string classesFile = "B:/coco.names";
ifstream ifs(classesFile.c_str());
string line;
while (getline(ifs, line)) classes.push_back(line);

// Give the configuration and weight files for the model
String modelConfiguration = "B:/yolov3a.cfg";
String modelWeights = "B:/yolov3.weights";

// Load the network
Net net = readNetFromDarknet(modelConfiguration, modelWeights);
net.setPreferableBackend(DNN_BACKEND_OPENCV);
net.setPreferableTarget(DNN_TARGET_CPU);

//---------------

return 0;

Any help is appreciated

Body:
Line parser in darknet_io.cpp seems to fail if there are commented lines without whitespace immidiately after the '#' in the .cfg file.

[net]
# This is OK!
# Testing
# batch=1
# subdivisions=1
# Training
batch=64
subdivisions=16
width=416
height=416
...

[net]
#This would FAIL!
#batch=1
#subdivisions=1
#Training
batch=64
...


问:
Making adjacency matrix using group information
I am relatively new to R and I am have issues in creating an adjacency matrix using group characteristics.

I have a data frame that looks like this:

```<code>distid villageid  hhid group1 group2 group3 group4
1        1         111  0        1     0        0
1        1         112  1        1     1        0
1        2         121  1        1     0        1
1        2         122  1        0     0        1
2        1         211  1        1     0        0
2        1         212  1        1     1        1
2        2         221  0        0     1        0
2        2         222  0        1     1        0
</code>```

I need to create an adjacency matrix where if a hhid is in the same distid, villageid and group then they are all fully connected.

So my final matrix should look something like this

```<code>hhid  111    112  121   122    211   212   221 222
111    0     1     0     0       0    0     0   0
112    1     0     0     0       0    0     0   0
121    0     0     0     1       0    0     0   0
122    0     0     0     0       0    0     0   0
211    0     0     0     0       0    1     0   0
212    0     0     0     0       1    0     0   0
221    0     0     0     0       0    0     0   1
222    0     0     0     0       0    0     1   0
</code>```

答:
We assume that what is wanted is that two elements are regarded as adjacent if they are in the same group, dist and village.

Using the input in the Note create the adjacency matrices for groups, for distid and for villageid and then multiply them together and zero out the diagonal.

```<code>m1 <- sign(crossprod(t(DF[-(1:3)])))
m2 <- +outer(DF$distid, DF$distid, "==")
m3 <- +outer(DF$villageid, DF$villageid, "==")
m4 <- 1 - diag(nrow(DF))
m <- m1 * m2 * m3 * m4
dimnames(m) <- list(DF$hhid, DF$hhid)
</code>```

giving:

```<code>> m
    111 112 121 122 211 212 221 222
111   0   1   0   0   0   0   0   0
112   1   0   0   0   0   0   0   0
121   0   0   0   1   0   0   0   0
122   0   0   1   0   0   0   0   0
211   0   0   0   0   0   1   0   0
212   0   0   0   0   1   0   0   0
221   0   0   0   0   0   0   0   1
222   0   0   0   0   0   0   1   0
</code>```

Graph

```<code>library(igraph)
g <- graph_from_adjacency_matrix(m)
plot(g)
</code>```

Note

The input in reproducible form.

```<code>Lines <- "distid villageid  hhid group1 group2 group3 group4
1        1         111  0        1     0        0
1        1         112  1        1     1        0
1        2         121  1        1     0        1
1        2         122  1        0     0        1
2        1         211  1        1     0        0
2        1         212  1        1     1        1
2        2         221  0        0     1        0
2        2         222  0        1     1        0"
DF <- read.table(text = Lines, header = TRUE)
</code>```

Body:
I am relatively new to R and I am have issues in creating an adjacency matrix using group characteristics.

I have a data frame that looks like this:

distid villageid  hhid group1 group2 group3 group4
1        1         111  0        1     0        0
1        1         112  1        1     1        0
1        2         121  1        1     0        1
1        2         122  1        0     0        1
2        1         211  1        1     0        0
2        1         212  1        1     1        1
2        2         221  0        0     1        0
2        2         222  0        1     1        0

I need to create an adjacency matrix where if a hhid is in the same distid, villageid and group then they are all fully connected.

So my final matrix should look something like this

hhid  111    112  121   122    211   212   221 222
111    0     1     0     0       0    0     0   0
112    1     0     0     0       0    0     0   0
121    0     0     0     1       0    0     0   0
122    0     0     0     0       0    0     0   0
211    0     0     0     0       0    1     0   0
212    0     0     0     0       1    0     0   0
221    0     0     0     0       0    0     0   1
222    0     0     0     0       0    0     1   0

Body:
We assume that what is wanted is that two elements are regarded as adjacent if they are in the same group, dist and village.

Using the input in the Note create the adjacency matrices for groups, for distid and for villageid and then multiply them together and zero out the diagonal.

m1 <- sign(crossprod(t(DF[-(1:3)])))
m2 <- +outer(DF$distid, DF$distid, "==")
m3 <- +outer(DF$villageid, DF$villageid, "==")
m4 <- 1 - diag(nrow(DF))
m <- m1 * m2 * m3 * m4
dimnames(m) <- list(DF$hhid, DF$hhid)

giving:

> m
    111 112 121 122 211 212 221 222
111   0   1   0   0   0   0   0   0
112   1   0   0   0   0   0   0   0
121   0   0   0   1   0   0   0   0
122   0   0   1   0   0   0   0   0
211   0   0   0   0   0   1   0   0
212   0   0   0   0   1   0   0   0
221   0   0   0   0   0   0   0   1
222   0   0   0   0   0   0   1   0

Graph

library(igraph)
g <- graph_from_adjacency_matrix(m)
plot(g)

Note

The input in reproducible form.

Lines <- "distid villageid  hhid group1 group2 group3 group4
1        1         111  0        1     0        0
1        1         112  1        1     1        0
1        2         121  1        1     0        1
1        2         122  1        0     0        1
2        1         211  1        1     0        0
2        1         212  1        1     1        1
2        2         221  0        0     1        0
2        2         222  0        1     1        0"
DF <- read.table(text = Lines, header = TRUE)


问:
Get value from a XML
I have a XML .How to get CustomerSet value from this ?</p>

```<code><a:CreditCards>
 <a:CreditCard>
  <a:AccountNumber>1234XXXXXX23XXXX</a:AccountNumber>
 <a:ExtendedInfo>
  <a:CustomerSet>RC808687</a:CustomerSet>
 </a:ExtendedInfo>
 </a:CreditCard>
<a:CreditCards>
</code>```

答:
Have a look at this</p>

```<code>XmlDocument xml = new XmlDocument();
            xml.LoadXml("<CreditCards>  <CreditCard>   <AccountNumber>1234XXXXXX23XXXX</AccountNumber>   <ExtendedInfo>   <CustomerSet>RC808687</CustomerSet>   </ExtendedInfo>  </CreditCard> </CreditCards> ");
            XmlNodeList xmlList = xml.SelectNodes("/CreditCards/CreditCard/ExtendedInfo/CustomerSet");
</code>```

Title: Get value from a XML

Body:
I have a XML .How to get CustomerSet value from this ?

  1234XXXXXX23XXXX

  RC808687

Body:
Have a look at this

XmlDocument xml = new XmlDocument();
            xml.LoadXml("<CreditCards>  <CreditCard>   <AccountNumber>1234XXXXXX23XXXX</AccountNumber>   <ExtendedInfo>   <CustomerSet>RC808687</CustomerSet>   </ExtendedInfo>  </CreditCard> </CreditCards> ");
            XmlNodeList xmlList = xml.SelectNodes("/CreditCards/CreditCard/ExtendedInfo/CustomerSet");


问:
How to import jspdf-autotable in Vue main.js?
I searched all over the internet but found nothing. I know this is a noob question.

I installed jspdf and jspdf-autotable over npm in my vue project:

```<code>npm install jspdf --save
npm install jspdf-autotables --save
</code>```

Packages installed successfully. I'm importing jspdf and jspdf-autotable in main.js file like that:

```<code>import jsPDF from 'jspdf';
import 'jspdf-autotable';

Vue.use(jsPDF)
</code>```

Then in my .vue file I import jsPDF first:

```<code>import jsPDF from 'jspdf';
</code>```

and then in mounted() hook:

```<code>let doc = new jsPDF();
doc.autoTable({ html: '#my-table' });
doc.save('table.pdf');
</code>```

But autoTable is not imported. It says unresolved method or hook autotable. I get empty pdf.

I don't know how to import autoTable. Please help me. It's one day left to finish my job. Sorry I'm new to Vue js. Many thanks in advance!

答:
you don't need the imports in the main.js file.

Do you import directly in your .vue file. that work well.

```<code>import jsPDF from 'jspdf'
import 'jspdf-autotable'
</code>```

and then in mounted() hook:

```<code>let doc = new jsPDF();
doc.autoTable({ html: '#my-table' });
doc.save('table.pdf');
</code>```

Body:
I searched all over the internet but found nothing. I know this is a noob question.

I installed jspdf and jspdf-autotable over npm in my vue project:

npm install jspdf --save
npm install jspdf-autotables --save

Packages installed successfully. I'm importing jspdf and jspdf-autotable in main.js file like that:

import jsPDF from 'jspdf';
import 'jspdf-autotable';

Vue.use(jsPDF)

Then in my .vue file I import jsPDF first:

import jsPDF from 'jspdf';

and then in mounted() hook:

let doc = new jsPDF();
doc.autoTable({ html: '#my-table' });
doc.save('table.pdf');

But autoTable is not imported. It says unresolved method or hook autotable. I get empty pdf.

I don't know how to import autoTable. Please help me. It's one day left to finish my job. Sorry I'm new to Vue js. Many thanks in advance!

Body:
you don't need the imports in the main.js file.

Do you import directly in your .vue file. that work well.

import jsPDF from 'jspdf'
import 'jspdf-autotable'

and then in mounted() hook:

let doc = new jsPDF();
doc.autoTable({ html: '#my-table' });
doc.save('table.pdf');


问:
Extending the HTML 5/JavaScript input validation API
I'm to work with with the HTML 5 validation on an input type number field, that uses min and step attributes, and an initial value, i.e.,

```<code><input type="number" min="50" step="50" value="100" />
</code>```

However, I want the validation to allow the user to enter values that are greater than the min, but between the steps, here shown in bold:

    50, 51 ... 99, 100, 101 ... 149, 150, 151 ...

Can I somehow 'hook' into the validation API after it has performed its work, and if the only error that it finds is a step error, reset the valid condition so that the form that it the field is in can be submitted?

Sure would be nice if besides a message string parameter, the element.setCustomValidity() function could also accept a callback function that returned a empty string if the element's value passed the check(s) in the callback function or return a non-empty message string if the value didn't pass.

答:
You can work with a text input and use a pattern attribute that uses a Regular Expression (RegExp) to validate its values like so:

```<code><form>
    <input type="text" pattern="(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)" title="Invalid values" required>
</form>
</code>```

Edit 1: Since you don't want to change the input type this may be the solution (using the same RegEx):

```<code><script>
    window.validate50 = function(ev){
        var tar = ev.target || ev;

        // tests the value is not a 50 multiple
        if(!/(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)/img.test(tar.value)){

            // in this case triggers the validation using the text on html title attribute
            tar.setCustomValidity(tar.title);

            // returns false so the "submit" action is supressed
            return false;
        }
    };
</script>
<form>
    <input type="number" min="50" step="50" onchange="return validate50(this);" title="The number must not be a multiple of 50!" required>
</form>
</code>```

Body:
I'm to work with with the HTML 5 validation on an input type number field, that uses min and step attributes, and an initial value, i.e.,

<input type="number" min="50" step="50" value="100" />

However, I want the validation to allow the user to enter values that are greater than the min, but between the steps, here shown in bold:

    50, 51 ... 99, 100, 101 ... 149, 150, 151 ...

Can I somehow 'hook' into the validation API after it has performed its work, and if the only error that it finds is a step error, reset the valid condition so that the form that it the field is in can be submitted?

Sure would be nice if besides a message string parameter, the element.setCustomValidity() function could also accept a callback function that returned a empty string if the element's value passed the check(s) in the callback function or return a non-empty message string if the value didn't pass.

Body:
You can work with a text input and use a pattern attribute that uses a Regular Expression (RegExp) to validate its values like so:

<form>
    <input type="text" pattern="(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)" title="Invalid values" required>
</form>

Edit 1: Since you don't want to change the input type this may be the solution (using the same RegEx):

<script>
    window.validate50 = function(ev){
        var tar = ev.target || ev;

        // tests the value is not a 50 multiple
        if(!/(^[6-9][0-9]{1,}$|^[5][1-9]$)|(^((?!00|50|[a-zA-Z]).){3,}$)/img.test(tar.value)){

            // in this case triggers the validation using the text on html title attribute
            tar.setCustomValidity(tar.title);

            // returns false so the "submit" action is supressed
            return false;
        }
    };
</script>
<form>
    <input type="number" min="50" step="50" onchange="return validate50(this);" title="The number must not be a multiple of 50!" required>
</form>