问:
R SaTScan package not producing expected output
I am using the rsatscan package to automate a spatial scan statistic analysis. I'm attempting to eliminate the need to use the gui.

I have been able to successfully create valid input files (geo,cas,prm); however, when I attempt to run the satscan function, no output is returned. Here is the code I'm running to set the parameters and run the analysis:

```<code>##reset parameters file
invisible(ss.options(reset=TRUE))

##set SaTScan Parameters
ss.options(list(CaseFile="malawi.cas",PrecisionCaseTimes=0))
ss.options(list(PopulationFile="malawi.pop"))
ss.options(list(CoordinatesFile="malawi.geo"))
ss.options(list(PrecisionCaseTimes=3,
                AnalysisType=1,
                ModelType=0,
                TimeAggregationUnits=1,
                MaxSpatialSizeInDistanceFromCenter=20,
                CriteriaForReportingSecondaryClusters=0,
                ReportGiniClusters="n",
                OutputShapefiles="y",
                CoordinatesType=1,
                UseDistanceFromCenterOption="y",
                ScanAreas=1,
                GeographicalCoordinatesCheckType=1))

head(ss.options(),3)

##Write satscan parameter file
td = "~/Documents/RSaTScan"
write.ss.prm(td, "CountryRec")
write.cas(malawiCas, td, "CountryRec")
write.geo(malawiGeo, td, "CountryRec")
write.pop(malawiPop, td, "CountryRec")

##run satscan
malawiRec<-satscan(prmlocation=td,
                  prmfilename="CountryRec",
                  sslocation = "SaTScan",ssbatchfilename = "SaTScanBatch64", cleanup=T, verbose=F)```
```

Body:
I am using the rsatscan package to automate a spatial scan statistic analysis. I'm attempting to eliminate the need to use the gui.

I have been able to successfully create valid input files (geo,cas,prm); however, when I attempt to run the satscan function, no output is returned. Here is the code I'm running to set the parameters and run the analysis:

##reset parameters file
invisible(ss.options(reset=TRUE))

##set SaTScan Parameters
ss.options(list(CaseFile="malawi.cas",PrecisionCaseTimes=0))
ss.options(list(PopulationFile="malawi.pop"))
ss.options(list(CoordinatesFile="malawi.geo"))
ss.options(list(PrecisionCaseTimes=3,
                AnalysisType=1,
                ModelType=0,
                TimeAggregationUnits=1,
                MaxSpatialSizeInDistanceFromCenter=20,
                CriteriaForReportingSecondaryClusters=0,
                ReportGiniClusters="n",
                OutputShapefiles="y",
                CoordinatesType=1,
                UseDistanceFromCenterOption="y",
                ScanAreas=1,
                GeographicalCoordinatesCheckType=1))

head(ss.options(),3)

##Write satscan parameter file
td = "~/Documents/RSaTScan"
write.ss.prm(td, "CountryRec")
write.cas(malawiCas, td, "CountryRec")
write.geo(malawiGeo, td, "CountryRec")
write.pop(malawiPop, td, "CountryRec")

##run satscan
malawiRec<-satscan(prmlocation=td,
                  prmfilename="CountryRec",
                  sslocation = "SaTScan",ssbatchfilename = "SaTScanBatch64", cleanup=T, verbose=F)```


来源: stackexchange

问:
Firestore Transaction Triggering Itself Recursively
I have a booking feature in my app and I'm trying to use transactions to prevent multiple users from booking the same timeslot.

I have a collection called "bookedTimeslots" under each user. Each document in the collection represents a 15 minute timeslot with a specific start date. If a user books a one hour appointment, the system should create 4 "bookedTimeslot" records. First, though, I need to check if any of these records already exists and reject the operation if they do.

Below, I've pasted the code for the transaction in Node. The function keeps timing out, though. I'm guessing it's because the first "set" operation is updating the results of my bookedTimeslotQuery and triggering the transaction to re-evaluate. If that's the case, is there some way to batch all the sets together or prevent the transaction from triggering itself?

export const afs = admin.firestore();

const startDate = appointment.startDate;
const endDate = appointment.endDate;

const bookedTimeslotQuery = afs.collection("users").doc(userId).collection("bookedTimeslots")
            .where("startDate", ">=", startDate)
            .where("startDate", "<", endDate);

const timeslotIncrement = 15*60; // 15 minutes
await afs.runTransaction(async (t) => {
    const docs = await t.get(bookedTimeslotQuery);
    if (!docs.empty) {
        throw new BookingError("timeslot not available", ErrorCode.TimeslotNotAvailable);
    }
    const tempStartDate = new Date(startDate);
    while (tempStartDate < endDate) {
        const bookingTimeslotId = uuidv4();
        const bookingTimeslot = {
            id: bookingTimeslotId,
            startDate: tempStartDate,
            duration: timeslotIncrement
        };
        t.set(afs.collection("users").doc(userId).collection("bookedTimeslots").doc(bookingTimeslotId), bookingTimeslot);
        tempStartDate.setSeconds(tempStartDate.getSeconds() + timeslotIncrement);
    }
});
```
<p><strong>UPDATE:</strong>
I found a workable solution for anyone who comes across this in the future. Instead of using a query, I used sequential individual document reads, then writes.
For my specific use case, instead of using a UUID for the document name, I use the ISOString of the document start date. Then, I sequentially call get then set inside the loop and individually check each document. Here's the code (it still needs to be cleaned up but this works).</p>
<pre class="lang-js prettyprint-override"><code>export const afs = admin.firestore();

const startDate = appointment.startDate;
const endDate = appointment.endDate;

const timeslotIncrement = 15*60; // 15 minutes
await afs.runTransaction(async (t) => {
    const tempStartDate1 = new Date(startDate);
    while (startDate < endDate) {
        const dateISOString = tempStartDate1.toISOString();
        const docRef = afs.collection("users").doc(userId)
            .collection("bookedTimeslots")
            .doc(dateISOString);
        const currentTimeslotDoc = await t.get(docRef);
        if (currentTimeslotDoc.exists) {
            throw new BookingError("timeslot not available", ErrorCode.TimeslotNotAvailable);
        }
        tempStartDate1.setSeconds(tempStartDate1.getSeconds() + timeslotIncrement);
    }
    const tempStartDate2 = new Date(startDate);
    while (startDate < endDate) {
        const dateISOString = tempStartDate2.toISOString();
        const docRef = afs.collection("users").doc(userId)
            .collection("bookedTimeslots")
            .doc(dateISOString);
        const bookingTimeslot = {
            id: dateISOString,
            startDate: new Date(tempStartDate2),
            duration: timeslotIncrement
        };
        t.set(docRef, bookingTimeslot);
        tempStartDate2.setSeconds(tempStartDate2.getSeconds() + timeslotIncrement);
    }
});

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a booking feature in my app and I'm trying to use transactions to prevent multiple users from booking the same timeslot.

I have a collection called "bookedTimeslots" under each user. Each document in the collection represents a 15 minute timeslot with a specific start date. If a user books a one hour appointment, the system should create 4 "bookedTimeslot" records. First, though, I need to check if any of these records already exists and reject the operation if they do.

Below, I've pasted the code for the transaction in Node. The function keeps timing out, though. I'm guessing it's because the first "set" operation is updating the results of my bookedTimeslotQuery and triggering the transaction to re-evaluate. If that's the case, is there some way to batch all the sets together or prevent the transaction from triggering itself?

export const afs = admin.firestore();

const startDate = appointment.startDate;
const endDate = appointment.endDate;

const bookedTimeslotQuery = afs.collection("users").doc(userId).collection("bookedTimeslots")
            .where("startDate", ">=", startDate)
            .where("startDate", "<", endDate);

const timeslotIncrement = 15*60; // 15 minutes
await afs.runTransaction(async (t) => {
    const docs = await t.get(bookedTimeslotQuery);
    if (!docs.empty) {
        throw new BookingError("timeslot not available", ErrorCode.TimeslotNotAvailable);
    }
    const tempStartDate = new Date(startDate);
    while (tempStartDate < endDate) {
        const bookingTimeslotId = uuidv4();
        const bookingTimeslot = {
            id: bookingTimeslotId,
            startDate: tempStartDate,
            duration: timeslotIncrement
        };
        t.set(afs.collection("users").doc(userId).collection("bookedTimeslots").doc(bookingTimeslotId), bookingTimeslot);
        tempStartDate.setSeconds(tempStartDate.getSeconds() + timeslotIncrement);
    }
});

UPDATE:
I found a workable solution for anyone who comes across this in the future. Instead of using a query, I used sequential individual document reads, then writes.
For my specific use case, instead of using a UUID for the document name, I use the ISOString of the document start date. Then, I sequentially call get then set inside the loop and individually check each document. Here's the code (it still needs to be cleaned up but this works).

export const afs = admin.firestore();

const startDate = appointment.startDate;
const endDate = appointment.endDate;

const timeslotIncrement = 15*60; // 15 minutes
await afs.runTransaction(async (t) => {
    const tempStartDate1 = new Date(startDate);
    while (startDate < endDate) {
        const dateISOString = tempStartDate1.toISOString();
        const docRef = afs.collection("users").doc(userId)
            .collection("bookedTimeslots")
            .doc(dateISOString);
        const currentTimeslotDoc = await t.get(docRef);
        if (currentTimeslotDoc.exists) {
            throw new BookingError("timeslot not available", ErrorCode.TimeslotNotAvailable);
        }
        tempStartDate1.setSeconds(tempStartDate1.getSeconds() + timeslotIncrement);
    }
    const tempStartDate2 = new Date(startDate);
    while (startDate < endDate) {
        const dateISOString = tempStartDate2.toISOString();
        const docRef = afs.collection("users").doc(userId)
            .collection("bookedTimeslots")
            .doc(dateISOString);
        const bookingTimeslot = {
            id: dateISOString,
            startDate: new Date(tempStartDate2),
            duration: timeslotIncrement
        };
        t.set(docRef, bookingTimeslot);
        tempStartDate2.setSeconds(tempStartDate2.getSeconds() + timeslotIncrement);
    }
});


问:
Python subprocess capture output of bash code in parentheses
I have a shell script that I run in a subprocess.popen() and would like to capture the output of that script and send it line by line into a logger object. The issue is that the output from the subprocess is captured by the parentheses (), and I never see the output. Has anyone here ever seen this happen, and would you be able to guide me on how to best do this?

The code takes a backup on a remote server and stores it locally. The parentheses are needed to encapsulate the ssh-agent in case more than one are open at the same time.

The bash code

( \
  eval $(ssh-agent) > /dev/null; \
  ssh-add -q /home/borgs/.ssh/borg-client_key; \
  echo $borgPassword | \
    ssh -p ${port} -A -o StrictHostKeyChecking=no ${user}@${ipAddress} \
    "BORG_PASSPHRASE=\$(cat) \
    borg \
    --rsh 'ssh -p 9270 -o StrictHostKeyChecking=no' \
    create \
    --verbose \
    --filter AME \
    --list \
    --stats \
    --show-rc \
    --compression lz4 \
    --exclude-caches \
    ssh://borgs@${ip_address}/~/${hostname}::$hostname-$backupTime $locations";
  kill "${SSH_AGENT_PID}"; \
) >&1
```
<p>The python code</p>
<pre class="lang-py prettyprint-override"><code>def takeBackup(server, lg):
    print(f"Taking backup of {server['hostname']}")
    locationString = " ".join(server['locations'])
    print(
        "Running create-backup.sh command: create-backup.sh",
        f"{server['hostname']} {server['ip-address']} '{locationString}'"
    )
    process = subprocess.Popen(
        [
            "./create-backup.sh",
            server['hostname'],
            server['ip-address'],
            server['borgPassword'],
            locationString
        ],
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE
    )
    for line in process.stdout:
        line = line.decode().rstrip('\n')
        lg.print_info(line)
    process.wait()
    print(process.returncode)
