问:
Compact way to produce a large sequence of strings in lexical order
I want to generate a sequence of strings with the following properties:

Lexically ordered

Theoretically infinite

Compact over a realistic range

Generated by a simple process of incrementation

Matches the regexp /\w+/

The obvious way to generate a lexically-ordered sequence is to choose a string length and pad the strings with a base value like this: 000000, 000001, etc. This approach poses a trade-off between the number of permutations and compactness: a string long enough to yield many permutations will be filled many zeros along the way. Plus, the length I choose sets an upper bound on the total number of permutations unless I have some mechanism for expanding the string when it maxes out.

So I came up with a sequence that works like this:

Each string consists of a "head", which is a base-36 number, followed by an underscore, and then the "tail", which is also a base-36 number padded by an increasing number of zeros

The first cycle goes from 0_0 to 0_z

The second cycle goes from 1_00 to 1_zz

The third cycle goes from 2_000 to 2_zzz, and so on

Once the head has reached z and the tail consists of 36 zs, the first "supercycle" has ended. Now the whole sequence starts over, except the z remains at the beginning, so the new cycle starts with z0_0, then continues to z1_00, and so on

The second supercycle goes zz0_0, zz1_00, and so on

Although the string of zs in the head could become unwieldy over the long run, a single supercycle contains over 10^56 permutations, which is far more than I ever expect to use.  The sequence is theoretically infinite but very compact within a realistic range. For instance, the trillionth permutation is a succinct 7_bqd55h8s.

I can generate the sequence relatively simply with this javascript function:

function genStr (n) {
  n = BigInt(n);
  let prefix = "",
      cycle = 0n,
      max = 36n ** (cycle + 1n);
  while (n >= max) {
    n -= max;
    if (cycle === 35n) {
      prefix += "z";
      cycle = 0n;
    } else {
      cycle++;
    }
    max = 36n ** (cycle + 1n);
  }
  return prefix
         + cycle.toString(36)
         + "_"
         + n.toString(36).padStart(Number(cycle) + 1, 0);
}
```

The n parameter is a number that I increment and pass to the function to get the next member of the sequence. All I need to keep track of is a simple integer, making the sequence very easy to use.

So obviously I spent a lot of time on this and I think it's pretty good, but I'm wondering if there is a better way. Is there a good algorithm for generating a sequence along the lines of the one I'm looking for?

答:
After considering the advice provided by @kaya3 and @grodzi and reviewing my original code, I have made some improvements.  I realized a few things:

There was a bug in my original code.  If one cycle ends at z_z (actually 36 z's after the underscore, but you get the idea) and the next one begins at z0_0, then lexical ordering is broken because _ comes after 0. The separator (or "neck") needs to be lower in lexical order than the lowest possible value of the head.

Though I was initially resistant to the idea of rolling a custom baseN generator so that more characters can be included, I have now come around to the idea.

I can squeeze more permutations out of a given string length by also incrementing the neck. For example, I can go from A00...A0z to A10...A1z, and so on, thus increasing the number of unique strings I can generate with A as the head before I move on to B.

With that in mind, I have revised my code:

// this is the alphabet used in standard baseN conversions:

let baseAlpha = "0123456789abcdefghijklmnopqrstuvwxyz";

// this is a factory for creating a new string generator:

function sequenceGenerator (config) {
  let
      // alphabets for the head, neck and body:

      headAlpha = config.headAlpha,
      neckAlpha = config.neckAlpha,
      bodyAlpha = config.bodyAlpha,

      // length of the body alphabet corresponds to the
      // base of the numbering system:

      base = BigInt(bodyAlpha.length),

      // if bodyAlpha is identical to an alphabet that
      // would be used for a standard baseN conversion,
      // then use the built-in method, which should be
      // much faster:

      convertBody = baseAlpha.startsWith(bodyAlpha)
                    ? (n) => n.toString(bodyAlpha.length)

      // otherwise, roll a custom baseN generator:

                    : function (n) {
                        let s = "";
                        while (n > 0n) {
                          let i = n % base;
                          s = bodyAlpha[i] + s;
                          n = n / base;
                        }
                        return s;
                      },

      // n is used to cache the last iteration and is
      // incremented each time you call `getNext`

      // it can optionally be initialized to a value other
      // than 0:

      n = BigInt(config.start || 0),

      // see below:

      headCycles = [0n],
      cycleLength = 0n;

  // the length of the body increases by 1 each time the
  // head increments, meaning that the total number of
  // permutations increases geometrically for each
  // character in headAlpha

  // here we cache the maximum number of permutations for
  // each length of the body

  // since we know these values ahead of time, calculating
  // them in advance saves time when we generate a new
  // string

  // more importantly, it saves us from having to do a
  // reverse calculation involving Math.log, which requires
  // converting BigInts to Numbers, which breaks the
  // program on larger numbers:

  for (let i = 0; i < headAlpha.length; i++) {

    // the maximum number of permutations depends on both
    // the string length (i + 1) and the number of
    // characters in neckAlpha, since the string length
    // remains the same while the neck increments

    cycleLength += BigInt(neckAlpha.length) * base ** BigInt(i + 1);
    headCycles.push(cycleLength);
  }

  // given a number n, this function searches through
  // headCycles to find where the total number of
  // permutations exceeds n

  // this is how we avoid the reverse calculation with
  // Math.log to determine which head cycle we are on for
  // a given permutation:

  function getHeadCycle (n) {
    for (let i = 0; i < headCycles.length; i++) {
      if (headCycles[i] > n) return i;
    }
  }

  return {

    cycleLength: cycleLength,

    getString: function (n) {
      let cyclesDone = Number(n / cycleLength),
          headLast = headAlpha[headAlpha.length - 1],
          prefix = headLast.repeat(cyclesDone),
          nn = n % cycleLength,
          headCycle = getHeadCycle(nn),
          head = headAlpha[headCycle - 1],
          nnn = nn - headCycles[headCycle - 1],
          neckCycleLength = BigInt(bodyAlpha.length) ** BigInt(headCycle),
          neckCycle = nnn / neckCycleLength,
          neck = neckAlpha[Number(neckCycle)],
          body = convertBody(nnn % neckCycleLength);
      body = body.padStart(headCycle , bodyAlpha[0]);
      return prefix + head + neck + body;
    },

    getNext: function () { return this.getString(n++); }

  };
}

let bodyAlpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
    getStr = sequenceGenerator({

      // achieve more permutations within a supercycle
      // with a larger headAlpha:

      headAlpha: "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",

      // the highest value of neckAlpha must be lower than
      // the lowest value of headAlpha:

      neckAlpha: "0",
      bodyAlpha: bodyAlpha
    });

console.log("---supercycle length:");
console.log(Number(getStr.cycleLength));
console.log("---first two values:")
console.log(getStr.getNext());
console.log(getStr.getNext());
console.log("---arbitrary large value (1e57):");
console.log(getStr.getString(BigInt(1e57)));
console.log("");

// here we use a shorter headAlpha and longer neckAlpha
// to shorten the maximum length of the body, but this also
// decreases the number of permutations in the supercycle:

getStr = sequenceGenerator({
  headAlpha: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
  neckAlpha: "0123456789",
  bodyAlpha: bodyAlpha
});

console.log("---supercycle length:");
console.log(Number(getStr.cycleLength));
console.log("---first two values:");
console.log(getStr.getNext());
console.log(getStr.getNext());
console.log("---arbitrary large value (1e57):");
console.log(getStr.getString(BigInt(1e57)));```
</div>
</div>
</p>
<hr />
<p>EDIT</p>
<p>After further discussion with @grodzi, I have made some more improvements:</p>
<ol>
<li>I realized that the "neck" or separator wasn't providing much value, so I have gotten rid of it. <strong>Later edit</strong>: <em>actually, the separator is necessary. I am not sure why I thought it wasn't. Without the separator, the beginning of each new supercycle will lexically precede the end of the previous supercycle. I haven't changed my code below, but anyone using this code should include a separator. I have also realized that I was wrong to use an underscore as the separator. The separator must be a character, such as the hyphen, which lexically precedes the lowest digit used in the sequence (0).</em></li>
<li>I have taken @grodzi's suggestion to allow the length of the tail to continue growing indefinitely.</li>
</ol>
<p>Here is the new code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let baseAlpha = "0123456789abcdefghijklmnopqrstuvwxyz";

function sequenceGenerator (config) {

  let headAlpha = config.headAlpha,
      tailAlpha = config.tailAlpha,
      base = BigInt(tailAlpha.length),
      convertTail = baseAlpha.startsWith(tailAlpha)
                    ? (n) => n.toString(tailAlpha.length)
                    : function (n) {
                        if (n === 0n) return "0";
                        let s = "";
                        while (n > 0n) {
                          let i = n % base;
                          s = tailAlpha[i] + s;
                          n = n / base;
                        }
                        return s;
                      },
      n = BigInt(config.start || 0);

  return {

    getString: function (n) {
      let cyclesDone = 0n,
          headCycle = 0n,
          initLength = 0n,
          accum = 0n;
      for (;; headCycle++) {
        let _accum = accum + base ** (headCycle + 1n + initLength);
        if (_accum > n) {
          n -= accum;
          break;
        } else if (Number(headCycle) === headAlpha.length - 1) {
          cyclesDone++;
          initLength += BigInt(headAlpha.length);
          headCycle = -1n;
        }
        accum = _accum;
      }
      let headLast = headAlpha[headAlpha.length - 1],
          prefix = headLast.repeat(Number(cyclesDone)),
          head = headAlpha[Number(headCycle)],
          tail = convertTail(n),
          tailLength = Number(headCycle + initLength);
      tail = tail.padStart(tailLength, tailAlpha[0]);
      return prefix + head + tail;
    },

    getNext: function () { return this.getString(n++); }

  };
}

let alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
    genStr = sequenceGenerator({headAlpha: alpha, tailAlpha: alpha});