</code>```

Body:
I have a shell script that I run in a subprocess.popen() and would like to capture the output of that script and send it line by line into a logger object. The issue is that the output from the subprocess is captured by the parentheses (), and I never see the output. Has anyone here ever seen this happen, and would you be able to guide me on how to best do this?

The code takes a backup on a remote server and stores it locally. The parentheses are needed to encapsulate the ssh-agent in case more than one are open at the same time.

The bash code

( \
  eval $(ssh-agent) > /dev/null; \
  ssh-add -q /home/borgs/.ssh/borg-client_key; \
  echo $borgPassword | \
    ssh -p ${port} -A -o StrictHostKeyChecking=no ${user}@${ipAddress} \
    "BORG_PASSPHRASE=\$(cat) \
    borg \
    --rsh 'ssh -p 9270 -o StrictHostKeyChecking=no' \
    create \
    --verbose \
    --filter AME \
    --list \
    --stats \
    --show-rc \
    --compression lz4 \
    --exclude-caches \
    ssh://borgs@${ip_address}/~/${hostname}::$hostname-$backupTime $locations";
  kill "${SSH_AGENT_PID}"; \
) >&1

The python code

def takeBackup(server, lg):
    print(f"Taking backup of {server['hostname']}")
    locationString = " ".join(server['locations'])
    print(
        "Running create-backup.sh command: create-backup.sh",
        f"{server['hostname']} {server['ip-address']} '{locationString}'"
    )
    process = subprocess.Popen(
        [
            "./create-backup.sh",
            server['hostname'],
            server['ip-address'],
            server['borgPassword'],
            locationString
        ],
        stdin=subprocess.PIPE,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE
    )
    for line in process.stdout:
        line = line.decode().rstrip('\n')
        lg.print_info(line)
    process.wait()
    print(process.returncode)


问:
How to connect ATMEGA128 to EW12A03GLY?
What should I do to connect controller to display and after that show on this display generated array.
Maybe I could create a program which generates random array but how to connect these 2 devices and show the array on display I have no ideas. Below is my attempt of this.

1

2

Title: How to connect ATMEGA128 to EW12A03GLY?


问:
How to create a new database on Notion API with the new "Status" property?
Notion API HTTP requests are not working when I add a new "Status" propoerty for a new database creation.

I've been trying for a while to figure out why, sending Notion a simple HTTP POST request with a "Status" breaks it.

If I just replace "Status" with a simple "Select" it works fine...

This is the code that I tried on my latest attempt:

```<code>{
  "is_inline": true,
  "parent": {
    "type": "page_id",
    "page_id": page_id
  },
  "icon": {
    "type": "emoji",
    "emoji": ""
  },
  "title": [
    {
      "type": "text",
      "text": {
        "content": "Catches",
        "link": null
      }
    }
  ],
  "properties": {
    "Name": {
      "title": {}
    },
    "Status": {
      "status": {
        "options": [
          {
            "name": "Not started",
            "color": "default"
          },
          {
            "name": "25% Complete",
            "color": "blue"
          },
          {
            "name": "50% Complete",
            "color": "blue"
          },
          {
            "name": "75% Complete",
            "color": "blue"
          },
          {
            "name": "Done",
            "color": "green"
          },
          {
            "name": "Blocked",
            "color": "red"
          }
        ]
      }
    }
  }
}
</code>```

Status ref page on Notions docs: https://developers.notion.com/reference/property-object#status-configuration

Body:
Notion API HTTP requests are not working when I add a new "Status" propoerty for a new database creation.

I've been trying for a while to figure out why, sending Notion a simple HTTP POST request with a "Status" breaks it.

If I just replace "Status" with a simple "Select" it works fine...

This is the code that I tried on my latest attempt:

{
  "is_inline": true,
  "parent": {
    "type": "page_id",
    "page_id": page_id
  },
  "icon": {
    "type": "emoji",
    "emoji": ""
  },
  "title": [
    {
      "type": "text",
      "text": {
        "content": "Catches",
        "link": null
      }
    }
  ],
  "properties": {
    "Name": {
      "title": {}
    },
    "Status": {
      "status": {
        "options": [
          {
            "name": "Not started",
            "color": "default"
          },
          {
            "name": "25% Complete",
            "color": "blue"
          },
          {
            "name": "50% Complete",
            "color": "blue"
          },
          {
            "name": "75% Complete",
            "color": "blue"
          },
          {
            "name": "Done",
            "color": "green"
          },
          {
            "name": "Blocked",
            "color": "red"
          }
        ]
      }
    }
  }
}

Status ref page on Notions docs: https://developers.notion.com/reference/property-object#status-configuration


问:
multiple-select openning upwards and downwards problem
I use the multiple-select plugin on the website I made with html js (https://multiple-select.wenzhixin.net.cn/docs/en/options). When it comes to the bottom of the page, select should open upwards, but it opens downwards.How can i solve this?

when i scrool to page boottom,select input hawe to opening upwards, but it is openning downwards


问:
How to make line renderer work inside a sprite only using collision in a tracing game in unity2D?
I am creating a tracing game in unity. Where the tracing object is the sprite. I want the line renderer to not cross the sprite boundaries although collision is being detected but I an't figure out how to make line stay inside the sprite only.

DrawManager.cs

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

public class DrawManager : MonoBehaviour
{
    private Camera _cam;
    [SerializeField] private Line _lineprefab;
    private Line _currentline;
    public const float RESOLUTION = 0.1f;
    void Start()
    {
        _cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
        if (Input.GetMouseButtonDown(0)) {
            _currentline = Instantiate(_lineprefab,mousePos,Quaternion.identity);
        }
      if (Input.GetMouseButton(0)) _currentline.SetPosition(mousePos);

    }
}

</code>```

Line.cs

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

public class Line : MonoBehaviour
{
    [SerializeField] private LineRenderer _renderer;
    [SerializeField] private EdgeCollider2D _collider;
    private List<Vector2> _points = new List<Vector2>();
    collision oncollision;
    [SerializeField] private GameObject collisioncheck;
    void Start()
    {
        _collider.transform.position -= transform.position;
        oncollision = collisioncheck.GetComponent<collision>();
    }
    public void SetPosition(Vector2 pos)
    {

        if (!CanAppend(pos)) return;
        _points.Add(pos);
        _collider.points = _points.ToArray();
       _renderer.positionCount++;
       _renderer.SetPosition(_renderer.positionCount - 1, pos);
        }

    private bool CanAppend(Vector2 pos)
    {
        if (_renderer.positionCount == 0) return true;
        return Vector2.Distance(_renderer.GetPosition(_renderer.positionCount - 1), pos) > DrawManager.RESOLUTION;
    }

}

</code>```

Collision.cs

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

public class collision : MonoBehaviour
{
    private static bool iscollided;
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            iscollided = true;
        }
        Debug.Log("entered");
    }

    public bool getiscollided() {return iscollided; }

    private void OnCollisionStay2D(Collision2D collision)
    {
        Debug.Log("collision stayed");
    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        Debug.Log("exit");
    }
    public void ResetCollision()
    {
        iscollided = false;
    }
}

</code>```

I tried stopping the line using iscollided but getting nullexception error

Body:
I am creating a tracing game in unity. Where the tracing object is the sprite. I want the line renderer to not cross the sprite boundaries although collision is being detected but I an't figure out how to make line stay inside the sprite only.

DrawManager.cs

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

public class DrawManager : MonoBehaviour
{
    private Camera _cam;
    [SerializeField] private Line _lineprefab;
    private Line _currentline;
    public const float RESOLUTION = 0.1f;
    void Start()
    {
        _cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
        if (Input.GetMouseButtonDown(0)) {
            _currentline = Instantiate(_lineprefab,mousePos,Quaternion.identity);
        }
      if (Input.GetMouseButton(0)) _currentline.SetPosition(mousePos);

    }
}

Line.cs

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;

public class Line : MonoBehaviour
{
    [SerializeField] private LineRenderer _renderer;
    [SerializeField] private EdgeCollider2D _collider;
    private List<Vector2> _points = new List<Vector2>();
    collision oncollision;
    [SerializeField] private GameObject collisioncheck;
    void Start()
    {
        _collider.transform.position -= transform.position;
        oncollision = collisioncheck.GetComponent<collision>();
    }
    public void SetPosition(Vector2 pos)
    {

        if (!CanAppend(pos)) return;
        _points.Add(pos);
        _collider.points = _points.ToArray();
       _renderer.positionCount++;
       _renderer.SetPosition(_renderer.positionCount - 1, pos);
        }

    private bool CanAppend(Vector2 pos)
    {
        if (_renderer.positionCount == 0) return true;
        return Vector2.Distance(_renderer.GetPosition(_renderer.positionCount - 1), pos) > DrawManager.RESOLUTION;
    }

}

Collision.cs

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

public class collision : MonoBehaviour
{
    private static bool iscollided;
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Player")
        {
            iscollided = true;
        }
        Debug.Log("entered");
    }

    public bool getiscollided() {return iscollided; }

    private void OnCollisionStay2D(Collision2D collision)
    {
        Debug.Log("collision stayed");
    }
    private void OnCollisionExit2D(Collision2D collision)
    {
        Debug.Log("exit");
    }
    public void ResetCollision()
    {
        iscollided = false;
    }
}

I tried stopping the line using iscollided but getting nullexception error


问:
Querying values from one table into an array with a condition from a different table
I need to create an array with values from another table.

Table 1 has the columns id, A_type, and time

Table 2 has the columns array [{A_type:A_type value, time: time value},...], and id

All the necessary values present in the arrays in Table 2 is available in Table 1.

I need to recreate the array column from Table 2 in Table 1, but I cannot copy the array column from Table 2 due to redundancy issue.

How can I write the query logic so that I can recreate the array in Table 2 using values from Table 1?

Or is it even possible because there are multiple elements in the array?

I tried by simply joining the two tables together by id and create array by matching values from Table 2, but I can't seem to figure out what to do when there are multiple inputs that is made up of json blobs.


问:
How can I connect my python code and the React JS one so they work together?
I a newbie in backend and I am trying to connect the React with python, so basically it should work as it follows:
React sends inputted data in firebase -> python extracts it and works with it and sends it back in firebase -> react extracts it and works with it.

At this moment I've done all the necessary code however I don't know how to connect them.

Here is the React snippet were it sends the message to firebase:

```<code>  console.log(message)
  const Push = () => {
    const db = getDatabase();
    set(ref(db, 'users/'), {
      message : message
    });
  }
</code>```

Here is the pythonfile:

```<code>
firebase = Firebase(config) #extracting info
db = firebase.database()
users = db.child("users").get()
message = users.val()
query = ''
for element in message:
   query = message[element]

loc = Nominatim(user_agent="GetLoc")#working with it
getLoc = loc.geocode(f"{query}")
extract = db.child("extract").push(f"{getLoc.latitude},{getLoc.longitude}")#sending it in firebase
</code>```

So basically the question is how do I make them work together, and how can I do the operations that I said about above?
I've heard about Flask, but I don't know how it actually works...

Body:
I a newbie in backend and I am trying to connect the React with python, so basically it should work as it follows:
React sends inputted data in firebase -> python extracts it and works with it and sends it back in firebase -> react extracts it and works with it.

At this moment I've done all the necessary code however I don't know how to connect them.

Here is the React snippet were it sends the message to firebase:

  console.log(message)
  const Push = () => {
    const db = getDatabase();
    set(ref(db, 'users/'), {
      message : message
    });
  }

Here is the pythonfile:

firebase = Firebase(config) #extracting info
db = firebase.database()
users = db.child("users").get()
message = users.val()
query = ''
for element in message:
   query = message[element]

loc = Nominatim(user_agent="GetLoc")#working with it
getLoc = loc.geocode(f"{query}")
extract = db.child("extract").push(f"{getLoc.latitude},{getLoc.longitude}")#sending it in firebase

So basically the question is how do I make them work together, and how can I do the operations that I said about above?
I've heard about Flask, but I don't know how it actually works...


问:
mysql.connector to AWS RDS database timing out
I have an RDS database that a program I created using python and Mysql connect to, in order to keep track of usage of the program. Anytime the program is used, it adds 1 to a counter on the RDS database.  Just this week the program has started throwing an error connecting to the RDS SQL database after about an hour of use. Previous to this, I could leave the software running for days without ever timing out. Closing the software and re-opening it, to re-establish the connection allows me to connect for approx another hour or so before it times out again.

I am connecting using the following parameters:

```<code>awsConn = mysql.connector.connect(host='myDatabase.randomStringofChars.us-east-1.rds.amazonaws.com', database='myDatabase', port=3306, user='username', password='password')
</code>```

Did something recently change with AWS/RDS, do I just need to pass a different parameter into the connection string, or do I just need to add somewhere into my program to attempt to re-establish the connection every so often?

Thanks

Body:
I have an RDS database that a program I created using python and Mysql connect to, in order to keep track of usage of the program. Anytime the program is used, it adds 1 to a counter on the RDS database.  Just this week the program has started throwing an error connecting to the RDS SQL database after about an hour of use. Previous to this, I could leave the software running for days without ever timing out. Closing the software and re-opening it, to re-establish the connection allows me to connect for approx another hour or so before it times out again.

I am connecting using the following parameters:

awsConn = mysql.connector.connect(host='myDatabase.randomStringofChars.us-east-1.rds.amazonaws.com', database='myDatabase', port=3306, user='username', password='password')

Did something recently change with AWS/RDS, do I just need to pass a different parameter into the connection string, or do I just need to add somewhere into my program to attempt to re-establish the connection every so often?

Thanks


问:
My function call is returning expensive gas cost on metamask
To context. I want to make a contract that receives USDC and send custom tokens to the buyer. After that, in the same call, the contract forwards those USDCs to another wallet. I have done tests, and calls. When I do it through Remix, I'm able to get it working nicely, Rate works, forward funds, everything. However, once I try to call it through Metamask, it returns me a absurd amound of gas required (10 matic) to call buyTokens(). Could someone help me find if something is wrong, or should it be this expensive?

ps: With buyTokens(), we are also calling approve() from the buyer, to approve Crowdsale to take the right amount of USDC

I have two contracts to demonstrate. First, the custom token:

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./ERC777P.sol";
import "./MinterRole.sol";

contract TokenMBP is ERC777P, MinterRole {
    constructor(
        string memory name,
        string memory symbol,
        address[] memory defaultOperators,
        uint256 initialSupply
    ) ERC777P(name, symbol, defaultOperators)
    {
        _mint(msg.sender, initialSupply, "", "", "");
    }

    function mint(address account, uint256 amount, bytes memory userData, bytes memory operatorData, bytes32 proof) public onlyMinter returns (bool) {
        _mint(account, amount, userData, operatorData, proof);
        return true;
    }

    function burn(uint256 amount, bytes memory userData, bytes memory operatorData) public returns (bool) {
        _burn(msg.sender, amount, userData, operatorData);
        return true;
    }
}
</code>```

Then, the crowdsale:

```<code>pragma solidity ^0.5.0;

import "./Context.sol";
import "./IERC20.sol";
import "./StableCoin.sol";
import "./SafeMath.sol";
import "./SafeERC20.sol";
import "./ReentrancyGuard.sol";

/**
 * @title Crowdsale
 * @dev Crowdsale is a base contract for managing a token crowdsale,
 * allowing investors to purchase tokens with ether. This contract implements
 * such functionality in its most fundamental form and can be extended to provide additional
 * functionality and/or custom behavior.
 * The external interface represents the basic interface for purchasing tokens, and conforms
 * the base architecture for crowdsales. It is *not* intended to be modified / overridden.
 * The internal interface conforms the extensible and modifiable surface of crowdsales. Override
 * the methods to add functionality. Consider using 'super' where appropriate to concatenate
 * behavior.
 */