console.log("--- first string:");
console.log(genStr.getString(0n));
console.log("--- 1e+57");
console.log(genStr.getString(BigInt(1e+57)));
console.log("--- end of first supercycle:");
console.log(genStr.getString(63n*(1n-(63n**63n))/(1n-63n)-1n));
console.log("--- start of second supercycle:");
console.log(genStr.getString(63n*(1n-(63n**63n))/(1n-63n)));</code>```

Body:
I want to generate a sequence of strings with the following properties:

Lexically ordered

Theoretically infinite

Compact over a realistic range

Generated by a simple process of incrementation

Matches the regexp /\w+/

The obvious way to generate a lexically-ordered sequence is to choose a string length and pad the strings with a base value like this: 000000, 000001, etc. This approach poses a trade-off between the number of permutations and compactness: a string long enough to yield many permutations will be filled many zeros along the way. Plus, the length I choose sets an upper bound on the total number of permutations unless I have some mechanism for expanding the string when it maxes out.

So I came up with a sequence that works like this:

Each string consists of a "head", which is a base-36 number, followed by an underscore, and then the "tail", which is also a base-36 number padded by an increasing number of zeros

The first cycle goes from 0_0 to 0_z

The second cycle goes from 1_00 to 1_zz

The third cycle goes from 2_000 to 2_zzz, and so on

Once the head has reached z and the tail consists of 36 zs, the first "supercycle" has ended. Now the whole sequence starts over, except the z remains at the beginning, so the new cycle starts with z0_0, then continues to z1_00, and so on

The second supercycle goes zz0_0, zz1_00, and so on

Although the string of zs in the head could become unwieldy over the long run, a single supercycle contains over 10^56 permutations, which is far more than I ever expect to use.  The sequence is theoretically infinite but very compact within a realistic range. For instance, the trillionth permutation is a succinct 7_bqd55h8s.

I can generate the sequence relatively simply with this javascript function:

function genStr (n) {
  n = BigInt(n);
  let prefix = "",
      cycle = 0n,
      max = 36n ** (cycle + 1n);
  while (n >= max) {
    n -= max;
    if (cycle === 35n) {
      prefix += "z";
      cycle = 0n;
    } else {
      cycle++;
    }
    max = 36n ** (cycle + 1n);
  }
  return prefix
         + cycle.toString(36)
         + "_"
         + n.toString(36).padStart(Number(cycle) + 1, 0);
}

The n parameter is a number that I increment and pass to the function to get the next member of the sequence. All I need to keep track of is a simple integer, making the sequence very easy to use.

So obviously I spent a lot of time on this and I think it's pretty good, but I'm wondering if there is a better way. Is there a good algorithm for generating a sequence along the lines of the one I'm looking for?

Body:
After considering the advice provided by @kaya3 and @grodzi and reviewing my original code, I have made some improvements.  I realized a few things:

There was a bug in my original code.  If one cycle ends at z_z (actually 36 z's after the underscore, but you get the idea) and the next one begins at z0_0, then lexical ordering is broken because _ comes after 0. The separator (or "neck") needs to be lower in lexical order than the lowest possible value of the head.

Though I was initially resistant to the idea of rolling a custom baseN generator so that more characters can be included, I have now come around to the idea.

I can squeeze more permutations out of a given string length by also incrementing the neck. For example, I can go from A00...A0z to A10...A1z, and so on, thus increasing the number of unique strings I can generate with A as the head before I move on to B.

With that in mind, I have revised my code:

// this is the alphabet used in standard baseN conversions:

let baseAlpha = "0123456789abcdefghijklmnopqrstuvwxyz";

// this is a factory for creating a new string generator:

function sequenceGenerator (config) {
  let
      // alphabets for the head, neck and body:

      headAlpha = config.headAlpha,
      neckAlpha = config.neckAlpha,
      bodyAlpha = config.bodyAlpha,

      // length of the body alphabet corresponds to the
      // base of the numbering system:

      base = BigInt(bodyAlpha.length),

      // if bodyAlpha is identical to an alphabet that
      // would be used for a standard baseN conversion,
      // then use the built-in method, which should be
      // much faster:

      convertBody = baseAlpha.startsWith(bodyAlpha)
                    ? (n) => n.toString(bodyAlpha.length)

      // otherwise, roll a custom baseN generator:

                    : function (n) {
                        let s = "";
                        while (n > 0n) {
                          let i = n % base;
                          s = bodyAlpha[i] + s;
                          n = n / base;
                        }
                        return s;
                      },

      // n is used to cache the last iteration and is
      // incremented each time you call `getNext`

      // it can optionally be initialized to a value other
      // than 0:

      n = BigInt(config.start || 0),

      // see below:

      headCycles = [0n],
      cycleLength = 0n;

  // the length of the body increases by 1 each time the
  // head increments, meaning that the total number of
  // permutations increases geometrically for each
  // character in headAlpha

  // here we cache the maximum number of permutations for
  // each length of the body

  // since we know these values ahead of time, calculating
  // them in advance saves time when we generate a new
  // string

  // more importantly, it saves us from having to do a
  // reverse calculation involving Math.log, which requires
  // converting BigInts to Numbers, which breaks the
  // program on larger numbers:

  for (let i = 0; i < headAlpha.length; i++) {

    // the maximum number of permutations depends on both
    // the string length (i + 1) and the number of
    // characters in neckAlpha, since the string length
    // remains the same while the neck increments

    cycleLength += BigInt(neckAlpha.length) * base ** BigInt(i + 1);
    headCycles.push(cycleLength);
  }

  // given a number n, this function searches through
  // headCycles to find where the total number of
  // permutations exceeds n

  // this is how we avoid the reverse calculation with
  // Math.log to determine which head cycle we are on for
  // a given permutation:

  function getHeadCycle (n) {
    for (let i = 0; i < headCycles.length; i++) {
      if (headCycles[i] > n) return i;
    }
  }

  return {

    cycleLength: cycleLength,

    getString: function (n) {
      let cyclesDone = Number(n / cycleLength),
          headLast = headAlpha[headAlpha.length - 1],
          prefix = headLast.repeat(cyclesDone),
          nn = n % cycleLength,
          headCycle = getHeadCycle(nn),
          head = headAlpha[headCycle - 1],
          nnn = nn - headCycles[headCycle - 1],
          neckCycleLength = BigInt(bodyAlpha.length) ** BigInt(headCycle),
          neckCycle = nnn / neckCycleLength,
          neck = neckAlpha[Number(neckCycle)],
          body = convertBody(nnn % neckCycleLength);
      body = body.padStart(headCycle , bodyAlpha[0]);
      return prefix + head + neck + body;
    },

    getNext: function () { return this.getString(n++); }

  };
}

let bodyAlpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
    getStr = sequenceGenerator({

      // achieve more permutations within a supercycle
      // with a larger headAlpha:

      headAlpha: "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",

      // the highest value of neckAlpha must be lower than
      // the lowest value of headAlpha:

      neckAlpha: "0",
      bodyAlpha: bodyAlpha
    });

console.log("---supercycle length:");
console.log(Number(getStr.cycleLength));
console.log("---first two values:")
console.log(getStr.getNext());
console.log(getStr.getNext());
console.log("---arbitrary large value (1e57):");
console.log(getStr.getString(BigInt(1e57)));
console.log("");

// here we use a shorter headAlpha and longer neckAlpha
// to shorten the maximum length of the body, but this also
// decreases the number of permutations in the supercycle:

getStr = sequenceGenerator({
  headAlpha: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
  neckAlpha: "0123456789",
  bodyAlpha: bodyAlpha
});

console.log("---supercycle length:");
console.log(Number(getStr.cycleLength));
console.log("---first two values:");
console.log(getStr.getNext());
console.log(getStr.getNext());
console.log("---arbitrary large value (1e57):");
console.log(getStr.getString(BigInt(1e57)));

EDIT

After further discussion with @grodzi, I have made some more improvements:

I realized that the "neck" or separator wasn't providing much value, so I have gotten rid of it. Later edit: actually, the separator is necessary. I am not sure why I thought it wasn't. Without the separator, the beginning of each new supercycle will lexically precede the end of the previous supercycle. I haven't changed my code below, but anyone using this code should include a separator. I have also realized that I was wrong to use an underscore as the separator. The separator must be a character, such as the hyphen, which lexically precedes the lowest digit used in the sequence (0).

I have taken @grodzi's suggestion to allow the length of the tail to continue growing indefinitely.

Here is the new code:

let baseAlpha = "0123456789abcdefghijklmnopqrstuvwxyz";

function sequenceGenerator (config) {

  let headAlpha = config.headAlpha,
      tailAlpha = config.tailAlpha,
      base = BigInt(tailAlpha.length),
      convertTail = baseAlpha.startsWith(tailAlpha)
                    ? (n) => n.toString(tailAlpha.length)
                    : function (n) {
                        if (n === 0n) return "0";
                        let s = "";
                        while (n > 0n) {
                          let i = n % base;
                          s = tailAlpha[i] + s;
                          n = n / base;
                        }
                        return s;
                      },
      n = BigInt(config.start || 0);

  return {

    getString: function (n) {
      let cyclesDone = 0n,
          headCycle = 0n,
          initLength = 0n,
          accum = 0n;
      for (;; headCycle++) {
        let _accum = accum + base ** (headCycle + 1n + initLength);
        if (_accum > n) {
          n -= accum;
          break;
        } else if (Number(headCycle) === headAlpha.length - 1) {
          cyclesDone++;
          initLength += BigInt(headAlpha.length);
          headCycle = -1n;
        }
        accum = _accum;
      }
      let headLast = headAlpha[headAlpha.length - 1],
          prefix = headLast.repeat(Number(cyclesDone)),
          head = headAlpha[Number(headCycle)],
          tail = convertTail(n),
          tailLength = Number(headCycle + initLength);
      tail = tail.padStart(tailLength, tailAlpha[0]);
      return prefix + head + tail;
    },

    getNext: function () { return this.getString(n++); }

  };
}

let alpha = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",
    genStr = sequenceGenerator({headAlpha: alpha, tailAlpha: alpha});

console.log("--- first string:");
console.log(genStr.getString(0n));
console.log("--- 1e+57");
console.log(genStr.getString(BigInt(1e+57)));
console.log("--- end of first supercycle:");
console.log(genStr.getString(63n*(1n-(63n**63n))/(1n-63n)-1n));
console.log("--- start of second supercycle:");
console.log(genStr.getString(63n*(1n-(63n**63n))/(1n-63n)));


来源: stackexchange

问:
How to save faker images to local folder using JavaScript?
I am learning back-end and I want to use the faker library to generate about 1000 jpg files of random user images to my local folder.

Script Name: dummyImages.js

const faker = require('faker');
const makeFakeImage = function() {
  return faker.image.people();
}
makeFakeImage();```