contract Crowdsale is Context, ReentrancyGuard {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // The token being sold
    IERC20 private _token;
    STABLE private _stableCoin = _stableCoin;

    // Address where funds are collected
    address payable private _wallet;

    // Contract owner address
    address _owner;
    // How many token units a buyer gets per usdc.
    // The rate is the conversion between usdc and the smallest and indivisible token unit.
    // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
    // 1 usdc will give you 1 unit, or 0.001 TOK.
    uint256 private _rate;

    // Amount of usdc raised
    uint256 private _usdcRaised;

    /**
     * Event for token purchase logging
     * @param purchaser who paid for the tokens
     * @param beneficiary who got the tokens
     * @param value usdcs paid for purchase
     * @param amount amount of tokens purchased
     */
    event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);

    /**
     * @param rate Number of token units a buyer gets per wei
     * @dev The rate is the conversion between wei and the smallest and indivisible
     * token unit. So, if you are using a rate of 1 with a ERC20Detailed token
     * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
     * @param wallet Address where collected funds will be forwarded to
     * @param token Address of the token being sold
     */
    constructor (uint256 rate, address payable wallet, IERC20 token, address stableCoin) public {
        require(rate > 0, "Crowdsale: rate is 0");
        require(wallet != address(0), "Crowdsale: wallet is the zero address");
        require(address(token) != address(0), "Crowdsale: token is the zero address");
        require(address(stableCoin) != address(0), "Crowdsale: stable is the zero address");

        _owner = _msgSender();
        _rate = rate;
        _wallet = wallet;
        _token = token;
        _stableCoin = STABLE(stableCoin);
    }

    modifier onlyOwner() {
        require(_msgSender() == _owner, "OwnerRole: Only owner can make this change");
        _;
    }

    /**
     * @return the token being sold.
     */
    function token() public view returns (IERC20) {
        return _token;
    }

    /**
     * @return the stable token being required.
     */
    function stable() public view returns (STABLE) {
        return _stableCoin;
    }

    /**
     * @return the address where funds are collected.
     */
    function wallet() public view returns (address payable) {
        return _wallet;
    }

    /**
     * @return the number of token units a buyer gets per wei.
     */
    function rate() public view returns (uint256) {
        return _rate;
    }

    /**
     * @return the amount of wei raised.
     */
    function usdcRaised() public view returns (uint256) {
        return _usdcRaised;
    }

    /**
     * @dev Change contract rate
     * @param newRate New price for minimum amount of token
     * @return true if rate was modifie
     */

     function changeRate(uint256 newRate) public onlyOwner returns (bool) {
        _rate = newRate;
        return true;
     }

    /**
     * @dev low level token purchase ***DO NOT OVERRIDE***
     * This function has a non-reentrancy guard, so it shouldn't be called by
     * another `nonReentrant` function.
     * @param beneficiary Recipient of the token purchase
     * @param tokenAmount Stable coin quantity for the purchase
     */
    function buyTokens(address beneficiary, uint256 tokenAmount) public nonReentrant payable {
        // calculate token amount to be created
        // tokenAmount = tokenAmount * 10 ** 18;

        uint256 tokens = _getTokenAmount(tokenAmount);

        _preValidatePurchase(beneficiary, tokens);
        // update state
        _usdcRaised = _usdcRaised.add(tokenAmount);

        bool stableStatus = _stableCoin.transferFrom(beneficiary, address(this), tokenAmount);
        require(stableStatus, "Crowdsale: Stable token transfer failed");

        _processPurchase(beneficiary, tokens);
        emit TokensPurchased(_msgSender(), beneficiary, tokenAmount, tokens);

        _updatePurchasingState(beneficiary, tokenAmount);

        _forwardFunds(tokenAmount);
        _postValidatePurchase(beneficiary, tokenAmount);
    }
    /**
     * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
     * Use `super` in contracts that inherit from Crowdsale to extend their validations.
     * Example from CappedCrowdsale.sol's _preValidatePurchase method:
     *     super._preValidatePurchase(beneficiary, tokenAmount);
     *     require(weiRaised().add(tokenAmount) <= cap);
     * @param beneficiary Address performing the token purchase
     * @param tokenAmount Value in wei involved in the purchase
     */
    function _preValidatePurchase(address beneficiary, uint256 tokenAmount) internal view {
        require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
        require(tokenAmount != 0, "Crowdsale: tokenAmount is 0");
        require(!(_stableCoin.balanceOf(beneficiary) < tokenAmount), "Crowdsale: Not enough balance");
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
    }

    /**
     * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
     * conditions are not met.
     * @param beneficiary Address performing the token purchase
     * @param weiAmount Value in wei involved in the purchase
     */
    function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
        // solhint-disable-previous-line no-empty-blocks
    }

    /**
     * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
     * its tokens.
     * @param beneficiary Address performing the token purchase
     * @param tokenAmount Number of tokens to be emitted
     */
    function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
        _token.safeTransfer(beneficiary, tokenAmount);
    }

    /**
     * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
     * tokens.
     * @param beneficiary Address receiving the tokens
     * @param tokenAmount Number of tokens to be purchased
     */
    function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
        _deliverTokens(beneficiary, tokenAmount);
    }

    /**
     * @dev Override for extensions that require an internal state to check for validity (current user contributions,
     * etc.)
     * @param beneficiary Address receiving the tokens
     * @param weiAmount Value in wei involved in the purchase
     */
    function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
        // solhint-disable-previous-line no-empty-blocks
    }

    /**
     * @dev Override to extend the way in which ether is converted to tokens.
     * @param stableCoinAmount Value in wei to be converted into tokens
     * @return Number of tokens that can be purchased with the specified _weiAmount
     */
    function _getTokenAmount(uint256 stableCoinAmount) internal view returns (uint256) {
        return stableCoinAmount.div(_rate);
    }

    /**
     * @dev Determines how ETH is stored/forwarded on purchases.
     */
    function _forwardFunds(uint256 tokenAmount) internal returns (bool){
        require(_stableCoin.transfer(_wallet, tokenAmount), "Crowdsale: Stable token transfer failed");
        return true;
    }

}
</code>```

I used those contracts and with remix gas was as low as 0.01 matic.

Body:
To context. I want to make a contract that receives USDC and send custom tokens to the buyer. After that, in the same call, the contract forwards those USDCs to another wallet. I have done tests, and calls. When I do it through Remix, I'm able to get it working nicely, Rate works, forward funds, everything. However, once I try to call it through Metamask, it returns me a absurd amound of gas required (10 matic) to call buyTokens(). Could someone help me find if something is wrong, or should it be this expensive?

ps: With buyTokens(), we are also calling approve() from the buyer, to approve Crowdsale to take the right amount of USDC

I have two contracts to demonstrate. First, the custom token:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./ERC777P.sol";
import "./MinterRole.sol";

contract TokenMBP is ERC777P, MinterRole {
    constructor(
        string memory name,
        string memory symbol,
        address[] memory defaultOperators,
        uint256 initialSupply
    ) ERC777P(name, symbol, defaultOperators)
    {
        _mint(msg.sender, initialSupply, "", "", "");
    }

    function mint(address account, uint256 amount, bytes memory userData, bytes memory operatorData, bytes32 proof) public onlyMinter returns (bool) {
        _mint(account, amount, userData, operatorData, proof);
        return true;
    }

    function burn(uint256 amount, bytes memory userData, bytes memory operatorData) public returns (bool) {
        _burn(msg.sender, amount, userData, operatorData);
        return true;
    }
}

Then, the crowdsale:

pragma solidity ^0.5.0;

import "./Context.sol";
import "./IERC20.sol";
import "./StableCoin.sol";
import "./SafeMath.sol";
import "./SafeERC20.sol";
import "./ReentrancyGuard.sol";

/**
 * @title Crowdsale
 * @dev Crowdsale is a base contract for managing a token crowdsale,
 * allowing investors to purchase tokens with ether. This contract implements
 * such functionality in its most fundamental form and can be extended to provide additional
 * functionality and/or custom behavior.
 * The external interface represents the basic interface for purchasing tokens, and conforms
 * the base architecture for crowdsales. It is *not* intended to be modified / overridden.
 * The internal interface conforms the extensible and modifiable surface of crowdsales. Override
 * the methods to add functionality. Consider using 'super' where appropriate to concatenate
 * behavior.
 */

contract Crowdsale is Context, ReentrancyGuard {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    // The token being sold
    IERC20 private _token;
    STABLE private _stableCoin = _stableCoin;

    // Address where funds are collected
    address payable private _wallet;

    // Contract owner address
    address _owner;
    // How many token units a buyer gets per usdc.
    // The rate is the conversion between usdc and the smallest and indivisible token unit.
    // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
    // 1 usdc will give you 1 unit, or 0.001 TOK.
    uint256 private _rate;

    // Amount of usdc raised
    uint256 private _usdcRaised;

    /**
     * Event for token purchase logging
     * @param purchaser who paid for the tokens
     * @param beneficiary who got the tokens
     * @param value usdcs paid for purchase
     * @param amount amount of tokens purchased
     */
    event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);

    /**
     * @param rate Number of token units a buyer gets per wei
     * @dev The rate is the conversion between wei and the smallest and indivisible
     * token unit. So, if you are using a rate of 1 with a ERC20Detailed token
     * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
     * @param wallet Address where collected funds will be forwarded to
     * @param token Address of the token being sold
     */
    constructor (uint256 rate, address payable wallet, IERC20 token, address stableCoin) public {
        require(rate > 0, "Crowdsale: rate is 0");
        require(wallet != address(0), "Crowdsale: wallet is the zero address");
        require(address(token) != address(0), "Crowdsale: token is the zero address");
        require(address(stableCoin) != address(0), "Crowdsale: stable is the zero address");

        _owner = _msgSender();
        _rate = rate;
        _wallet = wallet;
        _token = token;
        _stableCoin = STABLE(stableCoin);
    }

    modifier onlyOwner() {
        require(_msgSender() == _owner, "OwnerRole: Only owner can make this change");
        _;
    }

    /**
     * @return the token being sold.
     */
    function token() public view returns (IERC20) {
        return _token;
    }

    /**
     * @return the stable token being required.
     */
    function stable() public view returns (STABLE) {
        return _stableCoin;
    }

    /**
     * @return the address where funds are collected.
     */
    function wallet() public view returns (address payable) {
        return _wallet;
    }

    /**
     * @return the number of token units a buyer gets per wei.
     */
    function rate() public view returns (uint256) {
        return _rate;
    }

    /**
     * @return the amount of wei raised.
     */
    function usdcRaised() public view returns (uint256) {
        return _usdcRaised;
    }

    /**
     * @dev Change contract rate
     * @param newRate New price for minimum amount of token
     * @return true if rate was modifie
     */

     function changeRate(uint256 newRate) public onlyOwner returns (bool) {
        _rate = newRate;
        return true;
     }

    /**
     * @dev low level token purchase ***DO NOT OVERRIDE***
     * This function has a non-reentrancy guard, so it shouldn't be called by
     * another `nonReentrant` function.
     * @param beneficiary Recipient of the token purchase
     * @param tokenAmount Stable coin quantity for the purchase
     */
    function buyTokens(address beneficiary, uint256 tokenAmount) public nonReentrant payable {
        // calculate token amount to be created
        // tokenAmount = tokenAmount * 10 ** 18;

        uint256 tokens = _getTokenAmount(tokenAmount);

        _preValidatePurchase(beneficiary, tokens);
        // update state
        _usdcRaised = _usdcRaised.add(tokenAmount);

        bool stableStatus = _stableCoin.transferFrom(beneficiary, address(this), tokenAmount);
        require(stableStatus, "Crowdsale: Stable token transfer failed");

        _processPurchase(beneficiary, tokens);
        emit TokensPurchased(_msgSender(), beneficiary, tokenAmount, tokens);

        _updatePurchasingState(beneficiary, tokenAmount);

        _forwardFunds(tokenAmount);
        _postValidatePurchase(beneficiary, tokenAmount);
    }
    /**
     * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
     * Use `super` in contracts that inherit from Crowdsale to extend their validations.
     * Example from CappedCrowdsale.sol's _preValidatePurchase method:
     *     super._preValidatePurchase(beneficiary, tokenAmount);
     *     require(weiRaised().add(tokenAmount) <= cap);
     * @param beneficiary Address performing the token purchase
     * @param tokenAmount Value in wei involved in the purchase
     */
    function _preValidatePurchase(address beneficiary, uint256 tokenAmount) internal view {
        require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
        require(tokenAmount != 0, "Crowdsale: tokenAmount is 0");
        require(!(_stableCoin.balanceOf(beneficiary) < tokenAmount), "Crowdsale: Not enough balance");
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
    }

    /**
     * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
     * conditions are not met.
     * @param beneficiary Address performing the token purchase
     * @param weiAmount Value in wei involved in the purchase
     */
    function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
        // solhint-disable-previous-line no-empty-blocks
    }

    /**
     * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
     * its tokens.
     * @param beneficiary Address performing the token purchase
     * @param tokenAmount Number of tokens to be emitted
     */
    function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
        _token.safeTransfer(beneficiary, tokenAmount);
    }

    /**
     * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
     * tokens.
     * @param beneficiary Address receiving the tokens
     * @param tokenAmount Number of tokens to be purchased
     */
    function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
        _deliverTokens(beneficiary, tokenAmount);
    }

    /**
     * @dev Override for extensions that require an internal state to check for validity (current user contributions,
     * etc.)
     * @param beneficiary Address receiving the tokens
     * @param weiAmount Value in wei involved in the purchase
     */
    function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
        // solhint-disable-previous-line no-empty-blocks
    }

    /**
     * @dev Override to extend the way in which ether is converted to tokens.
     * @param stableCoinAmount Value in wei to be converted into tokens
     * @return Number of tokens that can be purchased with the specified _weiAmount
     */
    function _getTokenAmount(uint256 stableCoinAmount) internal view returns (uint256) {
        return stableCoinAmount.div(_rate);
    }

    /**
     * @dev Determines how ETH is stored/forwarded on purchases.
     */
    function _forwardFunds(uint256 tokenAmount) internal returns (bool){
        require(_stableCoin.transfer(_wallet, tokenAmount), "Crowdsale: Stable token transfer failed");
        return true;
    }

}

I used those contracts and with remix gas was as low as 0.01 matic.


问:
AWS Amplify Flutter - Migrating user id from guest user to authenticated user
I'm using AWS Amplify with Cognito for authenticating users in my Flutter Application.

Users can use the app without having to sign up immediately, by using Cognito's Guest Authentication feature. A user can optionally sign up later on using the Amplify.Auth.signUp method.

The problem is that after signing up and then logging in, the created user has another ID than the guest user. Is there a way to keep the old ID across signup? If not, what options do I have besides updating all of the user's database items to the new ID?

I've seen that the js version of amplify supports this behavior by default.

I'm using this code to get the user's ID:

```<code>Future<String> getUserId() async {
    final currentUser = await Amplify.Auth.fetchAuthSession(options: const CognitoSessionOptions(getAWSCredentials: true)) as CognitoAuthSession;
    final uid = currentUser.identityId?.split(':').last;
    if (uid == null) {
      throw RemoteException(S.current.error_no_user_logged_in);
    }
    return uid;
  }
</code>```

Body:
I'm using AWS Amplify with Cognito for authenticating users in my Flutter Application.

Users can use the app without having to sign up immediately, by using Cognito's Guest Authentication feature. A user can optionally sign up later on using the Amplify.Auth.signUp method.

The problem is that after signing up and then logging in, the created user has another ID than the guest user. Is there a way to keep the old ID across signup? If not, what options do I have besides updating all of the user's database items to the new ID?

I've seen that the js version of amplify supports this behavior by default.

I'm using this code to get the user's ID:

Future<String> getUserId() async {
    final currentUser = await Amplify.Auth.fetchAuthSession(options: const CognitoSessionOptions(getAWSCredentials: true)) as CognitoAuthSession;
    final uid = currentUser.identityId?.split(':').last;
    if (uid == null) {
      throw RemoteException(S.current.error_no_user_logged_in);
    }
    return uid;
  }


问:
How to send some file contents and information about the data to a REST API and fetch it using node.js or express.js?
I have a requirement where in I have to send contents of a file to a REST API endpoint along with some information about the data being sent. For example, assume I would like to send ~64KB of file data in a request:

Offset of the data in the file

Length of the data being sent

Some one or more strings like "truncate", "append", "overwrite" (called as flags)

Actual file content

I am thinking of sending offset, length, and flags (as strings) as JSON data and the actual file data in raw binary format. Is it an appropriate way to do or not? If possible can you share sample code on how to access the offset, length, flags, and file data received on server side when using node.js or express.js?

Thanks in advance.


问:
Undefined Reference to function even though I included the header file and defined the functions
I am doing some homework in C++ and I just encountered an error I couldn't fix. I defined a RingBuffer class that stores values, the logic works but I have a problem with the includes. If I don't include the .cpp file with the implementation of the methods I get an "undefined reference to function" error for every single function I defined.

rbtest.cpp (This class was given and is used to test the implementation)

```<code>#include <iostream>
#include <stdexcept>

#include "ringbuffer.hpp"

int main(void) {
    RingBuffer<int, 3> rb;
    rb.print();
    std::cout << std::boolalpha;
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_back(2);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_front(1);
    rb.push_back(3);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_back(4);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.print();
    std::cout << "pop_front: " << rb.pop_front() << std::endl;
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    std::cout << "pop_front: " << rb.pop_front() << std::endl;
    rb.push_back(5);
    rb.print();
    std::cout << "pop_back: " << rb.pop_back() << std::endl;
    std::cout << "pop_back: " << rb.pop_back() << std::endl;
    rb.print();
    try {
        rb.pop_back();
        std::cout << "This should not be printed!" << std::endl;
    }
    catch (std::exception& rangeError) {
        std::cout << "Error: " << rangeError.what() << std::endl;
    }
}
</code>```

ringbuffer.hpp

```<code>#ifndef X

#define X
#include <iostream>
#include <stdexcept>

/**
 * @brief Ring Buffer class
 *
 * @tparam T typename
 * @tparam size int
 */
template <typename T, int size>
class RingBuffer {

private:
    int back = 0, front = 0;
    T content[size];
    int counter = 0;

public:

    void push_back(T item);

    void push_front(T item);

    T pop_back();

    T pop_front();

    bool full();
    bool empty();

    void print();

};
#endif
</code>```

ringbuffer.cpp

```<code>#include "ringbuffer.hpp"

/**
 * @brief Pushes an Item into the ring buffer from the back
 *
 * @tparam T
 * @tparam size
 * @param item
 */
template <typename T, int size>
void RingBuffer<T, size>::push_back(T item) {
    if (full()) return;

    content[back] = item;
    back++;
    if (back == size) back = 0;
    counter++;

}
/**
 * @brief Pushes an item into the ring buffer from the front
 *
 * @tparam T
 * @tparam size
 * @param item
 */
template <typename T, int size>
void RingBuffer<T, size>::push_front(T item) {
    if (full()) return;

    front--;
    if (front < 0) front = size - 1;
    content[front] = item;
    counter++;

}
/**
 * @brief Pops an Item from the back and returns it
 *
 * @tparam T
 * @tparam size
 * @return T
 */
template <typename T, int size>
T RingBuffer<T, size>::pop_back() {
    if (empty()) {
        throw std::out_of_range("pop_back on empty buffer");

    }
    back--;
    if (back < 0) back = size - 1;
    T item = content[back];

    counter--;

    return item;
}
/**
 * @brief Pops an Item from the front and returns it
 *
 * @tparam T
 * @tparam size
 * @return T
 */
template <typename T, int size>
T RingBuffer<T, size>::pop_front() {
    if (empty()) {
        throw std::out_of_range("pop_front on empty buffer");

    }
    T item = content[front++];
    if (front == size) front = 0;
    counter--;

    return item;

}

/**
 * @brief Checks if ring buffer is full
 *
 * @tparam T
 * @tparam size
 * @return true if full
 * @return false if not full
 */
template <typename T, int size>
bool RingBuffer<T, size>::full() {
    return counter == size;
}

/**
 * @brief Checks if ring buffer is empty
 *
 * @tparam T
 * @tparam size
 * @return true if empty
 * @return false if not empty
 */
template <typename T, int size>
bool RingBuffer<T, size>::empty() {

    return counter == 0;
}

/**
 * @brief Prints the ring buffer with all its elements front to back, prints "Buffer is empty" if empty
 *
 * @tparam T
 * @tparam size
 */
template <typename T, int size>
void RingBuffer<T, size>::print() {

    if (empty()) std::cout << "Buffer is empty" << std::endl;
    else {
        int i = front;
        do {

            std::cout << content[i++] << "\t";

            if (i >= size) i = 0;

        } while (i != back);

        std::cout << std::endl;

    }

}
</code>```

Makefile

```<code>all: rbtest.cpp ringbuffer.hpp ringbuffer.cpp
    g++ -o ringbuffer rbtest.cpp ringbuffer.hpp ringbuffer.cpp
clean:
    rm ringbuffer