If I run this script using the command

node dummyImages.js

I expect to receive an URL link and I can save and download the image file to my local folder. However, this process is too manual and it's not the best practice. Can someone help me to refractor my script so that it can save 1000 faker image files automatically into a local folder with jpg file name going from "1" to "1000" (ex: 1.jpg 2.jpg etc...). My intent is to insert all files inside that folder into AWS S3 afterward and use them on React.

答:
/* eslint-disable no-plusplus */
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');

const url = [];
// 100 fake avatar url from fakter
for (let i = 0; i < 100; i++) {
  url.push(faker.image.avatar());
}

// download 100 user photoes to local image folder
for (let i = 0; i < url.length; i++) {
  // path for image storage
  const imagePath = path.join(__dirname, '../image', `${i}.jpg`);
  axios({
    method: 'get',
    url: url[i],
    responseType: 'stream',
  })
    .then((response) => {
      response.data.pipe(fs.createWriteStream(imagePath));
    });
}```

The following script works. Just make sure I have to npm install the right dependencies into package.json and the folder referenced "image" exists

ContentLicense: CC BY-SA 4.0

Body:
I am learning back-end and I want to use the faker library to generate about 1000 jpg files of random user images to my local folder.

Script Name: dummyImages.js

const faker = require('faker');
const makeFakeImage = function() {
  return faker.image.people();
}
makeFakeImage();

If I run this script using the command

node dummyImages.js

I expect to receive an URL link and I can save and download the image file to my local folder. However, this process is too manual and it's not the best practice. Can someone help me to refractor my script so that it can save 1000 faker image files automatically into a local folder with jpg file name going from "1" to "1000" (ex: 1.jpg 2.jpg etc...). My intent is to insert all files inside that folder into AWS S3 afterward and use them on React.

Body:
/* eslint-disable no-plusplus */
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');

const url = [];
// 100 fake avatar url from fakter
for (let i = 0; i < 100; i++) {
  url.push(faker.image.avatar());
}

// download 100 user photoes to local image folder
for (let i = 0; i < url.length; i++) {
  // path for image storage
  const imagePath = path.join(__dirname, '../image', `${i}.jpg`);
  axios({
    method: 'get',
    url: url[i],
    responseType: 'stream',
  })
    .then((response) => {
      response.data.pipe(fs.createWriteStream(imagePath));
    });
}

The following script works. Just make sure I have to npm install the right dependencies into package.json and the folder referenced "image" exists


问:
How can I move something relative to it's facing at a fixed speed while preventing movement along the global y axis?
I've tried using transform.translate with Space.Self, but that comes with the problem of moving up or down when the object has any pitch. Using Space.World doesn't account for any of the objects facing though, so just that won't work either. I know this is a very simple issue that practically every 3D game has solved, but I haven't for the life of me been able to figure out the solution or find it in any searches.

This is what I currently have:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    float speed = 0.15f;

    void FixedUpdate()
    {
        if (Input.GetKey("w"))
        {
            transform.Translate (0, 0, speed, Space.Self);
        }
        if (Input.GetKey("s"))
        {
            transform.Translate (0, 0, -speed, Space.Self);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate (speed, 0, 0, Space.Self);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate (-speed, 0, 0, Space.Self);
        }
    }
}
</code>```

What I have here presents multiple issues. If the character has any pitch, it will attempt to float straight in that direction instead of moving at full speed horizontally. Additionally, diagonal movement such as when w and s are held simultaneously will move the character 1 unit along each axis instead of 1 unit in the diagonal.

答:
If you want your facing direction vector which ignores the Y axis, you can take transform.forward and remove the Y component like this:

```<code>Vector3 facingDirection = transform.forward;

Vector3 myNewDirectionVector = new Vector3(facingDirection.x, 0, facingDirection.z).normalized;
</code>```

You can then move your object like this:

```<code>transform.position += myNewDirectionVector * speed * Time.deltaTime;
</code>```

Body:
I've tried using transform.translate with Space.Self, but that comes with the problem of moving up or down when the object has any pitch. Using Space.World doesn't account for any of the objects facing though, so just that won't work either. I know this is a very simple issue that practically every 3D game has solved, but I haven't for the life of me been able to figure out the solution or find it in any searches.

This is what I currently have:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    float speed = 0.15f;

    void FixedUpdate()
    {
        if (Input.GetKey("w"))
        {
            transform.Translate (0, 0, speed, Space.Self);
        }
        if (Input.GetKey("s"))
        {
            transform.Translate (0, 0, -speed, Space.Self);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate (speed, 0, 0, Space.Self);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate (-speed, 0, 0, Space.Self);
        }
    }
}

What I have here presents multiple issues. If the character has any pitch, it will attempt to float straight in that direction instead of moving at full speed horizontally. Additionally, diagonal movement such as when w and s are held simultaneously will move the character 1 unit along each axis instead of 1 unit in the diagonal.

Body:
If you want your facing direction vector which ignores the Y axis, you can take transform.forward and remove the Y component like this:

Vector3 facingDirection = transform.forward;

Vector3 myNewDirectionVector = new Vector3(facingDirection.x, 0, facingDirection.z).normalized;

You can then move your object like this:

transform.position += myNewDirectionVector * speed * Time.deltaTime;


问:
Why this C code with pipe() suddenly stops?
I am a computer science's student and I have this "Operative Systems" exam nearby, while I was doing some exercises based on my teacher previous exams tracks, I found myself to be stuck on this one.

The track summarized:

Write a C program with two input files (input.txt and out.txt), the program has to create 2 child processes, the first one will read characters from the inputfile.txt two at a time and will pass them onto child n*2 only if the letters are equal! then will proceed to print them to out.txt.

I didn't do the equals part yet, because i'm stuck on this first while crashing.
I have done several attempts, but they always "freeze" after the first while sequence on V:55 , and I don't understand why the cicle is wrong(?)...

Here is my attempt:

```<code>#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdbool.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

#define MAX 128
#define argDef 3

int checkArgc(int argc);

int main(int argc, char **argv) {
    int pipe1[2], pipe2[2], nbytes, filedesc, pid1, pid2;
    char duelettere[2];
    char soluzione[MAX];
    if (!checkArgc(argc)) {
        printf("Numero di file insufficente!\a\n");
        exit(1);
    }
    printf("Qui tutto bene\n");
    /* Apertura file di input.txt */
    if ((filedesc = open(argv[1], O_RDONLY)) < 0) {
        perror("Errore durante l'apertura dei file.txt \a\n");
        exit(1);
    }
    printf("filedesc : %d\n", filedesc);
    if (pipe(pipe1) < 0) {
        perror("Errore durante la creazione della prima PIPE! \a\n");
        exit(1);
    }
    printf("pipe1 : %p\n", pipe1);
    if (pipe(pipe2) < 0) {
        perror("Errore durante la creazione della seconda PIPE! \a\n");
        exit(1);
    }
    printf("pipe2 : %p\n", pipe2);
    if ((pid1 = fork() < 0)) {
        perror("Errore creazione primo processo figlio \a\n");
        exit(1);
    }
    if (pid1 == 0) { /* Primo figlio */
        printf("pid1 : %d\n", pid1);
        close(pipe1[0]); /* Chiusura canale in entrata, per poter scrivere */
        while ((nbytes=read(filedesc, duelettere, 2)) == 2) {
            write(pipe1[1], duelettere, 2);
        }
        close(pipe1[1]); /* Chiudiamo la PIPE che stava scrivendo */
        close(filedesc);
    } else { /* Siamo nel processo padre, e lanceremo il figlio n^2 */
        close(pipe1[1]);
    }
    if (pid2 = fork() < 0) {
        perror("Errore creazione secondo figlio\a\n");
        exit(1);
    }
    if (pid2 == 0) {
        printf("pid2 : %d", pid2);
        close(pipe1[1]);
        close(pipe2[0]);
        nbytes = read(pipe1[0], soluzione, strlen(soluzione));
        nbytes = write("out.txt", soluzione, strlen(soluzione));
    } else { /* Codice del padre */
        close(pipe2[1]);
        /* Codice finale del padre */
        printf("Siamo arrivati nel padrino parte seconda\n");
    }
    waitpid(pid1, NULL, 0);
    waitpid(pid2, NULL, 0);
    return 0;
}

int checkArgc(int argc) {
    if (argc != argDef) {
        return 0;
    } else {
        return 1;
    }
}
</code>```

I apologize,
Some variables have italian names on it, because I'm italian.

答:
There might be other problems, but these two lines are definitely incorrect:

```<code>    if ((pid1 = fork() < 0))
    ...
    if (pid2 = fork() < 0) {
</code>```

You should change them to this:

```<code>    if ((pid1 = fork()) < 0)
    ...
    if ((pid2 = fork()) < 0) {
</code>```

Body:
I am a computer science's student and I have this "Operative Systems" exam nearby, while I was doing some exercises based on my teacher previous exams tracks, I found myself to be stuck on this one.

The track summarized:

Write a C program with two input files (input.txt and out.txt), the program has to create 2 child processes, the first one will read characters from the inputfile.txt two at a time and will pass them onto child n*2 only if the letters are equal! then will proceed to print them to out.txt.

I didn't do the equals part yet, because i'm stuck on this first while crashing.
I have done several attempts, but they always "freeze" after the first while sequence on V:55 , and I don't understand why the cicle is wrong(?)...