</code>```

Body:
I am doing some homework in C++ and I just encountered an error I couldn't fix. I defined a RingBuffer class that stores values, the logic works but I have a problem with the includes. If I don't include the .cpp file with the implementation of the methods I get an "undefined reference to function" error for every single function I defined.

rbtest.cpp (This class was given and is used to test the implementation)

#include <iostream>
#include <stdexcept>

#include "ringbuffer.hpp"

int main(void) {
    RingBuffer<int, 3> rb;
    rb.print();
    std::cout << std::boolalpha;
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_back(2);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_front(1);
    rb.push_back(3);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.push_back(4);
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    rb.print();
    std::cout << "pop_front: " << rb.pop_front() << std::endl;
    std::cout << "Empty: " << rb.empty() << " Full: " << rb.full() << std::endl;
    std::cout << "pop_front: " << rb.pop_front() << std::endl;
    rb.push_back(5);
    rb.print();
    std::cout << "pop_back: " << rb.pop_back() << std::endl;
    std::cout << "pop_back: " << rb.pop_back() << std::endl;
    rb.print();
    try {
        rb.pop_back();
        std::cout << "This should not be printed!" << std::endl;
    }
    catch (std::exception& rangeError) {
        std::cout << "Error: " << rangeError.what() << std::endl;
    }
}

ringbuffer.hpp

#ifndef X

#define X
#include <iostream>
#include <stdexcept>

/**
 * @brief Ring Buffer class
 *
 * @tparam T typename
 * @tparam size int
 */
template <typename T, int size>
class RingBuffer {

private:
    int back = 0, front = 0;
    T content[size];
    int counter = 0;

public:

    void push_back(T item);

    void push_front(T item);

    T pop_back();

    T pop_front();

    bool full();
    bool empty();

    void print();

};
#endif

ringbuffer.cpp

#include "ringbuffer.hpp"

/**
 * @brief Pushes an Item into the ring buffer from the back
 *
 * @tparam T
 * @tparam size
 * @param item
 */
template <typename T, int size>
void RingBuffer<T, size>::push_back(T item) {
    if (full()) return;

    content[back] = item;
    back++;
    if (back == size) back = 0;
    counter++;

}
/**
 * @brief Pushes an item into the ring buffer from the front
 *
 * @tparam T
 * @tparam size
 * @param item
 */
template <typename T, int size>
void RingBuffer<T, size>::push_front(T item) {
    if (full()) return;

    front--;
    if (front < 0) front = size - 1;
    content[front] = item;
    counter++;

}
/**
 * @brief Pops an Item from the back and returns it
 *
 * @tparam T
 * @tparam size
 * @return T
 */
template <typename T, int size>
T RingBuffer<T, size>::pop_back() {
    if (empty()) {
        throw std::out_of_range("pop_back on empty buffer");

    }
    back--;
    if (back < 0) back = size - 1;
    T item = content[back];

    counter--;

    return item;
}
/**
 * @brief Pops an Item from the front and returns it
 *
 * @tparam T
 * @tparam size
 * @return T
 */
template <typename T, int size>
T RingBuffer<T, size>::pop_front() {
    if (empty()) {
        throw std::out_of_range("pop_front on empty buffer");

    }
    T item = content[front++];
    if (front == size) front = 0;
    counter--;

    return item;

}

/**
 * @brief Checks if ring buffer is full
 *
 * @tparam T
 * @tparam size
 * @return true if full
 * @return false if not full
 */
template <typename T, int size>
bool RingBuffer<T, size>::full() {
    return counter == size;
}

/**
 * @brief Checks if ring buffer is empty
 *
 * @tparam T
 * @tparam size
 * @return true if empty
 * @return false if not empty
 */
template <typename T, int size>
bool RingBuffer<T, size>::empty() {

    return counter == 0;
}

/**
 * @brief Prints the ring buffer with all its elements front to back, prints "Buffer is empty" if empty
 *
 * @tparam T
 * @tparam size
 */
template <typename T, int size>
void RingBuffer<T, size>::print() {

    if (empty()) std::cout << "Buffer is empty" << std::endl;
    else {
        int i = front;
        do {

            std::cout << content[i++] << "\t";

            if (i >= size) i = 0;

        } while (i != back);

        std::cout << std::endl;

    }

}

Makefile

all: rbtest.cpp ringbuffer.hpp ringbuffer.cpp
    g++ -o ringbuffer rbtest.cpp ringbuffer.hpp ringbuffer.cpp
clean:
    rm ringbuffer


问:
Module Parse Failed: You may need an appropriate loader to handle this file type. ReactJS Error
I am trying to utilise AccordionJS npm in my project. However, when I try to compile the app I get this odd error that I have no idea how to react to:

Here is the error:

`Failed to compile.

./~/react-bootstrap/esm/Accordion.js
Module parse failed: C:\Users\userjohndoe\Desktop\book-app\node_modules\react-bootstrap\esm\Accordion.js Unexpected token (23:4)

You may need an appropriate loader to handle this file type.

|     flush,

|     alwaysOpen,

|     ...controlledProps

|   } = useUncontrolled(props, {

|     activeKey: 'onSelect'`


问:
TypeError: forward() missing 1 required positional argument: 'x'
Can somebody tell, please, what's wrong? I'm really don't understand (MLP and CNN models). MLP works correctly, I've this problem only with CNN. Tried to find something there but all without any result

My CNN model:

```<code>class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()

        self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=4, padding=2)
        self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, padding=2)
        self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4)
        self.conv4 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4)

        self.fc1 = nn.Linear(128 * 4 * 4, 256)
        self.fc2 = nn.Linear(256, 256)
        self.fc3 = nn.Linear(256, 10)

        self.drop = nn.Dropout(p=0.2)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.drop(x)
        x = F.relu(self.conv3(x))
        x = self.pool(F.relu(self.conv4(x)))
        x = self.drop(x)
        x = x.view(-1, 128 * 4 * 4)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
</code>```

Code with error:

```<code> conv_net_4 = CNN() ## right there I need to put something, but don't know, what exactly
 loss_fn = torch.nn.CrossEntropyLoss()
 learning_rate = 1e-4
 optimizer = torch.optim.Adam(conv_net_4.parameters(), lr=learning_rate)

 losses_4 = fit(conv_net_4, optimizer, loss_fn, 4)

 plt.plot(losses_4)
 plt.ylabel('Loss')
 plt.show()

 correct_4 = test_report(conv_net_4)
 print('Accuracy: %.2f %%' % ((np.array(correct_4)).mean()))

Traceback (here for more uderstanding):

         TypeError                                 Traceback (most
     recent call last)
         <ipython-input-62-1091c742672c> in <module>
         ----> 1 conv_net_4 = CNN()
               2 loss_fn = torch.nn.CrossEntropyLoss()
               3 learning_rate = 1e-4
               4 optimizer =
     torch.optim.Adam(conv_net_4.parameters(), lr=learning_rate)
               5

          /usr/local/lib/python3.8/dist-
    packages/torch/nn/modules/module.py in _call_impl(self, *input,
     **kwargs)
            1192         if not (self._backward_hooks or
     self._forward_hooks or self._forward_pre_hooks or
     _global_backward_hooks
            1193                 or _global_forward_hooks or
     _global_forward_pre_hooks):
         -> 1194             return forward_call(*input, **kwargs)
            1195         # Do not call functions when jit is used
            1196         full_backward_hooks, non_full_backward_hooks
     = [], []

         TypeError: forward() missing 1 required positional argument:
     'x'
</code>```

Probably problem with something in other pieces of code?

Body:
Can somebody tell, please, what's wrong? I'm really don't understand (MLP and CNN models). MLP works correctly, I've this problem only with CNN. Tried to find something there but all without any result

My CNN model:

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()

        self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=4, padding=2)
        self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4, padding=2)
        self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=4)
        self.conv4 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4)

        self.fc1 = nn.Linear(128 * 4 * 4, 256)
        self.fc2 = nn.Linear(256, 256)
        self.fc3 = nn.Linear(256, 10)

        self.drop = nn.Dropout(p=0.2)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.drop(x)
        x = F.relu(self.conv3(x))
        x = self.pool(F.relu(self.conv4(x)))
        x = self.drop(x)
        x = x.view(-1, 128 * 4 * 4)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

Code with error:

 conv_net_4 = CNN() ## right there I need to put something, but don't know, what exactly
 loss_fn = torch.nn.CrossEntropyLoss()
 learning_rate = 1e-4
 optimizer = torch.optim.Adam(conv_net_4.parameters(), lr=learning_rate)

 losses_4 = fit(conv_net_4, optimizer, loss_fn, 4)

 plt.plot(losses_4)
 plt.ylabel('Loss')
 plt.show()

 correct_4 = test_report(conv_net_4)
 print('Accuracy: %.2f %%' % ((np.array(correct_4)).mean()))

Traceback (here for more uderstanding):

         TypeError                                 Traceback (most
     recent call last)
         <ipython-input-62-1091c742672c> in <module>
         ----> 1 conv_net_4 = CNN()
               2 loss_fn = torch.nn.CrossEntropyLoss()
               3 learning_rate = 1e-4
               4 optimizer =
     torch.optim.Adam(conv_net_4.parameters(), lr=learning_rate)
               5

          /usr/local/lib/python3.8/dist-
    packages/torch/nn/modules/module.py in _call_impl(self, *input,
     **kwargs)
            1192         if not (self._backward_hooks or
     self._forward_hooks or self._forward_pre_hooks or
     _global_backward_hooks
            1193                 or _global_forward_hooks or
     _global_forward_pre_hooks):
         -> 1194             return forward_call(*input, **kwargs)
            1195         # Do not call functions when jit is used
            1196         full_backward_hooks, non_full_backward_hooks
     = [], []

         TypeError: forward() missing 1 required positional argument:
     'x'

Probably problem with something in other pieces of code?


问:
Find when was last SP\CU was installed on SQL Server using T-SQL query or powershell
I need to find when was last SP\CU was installed on SQL Server using T-SQL query or PowerShell.

Currently we can see it in

control panel--> installed updates
AND

C:\setupbootstrap\summary\logs

I have so many servers and  I don't want to login to each server and need some query for the same. Is it possible? Thanks


问:
How to update row in panda data from based on previous row condition met
I have a final data set in a data frame in panda and would like to identify weeks that are classified as a 'Winner. Weeks are classified as 'Winners' when the total count for the week is greater than the 20% the weekly average and when the previous week is not a 'Winner'. i.e., (Weekly_counts[B] > Winner_Num [H]) and the previous row is not 'Winner'

[Excel Example] (https://i.stack.imgur.com/1mAex.png)

How to do this in panda?

I've tried to use the shift() and Lamda function but not getting the expected results [I].


问:
Font files are not bundled for my production use
I am using font-awesome with my ReactJS application. Everything is fine but when I try to build my application for production use, the fonts are not bundled (all css and js files are bundled)

I use npm run build and I don't use webpack.

My question is: should I have something like a 'loader' in my package.json file to bundle the font files?

I get 404 not found in the production when it comes to font files such as .ttf and woff


问:
Write a test to check if a post has been removed from the old group
I need to check that the post has disappeared from the old group page. I need to get my old group for her slack.

```<code>   old_group_response = self.authorized_client.get(
       reverse('group_list', args=(self.group.slug,))
   )