Here is my attempt:

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdbool.h>
#include <signal.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

#define MAX 128
#define argDef 3

int checkArgc(int argc);

int main(int argc, char **argv) {
    int pipe1[2], pipe2[2], nbytes, filedesc, pid1, pid2;
    char duelettere[2];
    char soluzione[MAX];
    if (!checkArgc(argc)) {
        printf("Numero di file insufficente!\a\n");
        exit(1);
    }
    printf("Qui tutto bene\n");
    /* Apertura file di input.txt */
    if ((filedesc = open(argv[1], O_RDONLY)) < 0) {
        perror("Errore durante l'apertura dei file.txt \a\n");
        exit(1);
    }
    printf("filedesc : %d\n", filedesc);
    if (pipe(pipe1) < 0) {
        perror("Errore durante la creazione della prima PIPE! \a\n");
        exit(1);
    }
    printf("pipe1 : %p\n", pipe1);
    if (pipe(pipe2) < 0) {
        perror("Errore durante la creazione della seconda PIPE! \a\n");
        exit(1);
    }
    printf("pipe2 : %p\n", pipe2);
    if ((pid1 = fork() < 0)) {
        perror("Errore creazione primo processo figlio \a\n");
        exit(1);
    }
    if (pid1 == 0) { /* Primo figlio */
        printf("pid1 : %d\n", pid1);
        close(pipe1[0]); /* Chiusura canale in entrata, per poter scrivere */
        while ((nbytes=read(filedesc, duelettere, 2)) == 2) {
            write(pipe1[1], duelettere, 2);
        }
        close(pipe1[1]); /* Chiudiamo la PIPE che stava scrivendo */
        close(filedesc);
    } else { /* Siamo nel processo padre, e lanceremo il figlio n^2 */
        close(pipe1[1]);
    }
    if (pid2 = fork() < 0) {
        perror("Errore creazione secondo figlio\a\n");
        exit(1);
    }
    if (pid2 == 0) {
        printf("pid2 : %d", pid2);
        close(pipe1[1]);
        close(pipe2[0]);
        nbytes = read(pipe1[0], soluzione, strlen(soluzione));
        nbytes = write("out.txt", soluzione, strlen(soluzione));
    } else { /* Codice del padre */
        close(pipe2[1]);
        /* Codice finale del padre */
        printf("Siamo arrivati nel padrino parte seconda\n");
    }
    waitpid(pid1, NULL, 0);
    waitpid(pid2, NULL, 0);
    return 0;
}

int checkArgc(int argc) {
    if (argc != argDef) {
        return 0;
    } else {
        return 1;
    }
}

I apologize,
Some variables have italian names on it, because I'm italian.

Body:
There might be other problems, but these two lines are definitely incorrect:

    if ((pid1 = fork() < 0))
    ...
    if (pid2 = fork() < 0) {

You should change them to this:

    if ((pid1 = fork()) < 0)
    ...
    if ((pid2 = fork()) < 0) {


问:
GestureDetector fires all containers...how to fire just one?
I have a gesture detector that fires all containers and I just want to fire one at a time. How would I go about doing that? Right now they are all turning green and I just want to turn one of them green.

Is it the fact that I'm calling it multiple times in the same way in my _HomePageState class?

I thought the new keyword would have taken care of that so I tried that.

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.3,
                width: MediaQuery.of(context).size.width * 0.95,
                color: Theme.of(context).primaryColorLight,
              ),
              Padding(
                padding: EdgeInsets.all(5),
              ),
              Container(
                width: MediaQuery.of(context).size.width * .97,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.56,
                width: MediaQuery.of(context).size.width * .97,
                child: ListView(
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                  ],
                ),
              ),
            ]
          ),
        )
      );
  }

  Color _color = Colors.blue;

  Widget heroes(BuildContext context) {
    return new GestureDetector(
        onTap: () {
          setState( () {
            _color = Colors.green;
          });
        },
        child: new Container(
          height: MediaQuery.of(context).size.height * 0.05,
          width: MediaQuery.of(context).size.width * 0.12,
          color: _color,
        )
      );
  }

  Widget list(BuildContext context) {
    return Padding(
          padding: EdgeInsets.all(5),
          child: Container(
            height: MediaQuery.of(context).size.height * 0.07,
            width: MediaQuery.of(context).size.width * (0.12*8),
            color: Theme.of(context).primaryColorDark
          )
    );
  }

}
</code>```

答:
Read the comments to understand how it works. It is really simple.

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.3,
                width: MediaQuery.of(context).size.width * 0.95,
                color: Theme.of(context).primaryColorLight,
              ),
              Padding(
                padding: EdgeInsets.all(5),
              ),
              Container(
                width: MediaQuery.of(context).size.width * .97,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    // 1) Give each widget a number
                    heroes(context, 0),
                    heroes(context, 1),
                    heroes(context, 2),
                    heroes(context, 3),
                    heroes(context, 4),
                    heroes(context, 5),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.56,
                width: MediaQuery.of(context).size.width * .97,
                child: ListView(
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                  ],
                ),
              ),
            ]
          ),
        )
      );
  }

  // 2) This is important. It saves the current index.
  var selectedIndex;

  // 3) Add `index` as a parameter
  Widget heroes(BuildContext context, index) {
    return new GestureDetector(
        onTap: () {
          setState( () {
            // 4) After each tap the index of the widget is saved as `selectedIndex`
            selectedIndex = index;
          });
        },
        child: new Container(
          height: MediaQuery.of(context).size.height * 0.05,
          width: MediaQuery.of(context).size.width * 0.12,
          // 5) It compares the current selectedIndex with the index of the widget. If both have the same number, the color will be green. Otherwise it will be blue.
          color: selectedIndex == index? Colors.green : Colors.blue,
        )
      );
  }

  Widget list(BuildContext context) {
    return Padding(
          padding: EdgeInsets.all(5),
          child: Container(
            height: MediaQuery.of(context).size.height * 0.07,
            width: MediaQuery.of(context).size.width * (0.12*8),
            color: Theme.of(context).primaryColorDark
          )
    );
  }
}
</code>```

Body:
I have a gesture detector that fires all containers and I just want to fire one at a time. How would I go about doing that? Right now they are all turning green and I just want to turn one of them green.

Is it the fact that I'm calling it multiple times in the same way in my _HomePageState class?

I thought the new keyword would have taken care of that so I tried that.

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.3,
                width: MediaQuery.of(context).size.width * 0.95,
                color: Theme.of(context).primaryColorLight,
              ),
              Padding(
                padding: EdgeInsets.all(5),
              ),
              Container(
                width: MediaQuery.of(context).size.width * .97,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                    heroes(context),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.56,
                width: MediaQuery.of(context).size.width * .97,
                child: ListView(
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                  ],
                ),
              ),
            ]
          ),
        )
      );
  }

  Color _color = Colors.blue;

  Widget heroes(BuildContext context) {
    return new GestureDetector(
        onTap: () {
          setState( () {
            _color = Colors.green;
          });
        },
        child: new Container(
          height: MediaQuery.of(context).size.height * 0.05,
          width: MediaQuery.of(context).size.width * 0.12,
          color: _color,
        )
      );
  }

  Widget list(BuildContext context) {
    return Padding(
          padding: EdgeInsets.all(5),
          child: Container(
            height: MediaQuery.of(context).size.height * 0.07,
            width: MediaQuery.of(context).size.width * (0.12*8),
            color: Theme.of(context).primaryColorDark
          )
    );
  }

}

Body:
Read the comments to understand how it works. It is really simple.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(20),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.3,
                width: MediaQuery.of(context).size.width * 0.95,
                color: Theme.of(context).primaryColorLight,
              ),
              Padding(
                padding: EdgeInsets.all(5),
              ),
              Container(
                width: MediaQuery.of(context).size.width * .97,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    // 1) Give each widget a number
                    heroes(context, 0),
                    heroes(context, 1),
                    heroes(context, 2),
                    heroes(context, 3),
                    heroes(context, 4),
                    heroes(context, 5),
                  ],
                ),
              ),
              Container(
                height: MediaQuery.of(context).size.height * 0.56,
                width: MediaQuery.of(context).size.width * .97,
                child: ListView(
                  scrollDirection: Axis.vertical,
                  children: <Widget>[
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                    list(context),
                  ],
                ),
              ),
            ]
          ),
        )
      );
  }

  // 2) This is important. It saves the current index.
  var selectedIndex;

  // 3) Add `index` as a parameter
  Widget heroes(BuildContext context, index) {
    return new GestureDetector(
        onTap: () {
          setState( () {
            // 4) After each tap the index of the widget is saved as `selectedIndex`
            selectedIndex = index;
          });
        },
        child: new Container(
          height: MediaQuery.of(context).size.height * 0.05,
          width: MediaQuery.of(context).size.width * 0.12,
          // 5) It compares the current selectedIndex with the index of the widget. If both have the same number, the color will be green. Otherwise it will be blue.
          color: selectedIndex == index? Colors.green : Colors.blue,
        )
      );
  }

  Widget list(BuildContext context) {
    return Padding(
          padding: EdgeInsets.all(5),
          child: Container(
            height: MediaQuery.of(context).size.height * 0.07,
            width: MediaQuery.of(context).size.width * (0.12*8),
            color: Theme.of(context).primaryColorDark
          )
    );
  }
}


问:
@angular-cli install fails with deprecated request@2.88.2: request has been deprecated (mac)
After updating node.js and npm to current LTS:

```<code>node -v
v12.16.0
</code>```

```<code>npm -v
6.13.4
</code>```

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

```<code>npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s
</code>```

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.

答:
The issue you are experiencing has noting to do with npm warning you see in console ref. It is seems more likely a problem with permissions on your machine or NodeJS installation issue or both.

I would recommend to remove your NodeJS installation completely at first and then install NVM to manage your NodeJS instances:

Mac/Linux: https://github.com/nvm-sh/nvm

Windows:https://github.com/coreybutler/nvm-windows

Once you done installing NVM try to install Angular CLI:

```<code>npm install @angular/cli -g
</code>```

Hope it helps!

UPDATE: Also you  can check this issue

Body:
After updating node.js and npm to current LTS:

node -v
v12.16.0

npm -v
6.13.4

When I'm trying to install @angular-cli following the steps in the documentation, running npm install -g @angular/cli
 in the terminal stops the installation and the console output is:

npm install -g @angular/cli
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
/Users/user/.npm-global/bin/ng -> /USERS/USER/.npm-global/lib/node_modules/@angular/cli/bin/ng

> @angular/cli@9.0.2 postinstall /USERS/USER/.npm-global/lib/node_modules/@angular/cli
> node ./bin/postinstall/script.js

+ @angular/cli@9.0.2
updated 1 package in 12.202s

And in this case, ng new project-name yields -bash: ng: command not found. Any help would be very welcome as I have a big project coming up.
Thanks all.

Body:
The issue you are experiencing has noting to do with npm warning you see in console ref. It is seems more likely a problem with permissions on your machine or NodeJS installation issue or both.

I would recommend to remove your NodeJS installation completely at first and then install NVM to manage your NodeJS instances:

Mac/Linux: https://github.com/nvm-sh/nvm

Windows:https://github.com/coreybutler/nvm-windows

Once you done installing NVM try to install Angular CLI:

npm install @angular/cli -g

Hope it helps!

UPDATE: Also you  can check this issue


问:
Apache HttpComponents HttpClient timeout
How do I set the connection timeout in httpcomponents httpclient? I have found the documentation at: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html but it is not clear how these parameters are actually set.

Also, an explanation of the difference between SO_TIMEOUT and CONNECTION_TIMEOUT would be helpful.

答:
In section 2.5 you see an example of how to set the CONNECTION_TIMEOUT parameter.

CONNECTION_TIMEOUT is the time waiting for the initial connection and SO_TIMEOUT is the timeout that you wait for when reading a packet after the connection is established.

ContentLicense: CC BY-SA 3.0


问:
How can I get my QR code, processed with PyQRCode?
I am trying to append an image to my pdf. I have successfully appended a barcode but I am having troubles with the QRCode. I am using PyQrCode and ReportLab

Here is my code snippers:

Where I append :

```<code>parts.append(Image(self.qrCode, width=.3* 0.7 *inch, height=.4*.56*inch))`
</code>```

Where I create the QRCode:

```<code>qrCode = pyqrcode.create(str("252525"), error='L', version=27, mode='binary')
qrCode.svg(sys.stdout, scale=1)
qrCode.svg('uca-url.svg', scale=4)

number = pyqrcode.create(123456789012345)
number.png('big-number.png')
</code>```

and the error that I am getting:

```<code>AttributeError at /inventories/download_tag/2525/
QRCode instance has no attribute 'rfind'
</code>```

Is there a better library or method to achieve my goal here?

答:
```<code>pip install pyqrcode
</code>```

then

```<code>cd a_path_you_want
nano  make_qr.py

#!/usr/bin/python
import sys
import pyqrcode
text = sys.argv[1]
scale = sys.argv[2] # 1 to 8
err_prt = sys.argv[3] # error_protection in ['L','M','H']
url = pyqrcode.create(text,err_prt)
url.svg(sys.stdout, scale, module_color="brown") #this returns svg to caller script
exit(0)
</code>```

be sure to

```<code>chmod +x make_qr.py
</code>```

call from php

```<code><?php
  $text = ".... your data here ....";
  echo shell_exec("path_to_script/make_qr.py '$text' 4 'L' 2>&1");
 ?>
</code>```

Body:
I am trying to append an image to my pdf. I have successfully appended a barcode but I am having troubles with the QRCode. I am using PyQrCode and ReportLab

Here is my code snippers:

Where I append :

parts.append(Image(self.qrCode, width=.3* 0.7 *inch, height=.4*.56*inch))`

Where I create the QRCode:

qrCode = pyqrcode.create(str("252525"), error='L', version=27, mode='binary')
qrCode.svg(sys.stdout, scale=1)
qrCode.svg('uca-url.svg', scale=4)

number = pyqrcode.create(123456789012345)
number.png('big-number.png')

and the error that I am getting:

AttributeError at /inventories/download_tag/2525/
QRCode instance has no attribute 'rfind'

Is there a better library or method to achieve my goal here?

Body:
pip install pyqrcode

then

cd a_path_you_want
nano  make_qr.py

#!/usr/bin/python
import sys
import pyqrcode
text = sys.argv[1]
scale = sys.argv[2] # 1 to 8
err_prt = sys.argv[3] # error_protection in ['L','M','H']
url = pyqrcode.create(text,err_prt)
url.svg(sys.stdout, scale, module_color="brown") #this returns svg to caller script
exit(0)

be sure to

chmod +x make_qr.py

call from php

<?php
  $text = ".... your data here ....";
  echo shell_exec("path_to_script/make_qr.py '$text' 4 'L' 2>&1");
 ?>