</code>```

And compare that old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. And check another new group, that there is 1 post there. How can I write it in the right way?
I know what rubbish is written here (I'm just learning), this is what I was able to sketch.

```<code>from django import forms
from django.test import Client, TestCase
from django.urls import reverse

from ..models import Group, Post, User

NEW_POST = reverse('posts:post_create')

class PostFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.author_auth = User.objects.create_user(username='test auth')
        cls.not_author = User.objects.create_user(username='Not Author')
        cls.group = Group.objects.create(
            title='Test group_title',
            slug='test_slug',
            description='Test description')

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(PostFormTests.author_auth)
        self.authorized_client_not_author = Client()
        self.authorized_client_not_author.force_login(
            PostFormTests.not_author)

    def test_post_old_group_response(self):
        """ Check if a post has been removed from the old group."""
        post = Post.objects.create(
            group=PostFormTests.group,
            author=PostFormTests.author_auth,
            text='test post')
        group_2 = Group.objects.create(
            title='Test group_title2',
            slug='test_slug2',
            description='Test description2')
        posts_count = Post.objects.count()
        form_data = {
            'text': 'text_post',
            'group': group_2.id}
        old_group_response = self.authorized_client.get(
            reverse('posts:group_list', args=(self.group.slug)),
            data=form_data,
            follow=True)
        self.assertEqual(
            old_group_response, reverse(
                'posts:post_detail', kwargs={'post_id': post.pk}))
        self.assertEqual(Post.objects.count(), posts_count)
        self.assertEqual(old_group_response.context[
            'page_obj'].paginator.count == 0)
</code>```

Body:
I need to check that the post has disappeared from the old group page. I need to get my old group for her slack.

   old_group_response = self.authorized_client.get(
       reverse('group_list', args=(self.group.slug,))
   )

And compare that old_group_response.context['page_obj'].paginator.count equals zero. This means that there are no posts in our old group. And check another new group, that there is 1 post there. How can I write it in the right way?
I know what rubbish is written here (I'm just learning), this is what I was able to sketch.

from django import forms
from django.test import Client, TestCase
from django.urls import reverse

from ..models import Group, Post, User

NEW_POST = reverse('posts:post_create')

class PostFormTests(TestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.author_auth = User.objects.create_user(username='test auth')
        cls.not_author = User.objects.create_user(username='Not Author')
        cls.group = Group.objects.create(
            title='Test group_title',
            slug='test_slug',
            description='Test description')

    def setUp(self):
        self.authorized_client = Client()
        self.authorized_client.force_login(PostFormTests.author_auth)
        self.authorized_client_not_author = Client()
        self.authorized_client_not_author.force_login(
            PostFormTests.not_author)

    def test_post_old_group_response(self):
        """ Check if a post has been removed from the old group."""
        post = Post.objects.create(
            group=PostFormTests.group,
            author=PostFormTests.author_auth,
            text='test post')
        group_2 = Group.objects.create(
            title='Test group_title2',
            slug='test_slug2',
            description='Test description2')
        posts_count = Post.objects.count()
        form_data = {
            'text': 'text_post',
            'group': group_2.id}
        old_group_response = self.authorized_client.get(
            reverse('posts:group_list', args=(self.group.slug)),
            data=form_data,
            follow=True)
        self.assertEqual(
            old_group_response, reverse(
                'posts:post_detail', kwargs={'post_id': post.pk}))
        self.assertEqual(Post.objects.count(), posts_count)
        self.assertEqual(old_group_response.context[
            'page_obj'].paginator.count == 0)


问:
RGEE work in vegetal index and extract information in a data frame
i am working in R with RGEE package...First of all, i want to use a polygon (shapefile) and create a regular point grid (10m X 10m). In other hand, i need to extract all images for Sentinel2, create a GCI (green chlorophyll index) and clip it for the polygon. Next, I have to use the grid to extract all the values of GCI and the date for each images. Can someone help me with that?

library(sf)
library(tidyverse)
library(rgee)

ee_check()

ee_Authenticate(auth_mode = "notebook")

archivo <-  choose.files(caption = "Seleccione archivo a estandatizar (shp, gpkg)",
multi = FALSE)
file_name <- paste0(tools::file_path_sans_ext(archivo),
'_AMBIENTADO_GCI.',
tools::file_ext(archivo))

roi <- st_read(archivo)

grilla<- st_make_grid(x=datos, cellsize = 0.10, what = "centers")

plot(roi)
plot(grilla)

sf_as_ee(roi)


问:
Requeue message in MassTransit without triggering retry policy
Question: Can I requeue message without triggering retry policy in MassTransit?

For more context read bellow

General structure:

we have two entities SaleOrder and SaleReturnOrder in a microservice let's call it Sales API. Each of them has its own succeeded event SaleOrderSuceeded and SaleReturnOrderSucceeded which are published based on domain event into SQS by MassTransit and later consumed by second microservice, Inventory API.

Problem:

As expected there is much more SaleOrderSuceeded events than SaleReturnOrderSucceeded which means SaleOrderSuceeded event consumer has to handle more messages and
as a result it's slower than SaleReturnOrderSucceeded consumer, because of that in some cases Inventory API passes transaction and adds sold quantity back to inventory before it got handled by SaleOrderSuceeded event consumer and actually got subtracted from inventory, as a result this case creates more problems later in the flow.

My solution:

My solution is to check whether or not sale order has already subtracted it's quantity from inventory and than handle SaleReturnOrderSucceeded event, otherwise throw a custom error and wait for message to come back later. But it affects retry policy and the message is going to be returned only as many times as retry policy accepts to.. my question is, could I somehow requeue message without triggering retry policy?

I'll accept any suggestions to handle the validation in different way as well


问:
React Blitz.js 3rd party auth failing with passport-azure-ad
I'm attempting to swap the default auth scheme in Blitz.js with a passport-azure-ad scheme, using the OIDCStrategy. I'm getting an error that I'm not sure about and would appreciate any help! I've created a new file under src/pages/auth/openid.tsx and into inserted the following code:

```<code>import { passportAuth } from "@blitzjs/auth"
import { api } from "src/blitz-server"
import { OIDCStrategy } from "passport-azure-ad"

const users: Array<{ oid: string }> = []

var findByOid = function (oid, fn) {
  console.log("failing")
  for (var i = 0, len = users.length; i < len; i++) {
    const user = users[i]
    console.log("we are using user: ", user)
    if (user && user.oid === oid) {
      return fn(null, user)
    }
  }
  return fn(null, null)
}

export default api(
  passportAuth({
    successRedirectUrl: "/",
    errorRedirectUrl: "/",
    strategies: [
      {
        strategy: new OIDCStrategy(
          {
            identityMetadata:
              "https://login.microsoftonline.com/<tenant-nam>.onmicrosoft.com/v2.0/.well-known/openid-configuration",
            clientID: <client-id>,
            responseType: "code id_token",
            responseMode: "form_post",
            redirectUrl: "http://localhost:3000/auth/openid/callback",
            allowHttpForRedirectUrl: true,
            clientSecret: "<client-secret>",
            validateIssuer: false,
            passReqToCallback: true,
            scope: ["profile", "offline_access", "https://graph.microsoft.com/mail.read"],
            loggingLevel: "info",
            nonceMaxAmount: 5,
            useCookieInsteadOfSession: false,
            cookieEncryptionKeys: [
              { key: "12345678901234567890123456789012", iv: "123456789012" },
              { key: "abcdefghijklmnopqrstuvwxyzabcdef", iv: "abcdefghijkl" },
            ],
          },
          function (iss, sub, profile, accessToken, refreshToken, done) {
            if (!profile.oid) {
              return done(new Error("No oid found"), null)
            }
            // asynchronous verification, for effect...
            process.nextTick(function () {
              findByOid(profile.oid, function (err, user) {
                if (err) {
                  return done(err)
                }
                if (!user) {
                  // "Auto-registration"
                  users.push(profile)
                  return done(null, profile)
                }
                return done(null, user)
              })
            })
          }
        ),
      },
    ],
  })
)