问:
Accessing 3 characters from a string every time in C
I'm trying to get data from a file. The file has integer data in every line. The length of data varies every line. While I'm accessing each line with fgets(), I'm getting the line in a string format. I want to access 3 characters of the string every time till newline (\n) appears.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
    int k,a;
    char res[300] = "";
    char buff[1026];
    FILE *ip,*op;
    ip = fopen(argv[1],"r");
    op= fopen(argv[2],"w+");
    if( ip == NULL)
           {
                     perror("An error has occurred\n");
                       exit(1);
           }

    while(fgets(buff, sizeof(buff), fp))
    {       i=0;
            int len = sizeof(buff) / sizeof(buff[0]);
</code>```

Now buff has the first line of the file as a string. I want to use a for loop to get 3 characters of the string each time until \n, then my program will move to next line.

I'm more of a Python guy and in Python I can do it by using a for loop and accessing the index [i:i+2]. That will give me 3 indices every time, not sure how to do it in C. Maybe I can take another string (S1) and iterate over buff for 3 characters every time and append the 3 characters in the new string. Then I'll do my validations and initialize the string S1 for next iteration. It seems kind of messy.

Is there any other good way to do it? Please help.

答:
I'm more of a python guy and in python I can do it by using a for loop and accessing the index [i:i+2]. That will give me 3 indices every time, not sure how to do it in C.

Given index i, you want to access s[i], s[i+1] and s[i+2] in C.

To copy all 3 in one go, you could use memcpy or strncpy giving a starting address of &s[i].

For instance, if you do not care about the null character, you may do:

```<code>char d[3];
memcpy(d, &s[i], 3);
</code>```

Body:
I'm trying to get data from a file. The file has integer data in every line. The length of data varies every line. While I'm accessing each line with fgets(), I'm getting the line in a string format. I want to access 3 characters of the string every time till newline (\n) appears.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char* argv[])
{
    int k,a;
    char res[300] = "";
    char buff[1026];
    FILE *ip,*op;
    ip = fopen(argv[1],"r");
    op= fopen(argv[2],"w+");
    if( ip == NULL)
           {
                     perror("An error has occurred\n");
                       exit(1);
           }

    while(fgets(buff, sizeof(buff), fp))
    {       i=0;
            int len = sizeof(buff) / sizeof(buff[0]);

Now buff has the first line of the file as a string. I want to use a for loop to get 3 characters of the string each time until \n, then my program will move to next line.

I'm more of a Python guy and in Python I can do it by using a for loop and accessing the index [i:i+2]. That will give me 3 indices every time, not sure how to do it in C. Maybe I can take another string (S1) and iterate over buff for 3 characters every time and append the 3 characters in the new string. Then I'll do my validations and initialize the string S1 for next iteration. It seems kind of messy.

Is there any other good way to do it? Please help.

Body:
I'm more of a python guy and in python I can do it by using a for loop and accessing the index [i:i+2]. That will give me 3 indices every time, not sure how to do it in C.

Given index i, you want to access s[i], s[i+1] and s[i+2] in C.

To copy all 3 in one go, you could use memcpy or strncpy giving a starting address of &s[i].

For instance, if you do not care about the null character, you may do:

char d[3];
memcpy(d, &s[i], 3);


问:
re-sequencing a column of numbers based on a set value, R
I have a column of numbers that need to be re sequenced starting from 1, for example:
 column with numbers: 226 227 227 227 228 228 229 229 ...... so on

I would like to re sequence so that: 226 changes 1, 227 changes 2, 227 = 2, 227 = 2, 228 = 3, 228 = 3,
 229 = 4, 229 = 4  ....... and so on

    Current
    Desired

    226
    99

    227
    100

     227
    100

    227
    100

    228
    101

    228
    101

    229
    102

    229
    102

    229
    102

```

Body:
You can try as.numeric + factor like below, i.e.,

r <- as.numeric(factor(v))

such that

> r
[1] 1 2 2 2 3 3 4 4

DATA

v <- c(226, 227, 227, 227, 228, 228, 229, 229)


问:
is there an easy way to bring a dictionary into a function?
The goal is to play craps with this.

I created a dictionary "all_dice" and I end up passing it through 3 functions before it is used.

There must be an easier way to access the dictionary without just passing it over and over again like this.

```<code>import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz,ad):
    x = 0
    nday = ad[ndy]
    ndaz = ad[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker(ad,):
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z,ad)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker(all_dice)```
```

答:
You could condense a lot of that code. The function that prints could be condensed using ''.join() and a list comprehension. And the dice_roller() function being only a couple lines of active code could just be included in the primary function.

```<code>>>> def roll():
...     num_words = ["dummy", "one", "two", "three", "four", "five", "six"]
...     x = randint(1, 6)
...     y = randint(1, 6)
...     d1 = all_dice[num_words[x]]
...     d2 = all_dice[num_words[y]]
...     roll_str = ''.join(["%s %s\n" % (d1[i][0], d2[i][0]) for i in range(5)])
...     print(roll_str)
>>> roll()
_____ _____
0     0   0
        0
    0 0   0
_____ _____
</code>```

By reimplementing all_dice like so:

```<code>all_dice = {6: ["____", "0  0", "0  0", "0  0", "____"], 5: <and so on...>
</code>```

The code is further simplified:

```<code>>>> def roll():
...     d1 = all_dice[randint(1, 6)]
...     d2 = all_dice[randint(1, 6)]
...     print(''.join(["%s %s\n" % (d1[i], d2[i]) for i in range(5)]))
>>> roll()
_____ _____
0     0   0
        0
    0 0   0
_____ _____
</code>```

Body:
The goal is to play craps with this.

I created a dictionary "all_dice" and I end up passing it through 3 functions before it is used.

There must be an easier way to access the dictionary without just passing it over and over again like this.

import random
from random import randint

x = 0
the_dice_chosen = ""

##this is the dictionary

all_dice = {"six":
        [["_____",],
        ["0   0",],
        ["0   0",],
        ["0   0",],
        ["_____",],],
        "five":
        [["_____",],
        ["0   0",],
        ["  0  ",],
        ["0   0",],
        ["_____",],],
        "four":
        [["_____",],
        ["0   0",],
        ["     ",],
        ["0   0",],
        ["_____",],],
        "three":
        [["_____",],
        ["0    ",],
        ["  0  ",],
        ["    0",],
        ["_____",],],
        "two":
        [["_____",],
        ["0    ",],
        ["    ",],
        ["    0",],
        ["_____",],],
        "one":
        [["_____",],
        ["     ",],
        ["  0  ",],
        ["     ",],
        ["_____",],],}

## This prints the dictionary of the numbers chosen side by side.
## Again "all_dice" is passed as "ad" and is used.

def dice_print(ndy,ndz,ad):
    x = 0
    nday = ad[ndy]
    ndaz = ad[ndz]
    for i in nday:
        print(nday[x], ndaz[x])
        x = x + 1

##This creates the random dice numbers.

def dice_roller():
    x = randint(1, 6)
    y = randint(1, 6)
    return(x, y)

## This converts the numbers into selections in the dictionary. E.G. 6 into "six" "all_dice" is ad
## and it will from now on be passed as "ad".

def dice_maker(ad,):
    master = {1 : "one",
              2 : "two",
              3 : "three",
              4 : "four",
              5 : "five",
              6 : "six",}
    for i in range(1,2):
        x = dice_roller()
        y = int(x[0])
        z = int(x[1])
        new_die_y = (master[y])
        new_die_z = (master[z])
        dice_print(new_die_y,new_die_z,ad)

##This calls the script to action and passing the dictionary "all_dice"

dice_maker(all_dice)```

Body:
You could condense a lot of that code. The function that prints could be condensed using ''.join() and a list comprehension. And the dice_roller() function being only a couple lines of active code could just be included in the primary function.

>>> def roll():
...     num_words = ["dummy", "one", "two", "three", "four", "five", "six"]
...     x = randint(1, 6)
...     y = randint(1, 6)
...     d1 = all_dice[num_words[x]]
...     d2 = all_dice[num_words[y]]
...     roll_str = ''.join(["%s %s\n" % (d1[i][0], d2[i][0]) for i in range(5)])
...     print(roll_str)
>>> roll()
_____ _____
0     0   0
        0
    0 0   0
_____ _____

By reimplementing all_dice like so:

all_dice = {6: ["____", "0  0", "0  0", "0  0", "____"], 5: <and so on...>

The code is further simplified:

>>> def roll():
...     d1 = all_dice[randint(1, 6)]
...     d2 = all_dice[randint(1, 6)]
...     print(''.join(["%s %s\n" % (d1[i], d2[i]) for i in range(5)]))
>>> roll()
_____ _____
0     0   0
        0
    0 0   0
_____ _____


问:
C++: std::vector - std::find & std::distance query
To give context to my question I will describe what it is I am ultimately trying to achieve - I am developing a game, I have a .obj model that I am using as my terrain and I must update the players height as they traverse the terrain (because the terrain is far from flat). I am achieving this currently by doing the following - when I load the mesh (terrain.obj) I store all its vertices (each vertex is a Vector3f object that has an x y and z value) in a std::vector<Vector3f> meshVertices, then every second in the "main game loop" I loop through every one of the Vector3f objects in meshVertices and check its x and z value against the players x and z value, if they are colliding I set the players height as the y value of the matched Vector3f object.

This system actually works and updates my players height as they traverse through the terrain, the only issue is this - my approach of checking every single mesh vertex against player position every second kills my frame rate, I need a much better system.

I will now describe my new optimized approach in the attempt of saving my frame rate - Firstly, when creating the mesh I don't just store each Vector3f vertex in a single std::vector<Vector3f>, I store the x y and z values of each Vector3f vertex of the mesh in three seperate std::vector<Vector3f>'s, named meshVerticesX, mechVerticesY and meshVerticesZ. These std::vector's can be seen in the following code:

```<code>for (Vector3f currentVertex : meshVertices) {
            meshVerticesX.push_back((int)currentVertex.GetX());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesZ.push_back((int)currentVertex.GetZ());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesY.push_back((int)currentVertex.GetY());
}
</code>```

Now every second I get the x and z value of the players position (casted to an int because I feel like making this system work with int values and not float values will be much easier for comparisons later) and then send them to functions that check to see if they exist in the before mentioned meshVerticesX and mechVerticesZ by returning a bool, the code responsible for this is as follows:

```<code>int playerPosX = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetX();
int playerPosZ = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetZ();
bool x = meshObjects[0]->checkMeshVerticesX(playerPosX);
bool z = meshObjects[0]->checkMeshVerticesZ(playerPosZ);
</code>```

The functions checkMeshVerticesX and checkMeshVerticesZ are as follows:

```<code>bool Mesh::checkMeshVerticesX(int playerPosX)
{
    return std::find(meshVerticesX.begin(), meshVerticesX.end(), playerPosX) != meshVerticesX.end();
}
</code>```

```<code>bool Mesh::checkMeshVerticesZ(int playerPosZ)
{
    return std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerPosZ) != meshVerticesZ.end();
}
</code>```

Using the returned boolean values (true if the players position was in the respective std::vector or false if it was not) I then call another function (getMeshYHeight) that also gets passed the players x and z position that then checks the index of the respective std::vector's (meshVerticesX & meshVerticesZ) were the match was found, then checks if these indexes are equal and if so returns an int of that index from the meshVerticesY std::vector mentioned earlier, this code can be seen in the following:

```<code>if (x == true & z == true) {// boolean values returned by checkMeshVerticesX & checkMeshVerticesZ
        int terrainVertexYHeight = meshObjects[0]->getMeshYHeight(playerPosX, playerPosZ);
        freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->SetY(terrainVertexYHeight);
    }
</code>```

The function getMeshYHeight is as follows:

```<code>int Mesh::getMeshYHeight(int playerXPos, int playerZPos) {//15/2/20
    auto iterX = std::find(meshVerticesX.begin(), meshVerticesX.end(), playerXPos) != meshVerticesX.end();
    auto iterZ = std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerZPos) != meshVerticesZ.end();
    int indexX = std::distance(meshVerticesX.begin(), iterX);
    int indexZ = std::distance(meshVerticesZ.begin(), iterZ);
    if (indexX == indexZ)
    {
        return meshVerticesY[indexX];
    }
}
</code>```

The idea here is that if the index from the meshVerticesX and meshVerticesZ std::vectors's for the original check match, then they must be the x and z values from an original Vector3f object when I first made the mesh as described earlier, and so that same index in meshVerticesY must contain that same Vector3f's objects y value, therefore return it and use it to set the players height.

The issue is that I cant even test if this works because the line of code int indexX = std::distance(meshVerticesX.begin(), iterX); gives an error saying the arguments supplied to std::distance are wrong (it says iterX is a bool instead of an int which is what I thought it would be).

So my question is - Firstly, if I diden't have this error would my approach even work? and if so, how can I fix the error?

答: could you convert your terrain's x,y coordinates to ints, you may need to scale it, then when you load the mesh you could just store the z value for every x,y point (you may have to take some sort of average over the 1x1 square). Now you don't have to look for collisions, instead for each object in the game you can just look up it's z value by it's (scaled) x,y coordinates. </p>

Body:
To give context to my question I will describe what it is I am ultimately trying to achieve - I am developing a game, I have a .obj model that I am using as my terrain and I must update the players height as they traverse the terrain (because the terrain is far from flat). I am achieving this currently by doing the following - when I load the mesh (terrain.obj) I store all its vertices (each vertex is a Vector3f object that has an x y and z value) in a std::vector<Vector3f> meshVertices, then every second in the "main game loop" I loop through every one of the Vector3f objects in meshVertices and check its x and z value against the players x and z value, if they are colliding I set the players height as the y value of the matched Vector3f object.

This system actually works and updates my players height as they traverse through the terrain, the only issue is this - my approach of checking every single mesh vertex against player position every second kills my frame rate, I need a much better system.

I will now describe my new optimized approach in the attempt of saving my frame rate - Firstly, when creating the mesh I don't just store each Vector3f vertex in a single std::vector<Vector3f>, I store the x y and z values of each Vector3f vertex of the mesh in three seperate std::vector<Vector3f>'s, named meshVerticesX, mechVerticesY and meshVerticesZ. These std::vector's can be seen in the following code:

for (Vector3f currentVertex : meshVertices) {
            meshVerticesX.push_back((int)currentVertex.GetX());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesZ.push_back((int)currentVertex.GetZ());
}
for (Vector3f currentVertex : meshVertices) {
            meshVerticesY.push_back((int)currentVertex.GetY());
}

Now every second I get the x and z value of the players position (casted to an int because I feel like making this system work with int values and not float values will be much easier for comparisons later) and then send them to functions that check to see if they exist in the before mentioned meshVerticesX and mechVerticesZ by returning a bool, the code responsible for this is as follows:

int playerPosX = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetX();
int playerPosZ = (int) freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->GetZ();
bool x = meshObjects[0]->checkMeshVerticesX(playerPosX);
bool z = meshObjects[0]->checkMeshVerticesZ(playerPosZ);

The functions checkMeshVerticesX and checkMeshVerticesZ are as follows:

bool Mesh::checkMeshVerticesX(int playerPosX)
{
    return std::find(meshVerticesX.begin(), meshVerticesX.end(), playerPosX) != meshVerticesX.end();
}

bool Mesh::checkMeshVerticesZ(int playerPosZ)
{
    return std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerPosZ) != meshVerticesZ.end();
}

Using the returned boolean values (true if the players position was in the respective std::vector or false if it was not) I then call another function (getMeshYHeight) that also gets passed the players x and z position that then checks the index of the respective std::vector's (meshVerticesX & meshVerticesZ) were the match was found, then checks if these indexes are equal and if so returns an int of that index from the meshVerticesY std::vector mentioned earlier, this code can be seen in the following:

if (x == true & z == true) {// boolean values returned by checkMeshVerticesX & checkMeshVerticesZ
        int terrainVertexYHeight = meshObjects[0]->getMeshYHeight(playerPosX, playerPosZ);
        freeMoveObjects[0]->GetParent()->GetTransform()->GetPos()->SetY(terrainVertexYHeight);
    }

The function getMeshYHeight is as follows:

int Mesh::getMeshYHeight(int playerXPos, int playerZPos) {//15/2/20
    auto iterX = std::find(meshVerticesX.begin(), meshVerticesX.end(), playerXPos) != meshVerticesX.end();
    auto iterZ = std::find(meshVerticesZ.begin(), meshVerticesZ.end(), playerZPos) != meshVerticesZ.end();
    int indexX = std::distance(meshVerticesX.begin(), iterX);
    int indexZ = std::distance(meshVerticesZ.begin(), iterZ);
    if (indexX == indexZ)
    {
        return meshVerticesY[indexX];
    }
}

The idea here is that if the index from the meshVerticesX and meshVerticesZ std::vectors's for the original check match, then they must be the x and z values from an original Vector3f object when I first made the mesh as described earlier, and so that same index in meshVerticesY must contain that same Vector3f's objects y value, therefore return it and use it to set the players height.

The issue is that I cant even test if this works because the line of code int indexX = std::distance(meshVerticesX.begin(), iterX); gives an error saying the arguments supplied to std::distance are wrong (it says iterX is a bool instead of an int which is what I thought it would be).

So my question is - Firstly, if I diden't have this error would my approach even work? and if so, how can I fix the error?


问:
Wear OS application: Disable all possible options to closing application on android watch
I am working on an alert notification system were user is to be alerted on some events.

In this, I need to invoke the application on the android watch from the controller Android application and keep it until it is required to be closed from the controller application. The user should not be able to close the alert application by any means (e.g. swipe to left, long press etc).

After many tries, we could not find a way to prevent the close by user action.

Minimum wear OS version is 2.0.

答: Build watch face in one with your application. User who install your custom face can't exit with hardware buttons. Build watch faces</p>


问:
How to keep binary values in a Factor Variable?
I'm performing a toy example logistic regression.
What I would like to do is: keep the factor variable a_fac performing as a binary variable.

Here's my code:

```<code>set.seed(8)
a = rbinom( n = 10, size = 1, prob = 0.5)
d = seq(1:length(a))

a_fac = factor(a, labels=c("class1", "class2"))
plot(d, a_fac)

##Logistic Regression
lr = glm(a_fac~d, family=binomial(link="logit"))       ##cannot perform the log regression with factor var.
lr = glm(a~d, family=binomial(link="logit"))

##plotting
plot(d,a_fac, main = "logistic regression",  ylim = c(0,2))
lines(d,lr$fitted.values)

##this is the correct plot i want to obtain with the factor variable
plot(d,a, main = "logistic regression")
lines(d,lr$fitted.values)
</code>```

Can I do this or I have to keep object of the same variable? Thank You

答:
Your first glm model is NOT logistic regression since you did not include the family argument and specify "binomial".

```<code>lr = glm(a_fac~d) # Error!
</code>```

The error is due to R trying to do a linear regression on a non-numeric outcome. The correct command should be:

```<code>lr = glm(a_fac~d, family=binomial(link="logit"))
</code>```

With plotting, factors are treated as integers starting with 1 for the first level. So if you want to use 0 and 1 for the y-axis, but have your labels attached, use the a version of your outcome vector, suppress the tick labels (yaxt="n"), and then add an axis with your own labels.

```<code>plot(d, a, main = "logistic regression", yaxt="n", ylab="Outcome")
lines(d, lr2$fitted.values, col="red")
axis(side=2, at=c(0,1), labels=levels(a_fac), las=1)
</code>```

Body:
I'm performing a toy example logistic regression.
What I would like to do is: keep the factor variable a_fac performing as a binary variable.

Here's my code:

set.seed(8)
a = rbinom( n = 10, size = 1, prob = 0.5)
d = seq(1:length(a))

a_fac = factor(a, labels=c("class1", "class2"))
plot(d, a_fac)

##Logistic Regression
lr = glm(a_fac~d, family=binomial(link="logit"))       ##cannot perform the log regression with factor var.
lr = glm(a~d, family=binomial(link="logit"))

##plotting
plot(d,a_fac, main = "logistic regression",  ylim = c(0,2))
lines(d,lr$fitted.values)

##this is the correct plot i want to obtain with the factor variable
plot(d,a, main = "logistic regression")
lines(d,lr$fitted.values)

Can I do this or I have to keep object of the same variable? Thank You

Body:
Your first glm model is NOT logistic regression since you did not include the family argument and specify "binomial".

lr = glm(a_fac~d) # Error!

The error is due to R trying to do a linear regression on a non-numeric outcome. The correct command should be:

lr = glm(a_fac~d, family=binomial(link="logit"))

With plotting, factors are treated as integers starting with 1 for the first level. So if you want to use 0 and 1 for the y-axis, but have your labels attached, use the a version of your outcome vector, suppress the tick labels (yaxt="n"), and then add an axis with your own labels.

plot(d, a, main = "logistic regression", yaxt="n", ylab="Outcome")
lines(d, lr2$fitted.values, col="red")
axis(side=2, at=c(0,1), labels=levels(a_fac), las=1)


问:
Speed up linq query perfomance
I'm running this linq query which is a little big.

```<code>var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());
</code>```

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.

答:
one thing can be sorting at the end because there would be less items and then less time to sort,

BUT it really depends on your data distribution. Look if MOST of your data has  e.IsPresentation == true, then the first "Where" does not reduce the data size for you, SO then you are again checking  e.IsCanceled == false on e.g. 95 % your data. But assume only 10 % of your whole data is  e.IsCanceled == false. So now if you apply  e.IsPresentation == true , on that 10% in the second order, it takes much less time than before. So in big databases DB managers usually use different query plans! however the final result is the same. the process time is NOT same. hope it helps you.

Title: Speed up linq query perfomance

Body:
I'm running this linq query which is a little big.

var events = _context.Event.OrderByDescending(e => e.StartDate).Where(e => e.IsPresentation == true).Where(e => e.IsCanceled == false).Where(e => e.StartDate > new DateTime());

And the page outputing the data from this query is taking too much time to load. Maybe because I'm using too many wheres.

I had the same issue using includes, and then includes, in a different query, but I divided the query, to improve the performance. But I'm trying to figure it out how to do the same thing in that situation, because I'm not using any include.


问:
gradle circular dependency with external project
I have a fairly simple setup, that does not work and I cannot work out why:

the folder structure is as follows:

```<code>/dependency
    /build.gradle
    /settings.gradle
    /src/main/...

/Mainproject
    /build.gradle
    /settings.gradle

    /Subproject_1
        /build.gradle
        /src/main...

     /Subproject_2
        /build.gradle
        /src/main...
</code>```

I want the Subproject to depend on "dependency" locally for quick testing.
so I stuck to the manual and did:

/Mainproject/settings.gradle:

```<code>include "Subproject_1", "Subproject_2", "dependency"
project(":dependency").projectDir = file('../dependency')
</code>```

/Mainproject/build.gradle:

```<code>allprojects {
    apply plugin: 'java'
    dependencies {
        compile project(path: ':dependency')
    }
}

dependencies {
    compile project(':Subproject_1')
    compile project(':Subproject_2')
}
</code>```

/dependency/build.gradle:

```<code>version '1.0'
apply plugin: 'java'

repositories {
    maven {
        url "http://...."
    }
}

dependencies {
    compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
    compile group: 'javax', name: 'javaee-api', version: '7.0'
}

jar {
    manifest {
        attributes 'Implementation-Title': 'Archive delegation dispatcher classes',
                'Implementation-Version': project.version
    }
}
</code>```

The build.gradle files of Subproject_1 and _2 are empty.
The settings.gradle file of dependency is empty.

When i gradle build MainProject i get:

```<code>Circular dependency between the following tasks:
:dependency:classes
\--- :dependency:compileJava
     \--- :dependency:jar
          \--- :dependency:classes (*)

(*) - details omitted (listed previously)
</code>```

And I cannot get my head around why that would be.

Any hints?

答:
build.gradle (:shared)

This is because you are trying to include a module inside of yourself.

From:

```<code>dependencies {
    implementation project(':shared')
    ...
}
</code>```

To:

```<code>dependencies {
    ...
}
</code>```

GL

Source

Body:
I have a fairly simple setup, that does not work and I cannot work out why:

the folder structure is as follows:

/dependency
    /build.gradle
    /settings.gradle
    /src/main/...

/Mainproject
    /build.gradle
    /settings.gradle

    /Subproject_1
        /build.gradle
        /src/main...

     /Subproject_2
        /build.gradle
        /src/main...

I want the Subproject to depend on "dependency" locally for quick testing.
so I stuck to the manual and did:

/Mainproject/settings.gradle:

include "Subproject_1", "Subproject_2", "dependency"
project(":dependency").projectDir = file('../dependency')

/Mainproject/build.gradle:

allprojects {
    apply plugin: 'java'
    dependencies {
        compile project(path: ':dependency')
    }
}

dependencies {
    compile project(':Subproject_1')
    compile project(':Subproject_2')
}

/dependency/build.gradle:

version '1.0'
apply plugin: 'java'

repositories {
    maven {
        url "http://...."
    }
}

dependencies {
    compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
    compile group: 'javax', name: 'javaee-api', version: '7.0'
}

jar {
    manifest {
        attributes 'Implementation-Title': 'Archive delegation dispatcher classes',
                'Implementation-Version': project.version
    }
}

The build.gradle files of Subproject_1 and _2 are empty.
The settings.gradle file of dependency is empty.

When i gradle build MainProject i get:

Circular dependency between the following tasks:
:dependency:classes
\--- :dependency:compileJava
     \--- :dependency:jar
          \--- :dependency:classes (*)

(*) - details omitted (listed previously)

And I cannot get my head around why that would be.

Any hints?

Body:
build.gradle (:shared)

This is because you are trying to include a module inside of yourself.

From:

dependencies {
    implementation project(':shared')
    ...
}

To:

dependencies {
    ...
}

GL

Source


问:
Draw vertical line at the first bar of the month in tradingview's pine script
I'd like to draw a vertical dashed line at every first bar of a month (for daily and weekly charts) or a year (for monthly charts).
How can I do that? I don't know how to get those bar indexes.

Addition:
I read in
this post
that "line.new" has a restriction to 54 lines max per indicator. But when using the plot function in histogram style (=plot only single vertical histogram bars), I cannot plot dashed lines... and I prefer a solution with dashed lines...

答:
This is an adaptation of midtownsk8rguy's code here:</p>

```<code>//@version=4
study("Periodic Vline", overlay=true)
p = timeframe.ismonthly ? "12M" : "M"
vline(BarIndex, Color, LineStyle, LineWidth) =>
    return = line.new(BarIndex, low - tr, BarIndex, high + tr, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
if change(time(p))
    vline(bar_index, #FF800080, line.style_dashed, 1)
</code>```

Body:
This is an adaptation of midtownsk8rguy's code here:

//@version=4
study("Periodic Vline", overlay=true)
p = timeframe.ismonthly ? "12M" : "M"
vline(BarIndex, Color, LineStyle, LineWidth) =>
    return = line.new(BarIndex, low - tr, BarIndex, high + tr, xloc.bar_index, extend.both, Color, LineStyle, LineWidth)
if change(time(p))
    vline(bar_index, #FF800080, line.style_dashed, 1)


问:
How does R lm choose contrasts with interaction between a categorical and continuous variables?
If I run lm with a formula like Y ~ X1 + X2:X1 + X3:X1 where X1 is continuous and X2,X3 are categorical, I get a contrast for both levels of X2, but not X3.

The pattern is that the first categorical interaction gets both levels but not the second.

library(tidyverse)
library(magrittr)
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#>     set_names
#> The following object is masked from 'package:tidyr':
#>
#>     extract

df = data.frame(Frivolousness = sample(1:100, 50, replace =T))
df %<>% mutate(
  Personality=sample(c("Bad", "Good"), 50, replace = T),
  Timing=ifelse(Frivolousness %% 2 == 0 & runif(50) > 0.2, "Early", "Late")
  )
df %<>% mutate(
  Enchantedness = 11 +
    ifelse(Personality=="Good", 0.23, -0.052)*Frivolousness -
    1.3*ifelse(Personality=="Good", 1, 0) +
    10*rnorm(50)
  )
df %<>% mutate(
  Personality = factor(Personality, levels=c("Bad", "Good")),
  Timing = factor(Timing, levels=c("Early", "Late"))
)

lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Timing:Frivolousness +
#>     Personality:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate      TimingEarly:Frivolousness
#>                      -1.41757                       -0.05796
#>      TimingLate:Frivolousness  PersonalityGood:Frivolousness
#>                      -0.07433                        0.33410

lm(Enchantedness ~ Personality + Timing + Personality:Frivolousness+ Timing:Frivolousness , df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Personality:Frivolousness +
#>     Timing:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate   PersonalityBad:Frivolousness
#>                      -1.41757                       -0.05796
#> PersonalityGood:Frivolousness       TimingLate:Frivolousness
#>                       0.27614                       -0.01636
```

Created on 2020-02-15 by the reprex package (v0.3.0)

答: I think the reason it is dropped is that there would be perfect colinearity if it was included. You really should have Frivolousness as a regressor on its own also. Then, you will see that R provides you with the result for just one level of both interactions.</p>

Body:
If I run lm with a formula like Y ~ X1 + X2:X1 + X3:X1 where X1 is continuous and X2,X3 are categorical, I get a contrast for both levels of X2, but not X3.

The pattern is that the first categorical interaction gets both levels but not the second.

library(tidyverse)
library(magrittr)
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#>     set_names
#> The following object is masked from 'package:tidyr':
#>
#>     extract

df = data.frame(Frivolousness = sample(1:100, 50, replace =T))
df %<>% mutate(
  Personality=sample(c("Bad", "Good"), 50, replace = T),
  Timing=ifelse(Frivolousness %% 2 == 0 & runif(50) > 0.2, "Early", "Late")
  )
df %<>% mutate(
  Enchantedness = 11 +
    ifelse(Personality=="Good", 0.23, -0.052)*Frivolousness -
    1.3*ifelse(Personality=="Good", 1, 0) +
    10*rnorm(50)
  )
df %<>% mutate(
  Personality = factor(Personality, levels=c("Bad", "Good")),
  Timing = factor(Timing, levels=c("Early", "Late"))
)

lm(Enchantedness ~ Personality + Timing + Timing:Frivolousness + Personality:Frivolousness, df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Timing:Frivolousness +
#>     Personality:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate      TimingEarly:Frivolousness
#>                      -1.41757                       -0.05796
#>      TimingLate:Frivolousness  PersonalityGood:Frivolousness
#>                      -0.07433                        0.33410

lm(Enchantedness ~ Personality + Timing + Personality:Frivolousness+ Timing:Frivolousness , df)
#>
#> Call:
#> lm(formula = Enchantedness ~ Personality + Timing + Personality:Frivolousness +
#>     Timing:Frivolousness, data = df)
#>
#> Coefficients:
#>                   (Intercept)                PersonalityGood
#>                      15.64118                      -10.99518
#>                    TimingLate   PersonalityBad:Frivolousness
#>                      -1.41757                       -0.05796
#> PersonalityGood:Frivolousness       TimingLate:Frivolousness
#>                       0.27614                       -0.01636

Created on 2020-02-15 by the reprex package (v0.3.0)


问:
How to open a page in new tab on click of a button in react? I want to send some data to that page also
I'm working on a raise invoice page, in which user can raise a invoice on clicking of a button, I would call a api call and after getting the response I want to send some data to a page(RaisedInvoice.jsx) which should open in a new tab, how can i do it. The thing which I am not getting is how to open a page in new tab on click of a button in ReactJs.

RaiseInvoice.jsx:

```<code>import React from 'react';
import Links from './Links.jsx';
import history from './history.jsx';

import axios from 'axios';

class RaiseInvoice extends React.Component {

    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.state = {projects: [], searchParam : ''};
        this.raiseInvoiceClicked = this.raiseInvoiceClicked.bind(this);
    }

    raiseInvoiceClicked(){
        // here i wish to write the code for opening the page in new tab.
    }

    render() {
      return (
         <div>
              <Links activeTabName="tab2"></Links>
              <div className="container">
                  <div className = "row col-md-4">
                      <h1>Raise Invoice...</h1>
                  </div>
                  <div className = "row col-md-4"></div>
                  <div className = "row col-md-4" style ={{"marginTop":"24px"}}>
                      <button type="button" className="btn btn-default pull-right" onClick={this.raiseInvoiceClicked}>Raise Invoice</button>
                  </div>

              </div>
         </div>
      )
    }
}

export default RaiseInvoice;
</code>```

答:
Pass this data with props:

let href = '...url_to_redirect...'; let data_to_send = [...];

let api_href = '...url_api_where_sent_data.../?data_to_send';
export const DictDefaultOptions = (url=(api_href), method='GET') => {
let defaultOptions = {
    url : url,
    method  : method,
    mode : 'cors',
    headers : {'Access-Control-Allow-Origin':'*'}
};

return defaultOptions };

let sentData = {
    method: defaultOptions.method,
    mode: defaultOptions.mode
};

send_data_to_api = () => {
    let api_return = await fetch(api_href, sentData)
        .then(response => response.json())
        .then(responseText => {
            data = (JSON.parse(JSON.stringify(responseText)))
        })
        .catch(error => {
            console.log(`${requestURL} error: `, error)
        });

    do { await this.wait(100) } while(Object.keys(api_return).length <= 0);

    if (Object.keys(api_return).length > 0) {
        return window.open(href, "_blank")
    }
};
```

Body:
I'm working on a raise invoice page, in which user can raise a invoice on clicking of a button, I would call a api call and after getting the response I want to send some data to a page(RaisedInvoice.jsx) which should open in a new tab, how can i do it. The thing which I am not getting is how to open a page in new tab on click of a button in ReactJs.

RaiseInvoice.jsx:

import React from 'react';
import Links from './Links.jsx';
import history from './history.jsx';

import axios from 'axios';

class RaiseInvoice extends React.Component {

    constructor(props) {
        super(props);

        // This binding is necessary to make `this` work in the callback
        this.state = {projects: [], searchParam : ''};
        this.raiseInvoiceClicked = this.raiseInvoiceClicked.bind(this);
    }

    raiseInvoiceClicked(){
        // here i wish to write the code for opening the page in new tab.
    }

    render() {
      return (

              <Links activeTabName="tab2"></Links>

Raise Invoice...

                      <button type="button" className="btn btn-default pull-right" onClick={this.raiseInvoiceClicked}>Raise Invoice</button>

      )
    }
}

export default RaiseInvoice;