</code>```

I believe the configuration is good because I can run the example from passport-azure-ad from the github examples. The only change I make is that I set redirectUrl: "http://localhost:3000/auth/openid/callback", instead of  redirectUrl: ".../return", per the blitz.js third party auth documentation. The tenantname, client_id, client_secret are redacted but I do set them to the correct values. I have also verified that the app registration is correctly set with the correct redirect uri.

I run blitz dev and when I go to the http://localhost:3000/auth/openid route I get the following error.

Here is the console output that is produced:

As you can see there is a Module not found: Can't resolve './src/build', this error only occurs if I go to the auth/openid page but the app is able to load.

Body:
I'm attempting to swap the default auth scheme in Blitz.js with a passport-azure-ad scheme, using the OIDCStrategy. I'm getting an error that I'm not sure about and would appreciate any help! I've created a new file under src/pages/auth/openid.tsx and into inserted the following code:

import { passportAuth } from "@blitzjs/auth"
import { api } from "src/blitz-server"
import { OIDCStrategy } from "passport-azure-ad"

const users: Array<{ oid: string }> = []

var findByOid = function (oid, fn) {
  console.log("failing")
  for (var i = 0, len = users.length; i < len; i++) {
    const user = users[i]
    console.log("we are using user: ", user)
    if (user && user.oid === oid) {
      return fn(null, user)
    }
  }
  return fn(null, null)
}

export default api(
  passportAuth({
    successRedirectUrl: "/",
    errorRedirectUrl: "/",
    strategies: [
      {
        strategy: new OIDCStrategy(
          {
            identityMetadata:
              "https://login.microsoftonline.com/<tenant-nam>.onmicrosoft.com/v2.0/.well-known/openid-configuration",
            clientID: <client-id>,
            responseType: "code id_token",
            responseMode: "form_post",
            redirectUrl: "http://localhost:3000/auth/openid/callback",
            allowHttpForRedirectUrl: true,
            clientSecret: "<client-secret>",
            validateIssuer: false,
            passReqToCallback: true,
            scope: ["profile", "offline_access", "https://graph.microsoft.com/mail.read"],
            loggingLevel: "info",
            nonceMaxAmount: 5,
            useCookieInsteadOfSession: false,
            cookieEncryptionKeys: [
              { key: "12345678901234567890123456789012", iv: "123456789012" },
              { key: "abcdefghijklmnopqrstuvwxyzabcdef", iv: "abcdefghijkl" },
            ],
          },
          function (iss, sub, profile, accessToken, refreshToken, done) {
            if (!profile.oid) {
              return done(new Error("No oid found"), null)
            }
            // asynchronous verification, for effect...
            process.nextTick(function () {
              findByOid(profile.oid, function (err, user) {
                if (err) {
                  return done(err)
                }
                if (!user) {
                  // "Auto-registration"
                  users.push(profile)
                  return done(null, profile)
                }
                return done(null, user)
              })
            })
          }
        ),
      },
    ],
  })
)

I believe the configuration is good because I can run the example from passport-azure-ad from the github examples. The only change I make is that I set redirectUrl: "http://localhost:3000/auth/openid/callback", instead of  redirectUrl: ".../return", per the blitz.js third party auth documentation. The tenantname, client_id, client_secret are redacted but I do set them to the correct values. I have also verified that the app registration is correctly set with the correct redirect uri.

I run blitz dev and when I go to the http://localhost:3000/auth/openid route I get the following error.

Here is the console output that is produced:

As you can see there is a Module not found: Can't resolve './src/build', this error only occurs if I go to the auth/openid page but the app is able to load.


问:
How to Open a file in Unity Android?
I need to open a kmz file from the mobile app in order to see it in google earth, So i saved the kmz file in the StreamingAssets and i copy it to the persistentDataPath, Also the file is unable to open when i copy it to this folder.

Im calling it with this:

```<code>Application.OpenURL("file://"+Application.persistentDataPath + "/CR.kmz");
</code>```

I already granted the file permissions.
I dont know how to open files from the storage with code. Help.

Title: How to Open a file in Unity Android?

Body:
I need to open a kmz file from the mobile app in order to see it in google earth, So i saved the kmz file in the StreamingAssets and i copy it to the persistentDataPath, Also the file is unable to open when i copy it to this folder.

Im calling it with this:

Application.OpenURL("file://"+Application.persistentDataPath + "/CR.kmz");

I already granted the file permissions.
I dont know how to open files from the storage with code. Help.


问:
React - Uncaught ReferenceError: combinations is not defined
Im building a small gadget for a website that uses react. But its giving me a reference error when it says that my variable "combinations" is not defined as well that there is a TypeError: wrapper is null. It works but at the same time its giving a constant error.

```<code>import React from 'react';
import './portfolio.css';

const wrapper = document.getElementById("wrapper");
console.log(wrapper)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const uniqueRand = (min, max, prev) => {
  let next = prev;
  while(prev === next) next = rand(min, max);

  return next;
}

const combinations = [
  { configuration: 1, roundness: 1 },
  { configuration: 1, roundness: 2 },
  { configuration: 1, roundness: 3 },
  { configuration: 2, roundness: 2 },
  { configuration: 2, roundness: 3 }
];

let prev = 0;

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
        combination = combinations[index];

  wrapper.dataset.configuration = combination.configuration;
  wrapper.dataset.roundness = combination.roundness;

  prev = index;
}, 3000);

const Portfolio = () => {
  return (
    <div className='RO__portfolio'>
      <div className='RO__portfolio-content' data-roundness="1" data-configuration ="1" id='wrapper'>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
      </div>
    </div>
  )
}

export default Portfolio
</code>```

It should not be giving this to errors:

Uncaught ReferenceError: combinations is not defined

Uncaught TypeError: wrapper is null

Body:
Im building a small gadget for a website that uses react. But its giving me a reference error when it says that my variable "combinations" is not defined as well that there is a TypeError: wrapper is null. It works but at the same time its giving a constant error.

import React from 'react';
import './portfolio.css';

const wrapper = document.getElementById("wrapper");
console.log(wrapper)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const uniqueRand = (min, max, prev) => {
  let next = prev;
  while(prev === next) next = rand(min, max);

  return next;
}

const combinations = [
  { configuration: 1, roundness: 1 },
  { configuration: 1, roundness: 2 },
  { configuration: 1, roundness: 3 },
  { configuration: 2, roundness: 2 },
  { configuration: 2, roundness: 3 }
];

let prev = 0;

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
        combination = combinations[index];

  wrapper.dataset.configuration = combination.configuration;
  wrapper.dataset.roundness = combination.roundness;

  prev = index;
}, 3000);

const Portfolio = () => {
  return (

  )
}

export default Portfolio

It should not be giving this to errors:

Uncaught ReferenceError: combinations is not defined

Uncaught TypeError: wrapper is null


问:
NGINX configuration to Angular app not working
I am using NGINX to point to several Angular applications. I build all applications with a base-href and deploy-url equal to the app name - and then deploy those to the server. Example:

```<code>"server:build:app1": "nx build --baseHref='/app1/' --deployUrl='/app1/'
</code>```

The navigation buttons that bring me to these apps just do this:

```<code>window.location.href = {the path} // which would be s/thing like */app1*
</code>```

In my nginx.conf I then point to these files like this:

```<code>location /app1 {
    proxy_set_header Host {the host}
    proxy_pass {the url}
}
</code>```

And this works just great for all apps except 1 -- the one i'm not in control of building.

When I attempt to simply point to it using the above approach I get the following error:

```<code>Failed to load module script: Expected a JavaScript module script but the server responded with a mime-type of "text/html"...
</code>```

I know this is a red herring because the app does run on a domain elsewhere and works. I believe I get the error because when I attempt to load the application into my route I am not pointing to the assets correctly.

The question is this; is that assumption correct -- that the problem is loading the app into my route -- and, if so, how can I fix it so I don't have to ask them to rebuild their app with a -- base-href that will work with my route.

Thank you for any helpful tips.

Body:
I am using NGINX to point to several Angular applications. I build all applications with a base-href and deploy-url equal to the app name - and then deploy those to the server. Example:

"server:build:app1": "nx build --baseHref='/app1/' --deployUrl='/app1/'

The navigation buttons that bring me to these apps just do this:

window.location.href = {the path} // which would be s/thing like */app1*

In my nginx.conf I then point to these files like this:

location /app1 {
    proxy_set_header Host {the host}
    proxy_pass {the url}
}

And this works just great for all apps except 1 -- the one i'm not in control of building.

When I attempt to simply point to it using the above approach I get the following error:

Failed to load module script: Expected a JavaScript module script but the server responded with a mime-type of "text/html"...

I know this is a red herring because the app does run on a domain elsewhere and works. I believe I get the error because when I attempt to load the application into my route I am not pointing to the assets correctly.

The question is this; is that assumption correct -- that the problem is loading the app into my route -- and, if so, how can I fix it so I don't have to ask them to rebuild their app with a -- base-href that will work with my route.

Thank you for any helpful tips.


问:
Google Recaptcha work local and get error on live
This is an old site based on dot.net and iis

I try to add the option of google recaptcha to my site

but I got the error

```<code>The underlying connection was closed: An unexpected error occurred on a receive
</code>```

This is my current code (as I said this is work on the local dev)

```<code> public static string Validate(string EncodedResponse)
        {
            var client = new System.Net.WebClient();

            string PrivateKey = Utils.GetConfigValue("reCAPTCHA.SecretKey");

            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            ReCaptchaClass captchaResponse = js.Deserialize<ReCaptchaClass>(GoogleReply);

            return captchaResponse.Success;

        }
</code>```

Body:
This is an old site based on dot.net and iis

I try to add the option of google recaptcha to my site

but I got the error

The underlying connection was closed: An unexpected error occurred on a receive

This is my current code (as I said this is work on the local dev)

 public static string Validate(string EncodedResponse)
        {
            var client = new System.Net.WebClient();

            string PrivateKey = Utils.GetConfigValue("reCAPTCHA.SecretKey");

            var GoogleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", PrivateKey, EncodedResponse));
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            ReCaptchaClass captchaResponse = js.Deserialize<ReCaptchaClass>(GoogleReply);

            return captchaResponse.Success;

        }


问:
prepareForValidation does not work Laravel
I want to make a whitelist of id that can be created, but for some reason it doesn't work

```<code>    protected function prepareForValidation(){
        $WhiteListes = WhiteList::all();

        foreach ($WhiteListes as $WhiteList){
            if ($WhiteList->server_id == $this->id) {
                $this->merge(['id' => $this->id]);
            } else {
                $this->merge(['id' => null]);
            }
        }

    }
</code>```

This returns null. Although it should return an $this->id

I've already tried doing this

```<code>        foreach ($WhiteListes as $WhiteList){
            $test = $WhiteList->server_id == $this->id;
            dd($test);
        }
</code>```

This returns True to me
Why does it work so crookedly? And how do I do it right

Body:
I want to make a whitelist of id that can be created, but for some reason it doesn't work

    protected function prepareForValidation(){
        $WhiteListes = WhiteList::all();

        foreach ($WhiteListes as $WhiteList){
            if ($WhiteList->server_id == $this->id) {
                $this->merge(['id' => $this->id]);
            } else {
                $this->merge(['id' => null]);
            }
        }

    }

This returns null. Although it should return an $this->id

I've already tried doing this

        foreach ($WhiteListes as $WhiteList){
            $test = $WhiteList->server_id == $this->id;
            dd($test);
        }

This returns True to me
Why does it work so crookedly? And how do I do it right


问:
map dependend xarray coordinates
I have an xarray with dimensions in x,y which also has coordinates in lat,lon. Since these are shifted grids the lat and lon are both dependend on x,y. I want to convert my coordinate system to lat, lon but I am unsure how to achieve this.

I have tried to assign different coordinates, or to stack and unstack the dimensions, but unfortunatly this is not really getting me closer to my solution.

Title: map dependend xarray coordinates