问:
Send PHP cURL Request to QR API with multipart/form-data that includes several content-types and inputs with file upload
Language: PHP

Related Links:

RapidApi

Linqr

Problem: Unable to figure out how to post to API with several content types in a multipart/form-data PHP cURL request.

I am trying to reproduce the functionality of Linqr in my own project with the added feature of batch QR production.

I'm currently able to create a custom single QR with custom image if the image file is already hosted on a URL.

I'm struggling to figure out how to POST the entire form including the user choices for the QR AND an uploaded file for the logo.

How do I access the logo file information when a user uploads to the document and then add that to my code to post to the API so it returns the full custom QR with the user uploaded image?

I've tried using the following but it only displays two arrays of 'items' and 'output' without being able to access the nested arrays.

Also, I'm completely lost on how to get the uploaded image to post at the same time of the other information.

Based off this post: GIST

PHP File:

```<code><?php
header("Location: home.php");

// data fields for POST request

$postFields = array(

  'items'=> array(
      'image' => array(
          'uri' => $logo,
          'modules' => true
      ),
      'data' => $qrUrl,
      'style' => array(
          'module' => array(
              'color' => 'black',
              'shape' => 'default'
          ),
          'inner_eye' => array(
              'shape' => 'default'
          ),
          'outer_eye' => array(
              'shape' => 'default'
          ),
          'background' => array()
      ),
      'size' => array(
          'width' => 200,
          'quite_zone' => 4,
          'error_correction' => 'M'
      ),
      'output' => array(
          'filename' => 'qrcode',
          'format' => 'png'
      )
  ),
  'output' => array(
      'filename' => 'qrcodes',
      'format' => 'zip'
  )

);

// files to upload
$filenames = $_FILES['logoUpload']['tmp_name'];

$files = array();
foreach ($filenames as $f){
   $files[$f] = file_get_contents($f);
}

// URL to upload to
$url = "urltouploadto";

$curl = curl_init();

$url_data = http_build_query($postFields);

$boundary = 011000010111000001101001;
$delimiter = '-----' . $boundary;

$post_data = build_data_files($boundary, $postFields, $files);

echo "```";
print_r($post_data);
echo "```";

echo $post_data;

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => $post_data,
  CURLOPT_HTTPHEADER => array(
        "X-RapidAPI-Host: qrcode3.p.rapidapi.com",
        "X-RapidAPI-Key: somekey",
    "Content-Type: multipart/form-data; boundary=" . $delimiter,
    "Content-Length: " . strlen($post_data)

  ),

));

//
$response = curl_exec($curl);

$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

var_dump($response);
$err = curl_error($curl);

echo "error";
var_dump($err);
curl_close($curl);

function build_data_files($boundary, $postFields, $files){
    $data = '';
    $eol = "\r\n";

    $delimiter = '-------------' . $boundary;
    echo "This is the postFieldds data: <br><br>";
    foreach ($postFields as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
            . $content . $eol;

        echo $data;
    }

    echo "This is the files data: <br><br>";
    foreach ($files as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
            //. 'Content-Type: image/png'.$eol
            . 'Content-Transfer-Encoding: binary'.$eol
            ;

        $data .= $eol;
        $data .= $content . $eol;
        echo $data;

    }
    $data .= "--" . $delimiter . "--".$eol;

    return $data;
}
</code>```

Do I need to do something like this to "GET" the image that was just uploaded or is there a way to capture that file information before the original POST is sent to the API?

```<code>
// Get logo image id that was just posted:

if (isset($response)) {
    $curlImage = curl_init();

    $result = json_decode($reponse, true);
    $imageId = $result["id"];

    curl_setopt_array($curlImage, [
        CURLOPT_URL => "https://qrcode3.p.rapidapi.com/images/$imageId",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "X-RapidAPI-Host: qrcode3.p.rapidapi.com",
            "X-RapidAPI-Key: somekey"
        ],
    ]);

    $logoResponse = curl_exec($curlImage);
    $err = curl_error($curlImage);

    curl_close($curlImage);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $logoResponse;
    }
}
</code>```

Body:
Language: PHP

Related Links:

RapidApi

Linqr

Problem: Unable to figure out how to post to API with several content types in a multipart/form-data PHP cURL request.

I am trying to reproduce the functionality of Linqr in my own project with the added feature of batch QR production.

I'm currently able to create a custom single QR with custom image if the image file is already hosted on a URL.

I'm struggling to figure out how to POST the entire form including the user choices for the QR AND an uploaded file for the logo.

How do I access the logo file information when a user uploads to the document and then add that to my code to post to the API so it returns the full custom QR with the user uploaded image?

I've tried using the following but it only displays two arrays of 'items' and 'output' without being able to access the nested arrays.

Also, I'm completely lost on how to get the uploaded image to post at the same time of the other information.

Based off this post: GIST

PHP File:

<?php
header("Location: home.php");

// data fields for POST request

$postFields = array(

  'items'=> array(
      'image' => array(
          'uri' => $logo,
          'modules' => true
      ),
      'data' => $qrUrl,
      'style' => array(
          'module' => array(
              'color' => 'black',
              'shape' => 'default'
          ),
          'inner_eye' => array(
              'shape' => 'default'
          ),
          'outer_eye' => array(
              'shape' => 'default'
          ),
          'background' => array()
      ),
      'size' => array(
          'width' => 200,
          'quite_zone' => 4,
          'error_correction' => 'M'
      ),
      'output' => array(
          'filename' => 'qrcode',
          'format' => 'png'
      )
  ),
  'output' => array(
      'filename' => 'qrcodes',
      'format' => 'zip'
  )

);

// files to upload
$filenames = $_FILES['logoUpload']['tmp_name'];

$files = array();
foreach ($filenames as $f){
   $files[$f] = file_get_contents($f);
}

// URL to upload to
$url = "urltouploadto";

$curl = curl_init();

$url_data = http_build_query($postFields);

$boundary = 011000010111000001101001;
$delimiter = '-----' . $boundary;

$post_data = build_data_files($boundary, $postFields, $files);

echo "
";
print_r($post_data);
echo "
";

echo $post_data;

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  //CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => $post_data,
  CURLOPT_HTTPHEADER => array(
        "X-RapidAPI-Host: qrcode3.p.rapidapi.com",
        "X-RapidAPI-Key: somekey",
    "Content-Type: multipart/form-data; boundary=" . $delimiter,
    "Content-Length: " . strlen($post_data)

  ),

));

//
$response = curl_exec($curl);

$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";

//print_r($info['request_header']);

var_dump($response);
$err = curl_error($curl);

echo "error";
var_dump($err);
curl_close($curl);

function build_data_files($boundary, $postFields, $files){
    $data = '';
    $eol = "\r\n";

    $delimiter = '-------------' . $boundary;
    echo "This is the postFieldds data:

";
    foreach ($postFields as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . "\"".$eol.$eol
            . $content . $eol;

        echo $data;
    }

    echo "This is the files data:

";
    foreach ($files as $name => $content) {
        $data .= "--" . $delimiter . $eol
            . 'Content-Disposition: form-data; name="' . $name . '"; filename="' . $name . '"' . $eol
            //. 'Content-Type: image/png'.$eol
            . 'Content-Transfer-Encoding: binary'.$eol
            ;

        $data .= $eol;
        $data .= $content . $eol;
        echo $data;

    }
    $data .= "--" . $delimiter . "--".$eol;

    return $data;
}

Do I need to do something like this to "GET" the image that was just uploaded or is there a way to capture that file information before the original POST is sent to the API?

// Get logo image id that was just posted:

if (isset($response)) {
    $curlImage = curl_init();

    $result = json_decode($reponse, true);
    $imageId = $result["id"];

    curl_setopt_array($curlImage, [
        CURLOPT_URL => "https://qrcode3.p.rapidapi.com/images/$imageId",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => [
            "X-RapidAPI-Host: qrcode3.p.rapidapi.com",
            "X-RapidAPI-Key: somekey"
        ],
    ]);

    $logoResponse = curl_exec($curlImage);
    $err = curl_error($curlImage);

    curl_close($curlImage);

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $logoResponse;
    }
}


来源: stackexchange

问:
Integration test with mongoose, express and mocha
I am running the following test code

import mongoose from "mongoose";
import * as dotenv from "dotenv";
import { app } from "../server";
import chai, { expect } from "chai";
import chaiHttp from "chai-http";

chai.use(chaiHttp);
dotenv.config();
mongoose.set("strictQuery", true);

const company = require("./companyData.json");

const uri = process.env.CONTRACTS_DB_URI || "";

describe("API company crud", () => {
  before((done) => {
    mongoose.connect(uri);
    const db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error"));
    db.once("open", () => {
      console.log("We are connected to test database!");
      done();
    });
  });
  after(async () => {
    await mongoose.connection.close();
  });
  describe("Read operation", () => {
    it("should yield error for a GET at a non existing route at /company", (done) => {
      chai
        .request(app)
        .get("/company/NONEXISTING")
        .end((_, res) => {
          expect(res).to.have.status(404);
          expect(res.body).to.be.empty;
          done();
        });
    });
    it("should yield error response for a GET at /company", (done) => {
      chai
        .request(app)
        .get("/company")
        .end((_, res) => {
          expect(res).to.have.status(404);
          expect(res.body).to.be.empty;
          done();
        });
    });
    });
```
<p>The express app is</p>
<pre class="lang-js prettyprint-override"><code>import { config } from "dotenv";
import express from "express"
import cors from "cors"
import mongoose from "mongoose";
import { companyRouter } from "./routes/company";
import { personRouter } from "./routes/person";

mongoose.set('strictQuery', false);
config();
export const app = express()

app.use(cors());
app.use(express.json());

const uri = process.env.CONTRACTS_DB_URI || "";
mongoose.connect(uri);

const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

app.use('/company', companyRouter);
app.use('/person', personRouter);

const port = process.env.PORT;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`)
})
</code>```

Apparently I am not able to either:

establish a connection to the MongoDB Atlas remote database

close the connection when the tests teriminates

What would it be the correct way to:

Establish successfully a connection with MongoDB Atlas

Run tests

Close the connection

I have tried using the before and after mocha hooks, but the connection seems to persist

ContentLicense: CC BY-SA 4.0

Body:
I am running the following test code

import mongoose from "mongoose";
import * as dotenv from "dotenv";
import { app } from "../server";
import chai, { expect } from "chai";
import chaiHttp from "chai-http";

chai.use(chaiHttp);
dotenv.config();
mongoose.set("strictQuery", true);

const company = require("./companyData.json");

const uri = process.env.CONTRACTS_DB_URI || "";

describe("API company crud", () => {
  before((done) => {
    mongoose.connect(uri);
    const db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error"));
    db.once("open", () => {
      console.log("We are connected to test database!");
      done();
    });
  });
  after(async () => {
    await mongoose.connection.close();
  });
  describe("Read operation", () => {
    it("should yield error for a GET at a non existing route at /company", (done) => {
      chai
        .request(app)
        .get("/company/NONEXISTING")
        .end((_, res) => {
          expect(res).to.have.status(404);
          expect(res.body).to.be.empty;
          done();
        });
    });
    it("should yield error response for a GET at /company", (done) => {
      chai
        .request(app)
        .get("/company")
        .end((_, res) => {
          expect(res).to.have.status(404);
          expect(res.body).to.be.empty;
          done();
        });
    });
    });

The express app is

import { config } from "dotenv";
import express from "express"
import cors from "cors"
import mongoose from "mongoose";
import { companyRouter } from "./routes/company";
import { personRouter } from "./routes/person";

mongoose.set('strictQuery', false);
config();
export const app = express()

app.use(cors());
app.use(express.json());

const uri = process.env.CONTRACTS_DB_URI || "";
mongoose.connect(uri);

const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

app.use('/company', companyRouter);
app.use('/person', personRouter);

const port = process.env.PORT;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`)
})

Apparently I am not able to either:

establish a connection to the MongoDB Atlas remote database

close the connection when the tests teriminates

What would it be the correct way to:

Establish successfully a connection with MongoDB Atlas

Run tests

Close the connection

I have tried using the before and after mocha hooks, but the connection seems to persist


问:
Missing ligature strategy in an icon font setup
I use icomoon.io to create and manage my icon fonts. It's excellent and you can set "ligatures" for the text you want to display the icon.

However, I cannot find a sane way to handle missing ligatures to display a default or "missing" icon.

One insane way was I created an icon component and check the text against an array of ligatures. But this would mean that I must maintain the array to match the icons in my font.

```<code>everyDangLigature = ['star', 'arrow-up', ...]

iconText = everyDangLigature.includes(str) ? str : 'missing';
</code>```

IcoMoon wrote me back with

...if you parse the CMAP table of the font, you could check if a glyph
exists by its code point.

Also asked the opentypejs group.

How does one go about parsing the CMAP table of the font?

Is there another way to elegantly handle missing ligatures in our icon fonts?

Body:
I use icomoon.io to create and manage my icon fonts. It's excellent and you can set "ligatures" for the text you want to display the icon.

However, I cannot find a sane way to handle missing ligatures to display a default or "missing" icon.

One insane way was I created an icon component and check the text against an array of ligatures. But this would mean that I must maintain the array to match the icons in my font.

everyDangLigature = ['star', 'arrow-up', ...]

iconText = everyDangLigature.includes(str) ? str : 'missing';

IcoMoon wrote me back with

...if you parse the CMAP table of the font, you could check if a glyph
exists by its code point.

Also asked the opentypejs group.

How does one go about parsing the CMAP table of the font?

Is there another way to elegantly handle missing ligatures in our icon fonts?


问:
how to access a specific value inside an array of objects and sum them
How can I access each percent_value to sum all of them to calculate the average?

I did that but I couldn't sum the values to return, I can only access them. and I know that doing many loops in a row is not a good practice. So if anyone can help me... =(

```<code>  for (const [sectorName, sectorObjectArrays] of Object.entries(data.sectors)) {
    console.log(`sectorName ${sectorName}: sectorObjectArrays ${sectorObjectArrays}`);
    // sectorName sector1: sectorObjectArrays [object Object],[object Object],[object Object]
    for (const [sectorObjectArraysI, sectorObjectArraysProperties] of Object.entries(sectorObjectArrays)) {
      console.log(`sectorObjectArraysProperties ${sectorObjectArraysProperties.percent_value}`);
      // sectorObjectArraysProperties 1
      // sectorObjectArraysProperties 2
      // sectorObjectArraysProperties 3
    }
  }
</code>```

I have this JSON:

```<code>data: {
  "sectors": {
    "sector1": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ],
    "sector2": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ],
    "sector3": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ]
  },
  "avarageSectors": {

  }
}
</code>```

Body:
How can I access each percent_value to sum all of them to calculate the average?

I did that but I couldn't sum the values to return, I can only access them. and I know that doing many loops in a row is not a good practice. So if anyone can help me... =(

  for (const [sectorName, sectorObjectArrays] of Object.entries(data.sectors)) {
    console.log(`sectorName ${sectorName}: sectorObjectArrays ${sectorObjectArrays}`);
    // sectorName sector1: sectorObjectArrays [object Object],[object Object],[object Object]
    for (const [sectorObjectArraysI, sectorObjectArraysProperties] of Object.entries(sectorObjectArrays)) {
      console.log(`sectorObjectArraysProperties ${sectorObjectArraysProperties.percent_value}`);
      // sectorObjectArraysProperties 1
      // sectorObjectArraysProperties 2
      // sectorObjectArraysProperties 3
    }
  }

I have this JSON:

data: {
  "sectors": {
    "sector1": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ],
    "sector2": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ],
    "sector3": [
      {
        "name": "name1",
        "percent_value": 1
      },
            {
        "name": "name2",
        "percent_value": 2
      },
      {
        "name": "name3",
        "percent_value": 3
      },
    ]
  },
  "avarageSectors": {

  }
}


问:
C Array Points to Itself
I have the following C code:

```<code>char arr[1];
printf("%p %p\n", &arr, arr);
</code>```

The values of &arr and arr printed are always the same. This means that arr contains the location of itself.

If I dereference the array and write a value to it like so:

```<code> *arr = 'a';
</code>```

I expect it to overwrite the value in arr because arr points to itself.

But this doesn't happen. When I print the value of arr again:

```<code>printf("%p\n", arr);
</code>```

It contains the same old value which is the location to itself.

Why doesn't arr get overwritten?

Edit: I tried the following links but none of them answered my question exactly:

What is array to pointer decay?

Does an Array variable point to itself?

Title: C Array Points to Itself

Body:
I have the following C code:

char arr[1];
printf("%p %p\n", &arr, arr);

The values of &arr and arr printed are always the same. This means that arr contains the location of itself.

If I dereference the array and write a value to it like so:

 *arr = 'a';

I expect it to overwrite the value in arr because arr points to itself.

But this doesn't happen. When I print the value of arr again:

printf("%p\n", arr);

It contains the same old value which is the location to itself.

Why doesn't arr get overwritten?

Edit: I tried the following links but none of them answered my question exactly:

What is array to pointer decay?

Does an Array variable point to itself?


问:
setting boundaries of player in pygame
Greeting, I trying to set the boundaries for players in a game so they do not go passed the boundaries of the screen. They only move in the x-axis.

Bellow is the code for the player class. Right now In the move method I am trying to set a distance relative to the rectangle object(the player) do that it does not go past a certain points to the left and right of the x-axis. However, right now I keep getting the error

if self.rect.left + dx < 0:
AttributeError: 'tuple' object has no attribute 'left'
```
</blockquote>
<p>when I run the code.</p>
<pre class="lang-py prettyprint-override"><code>class Player():
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect((x,y, width, height))

    def move(self, screen_width, screen_height):
        SPEED = 10
        dx = 0
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.x -= SPEED
            dx = -SPEED

        if keys[pygame.K_RIGHT]:
            self.x += SPEED
            dx = SPEED

        # ensure player stays on screen
        if self.rect.left + dx < 0:
            self.rect.x += -self.rect.left
        if self.rect.right + dx > screen_width:
            self.rect.x += screen_width - self.rect.right

        self.update()

    def update(self):
        # update player position
        self.rect = (self.x, self.y, self.width, self.height)

</code>```

Title: setting boundaries of player in pygame

Body:
Greeting, I trying to set the boundaries for players in a game so they do not go passed the boundaries of the screen. They only move in the x-axis.

Bellow is the code for the player class. Right now In the move method I am trying to set a distance relative to the rectangle object(the player) do that it does not go past a certain points to the left and right of the x-axis. However, right now I keep getting the error

if self.rect.left + dx < 0:
AttributeError: 'tuple' object has no attribute 'left'

when I run the code.

class Player():
    def __init__(self, x, y, width, height, color):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect((x,y, width, height))

    def move(self, screen_width, screen_height):
        SPEED = 10
        dx = 0
        keys = pygame.key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.x -= SPEED
            dx = -SPEED

        if keys[pygame.K_RIGHT]:
            self.x += SPEED
            dx = SPEED

        # ensure player stays on screen
        if self.rect.left + dx < 0:
            self.rect.x += -self.rect.left
        if self.rect.right + dx > screen_width:
            self.rect.x += screen_width - self.rect.right

        self.update()

    def update(self):
        # update player position
        self.rect = (self.x, self.y, self.width, self.height)


问:
Uploading sharedflows using the Google cloud platform SDK in Python
Trying to use the Google Cloud SDK library for Python and was trying to use this particular method to upload a sharedflows .zip file,

https://googleapis.github.io/google-api-python-client/docs/dyn/apigee_v1.organizations.sharedflows.html#create

However, I ran into an issue on exactly how to attach the file to the request. The sharedflows file is a .zip file and I have tried the following

Read the zip file as

file = open("sharedflow.zip", "rb")

stringrepresentation = file.read().decode('latin_1')

and passed it to the request with parameters:

parent = "path/to/org",

name = "sharedflowExample",

action = "import"

 body = {

        "data" : string_representation

}

Because I am decoding the zip file, it blows up the actual size which exceeds the 15mb size that GCP requires. if I don't decode the zip file, and pass just the file itself, I then get a JSON error that it is not serializable. How exactly do I place the zip file into the request without exceeding the 15mb requirement?


问:
c# : Issues running hangfire job when creating expression
Traying to create an expression and delegate hangfire to run it

This is my task to be executed

```<code>public class MathClass : IBackgroundJob<MatchClassParams>
{
    public Task RunJobAsync(MatchClassParams payload)
    {
        return Task.FromResult(payload.A + payload.B);
    }
}

public class MatchClassParams : IBackgroundJobPayload
{
    public int A { get; set; }
    public int B { get; set; }
}
</code>```

This is my code

```<code> var calculator = new MathClass();

 MethodInfo methodInfo = typeof(MathClass).GetMethod("RunJobAsync");

 ParameterExpression param = Expression.Parameter(typeof(MatchClassParams), "payload");

 var thisParameter = Expression.Constant(calculator);

 MethodCallExpression methodCall = Expression.Call(thisParameter, methodInfo, param);

 Expression<Func<MatchClassParams, Task>> expression = Expression.Lambda<Func<MatchClassParams, Task>>(
     methodCall,
     new ParameterExpression[] { param }
 );

// IBackgroundJobClient _backgroundJobClient
_backgroundJobClient.Enqueue(lambda);
</code>```

When hangfire tries to execute the expression I'm getting

variable 'payload' of type 'AnalyseApi.Scheduler.MatchClassParams' referenced from scope '', but it is not defined

Body:
Traying to create an expression and delegate hangfire to run it

This is my task to be executed

public class MathClass : IBackgroundJob<MatchClassParams>
{
    public Task RunJobAsync(MatchClassParams payload)
    {
        return Task.FromResult(payload.A + payload.B);
    }
}

public class MatchClassParams : IBackgroundJobPayload
{
    public int A { get; set; }
    public int B { get; set; }
}

This is my code

 var calculator = new MathClass();

 MethodInfo methodInfo = typeof(MathClass).GetMethod("RunJobAsync");

 ParameterExpression param = Expression.Parameter(typeof(MatchClassParams), "payload");

 var thisParameter = Expression.Constant(calculator);

 MethodCallExpression methodCall = Expression.Call(thisParameter, methodInfo, param);

 Expression<Func<MatchClassParams, Task>> expression = Expression.Lambda<Func<MatchClassParams, Task>>(
     methodCall,
     new ParameterExpression[] { param }
 );

// IBackgroundJobClient _backgroundJobClient
_backgroundJobClient.Enqueue(lambda);

When hangfire tries to execute the expression I'm getting

variable 'payload' of type 'AnalyseApi.Scheduler.MatchClassParams' referenced from scope '', but it is not defined


问:
How to access http service running on windows from docker inside wsl2
I'm running an http service on win 10, listen at 0.0.0.0:8890
and a container instance running on wsl2

I want to access the 8890 port opened on windows from inside the container, I know ssh port portwarding from wsl2 to windows can do this, but is there an easier way to do this ?


问:
Preloading Pivot Table In Schedule efficiency
I have a User model which has many Postcode Sectors . These sectors link up to a large dataset of Properties and the subset of properties from this large set are pulled into a smaller working table overnight for the total set of each user.

Given this dataset is quite large, would it be more efficient to also load a pivot table for a many to many relationship between User and Property when creating the job (which itself may be larger than the table being created due to duplicated sectors) or simply query the Properties table through these postcode sectors when needed?

The Properties table has quite a large amount of columns (30+) and has always been tough to query quickly in other applications.

Any tips of what would be advisable are appreciated.


问:
I'm struggling to resolve 2 seemingly ireconsilable dependancy clashes
I have 2 libraries which a code base I'm trying to load and run locally use:

django-storages==1.10.1

django-pyodbc-azure==2.1.0.0

The problem I have is I either get this error:

django-storages 1.13.2 requires Django>=3.2, but you have django 2.2 which is incompatible., or this one if I try to resolve the first error:

django-pyodbc-azure 2.1.0.0 requires Django<2.2,>=2.1.0, but you have django 2.2.1 which is incompatible.

Resolving one causes a upgrade or downgrade of Django which triggers either one or the other of the above errors.

How do I resolve this?

Thanks!


问:
Loading static files in template with background-image: url()
I'm building a template and I want to set an image as background with background-image: url(). Can anyone help me How can I load the image in the url()?

HTML file(template):

DanielJohansson

                I am

a web developer.

a blogger.

a freelancer.

a photographer.

```
<p><strong>CSS file(layout.html)</strong>:</p>
<pre class="lang-css prettyprint-override"><code>.card-inner.card-started {
    text-align: center;
}

.card-inner.card-started .slide {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #262628;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

.card-inner.card-started .slide:after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: #181818;
    opacity: 0.6;
}
</code>```

Setting.py:

STATIC_URL = 'static/'

STATICFILES_DIR = [
    path.join(BASE_DIR, 'static'),
]

STATIC_ROOT = path.join(BASE_DIR, 'static')
```
<p><strong>homepage_app/urls.py:</strong></p>
<pre class="lang-py prettyprint-override"><code>urlpatterns = [
    path('', views.home)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

POV: This code had a pre loader that I deleted it, I thought that maybe the problem is there.

pre loader HTML:

```
<p>I tried to solve it with this code:</p>
<pre class="lang-html prettyprint-override"><code><div class="slide" style="background: url('/static/images/bg.jpg');"></div>
</code>```

but its not working.

And how can I set an img tag as background here?

EDIT:

I changed the CSS to:

.card-inner.card-started .slide {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #262628;
    background-image: url("/static/images/bg.jpg");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}
```

Now I can open the image in inspect(I think the image is loaded), But the page is all black and I can't see the image.

Body:
I'm building a template and I want to set an image as background with background-image: url(). Can anyone help me How can I load the image in the url()?

HTML file(template):

DanielJohansson

                I am

a web developer.

a blogger.

a freelancer.

a photographer.

CSS file(layout.html):

.card-inner.card-started {
    text-align: center;
}

.card-inner.card-started .slide {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #262628;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

.card-inner.card-started .slide:after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: #181818;
    opacity: 0.6;
}

Setting.py:

STATIC_URL = 'static/'

STATICFILES_DIR = [
    path.join(BASE_DIR, 'static'),
]

STATIC_ROOT = path.join(BASE_DIR, 'static')

homepage_app/urls.py:

urlpatterns = [
    path('', views.home)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

POV: This code had a pre loader that I deleted it, I thought that maybe the problem is there.

pre loader HTML:

I tried to solve it with this code:

but its not working.

And how can I set an img tag as background here?

EDIT:

I changed the CSS to:

.card-inner.card-started .slide {
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #262628;
    background-image: url("/static/images/bg.jpg");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
}

Now I can open the image in inspect(I think the image is loaded), But the page is all black and I can't see the image.


问:
Angular - Google Maps API integration in Module
I'm working on an Angular project and I installed the "@angular/google-maps" package to use <google-map></google-map>

To make the Map work, you must inject a script with the API KEY on the index.html file.

The problem is that our project is not a SPA, we produce individual web components that we deliver separately.

I want to know if there is a method to inject the script on the concerned module ( eg : maps.module.ts ) which will use the Map without the use of index.html


问:
How to fix TypeScript error for static import images in nextjs
I am trying to optimize images in my nextjs app, but for some reason, I am facing an issue that says: Cannot find module '/images/homeBg.jpg' or its corresponding type declarations.

The image is stored in public/images/name.jpg.

```<code>import { Layout } from '@common';
import Trips from '@ui/Trips/Trips';
import Image from 'next/image';
import bgImage from '/images/homeBg.jpg';
const HomePage = () => {
  return (
    <div className="relative h-screen w-full">
      <Image
        src={bgImage}
        fill
        className="-z-10 object-cover"
        alt="backgound_image_for_home_page"
      />
      <div className="mx-auto flex h-full w-full max-w-[2000px] flex-col space-y-10 px-7 py-36 lg:px-14">
        <h3 className="text-3xl font-normal leading-10 tracking-wider text-white lg:text-4xl">
          Welcome back, <br /> <span className="font-bold">Nedim!</span>
        </h3>
        <Trips />
      </div>
    </div>
  );
};

export default HomePage;

HomePage.layout = Layout;
</code>```

Body:
I am trying to optimize images in my nextjs app, but for some reason, I am facing an issue that says: Cannot find module '/images/homeBg.jpg' or its corresponding type declarations.

The image is stored in public/images/name.jpg.

import { Layout } from '@common';
import Trips from '@ui/Trips/Trips';
import Image from 'next/image';
import bgImage from '/images/homeBg.jpg';
const HomePage = () => {
  return (

      <Image
        src={bgImage}
        fill
        className="-z-10 object-cover"
        alt="backgound_image_for_home_page"
      />

          Welcome back,
 Nedim!

        <Trips />

  );
};

export default HomePage;

HomePage.layout = Layout;


问:
I suddenly get an unresolved reference error in my adapter class for the RecyclerView
everyone. I suddenly get an Unresolved reference error displayed in my layouts in RecyclerView. I've already restarted Android Studio, rebuilt and cleaned the project. All without success.

AddNewHomeFragment.kt:

```<code>class AddNewHomeFragment : Fragment() {

listImg = ArrayList()
var rv_img:RecyclerView = view.findViewById(R.id.recyclerViewImgs)
rv_img.layoutManager = GridLayoutManager(requireContext(),3)

adapter = CustomerAdapter(requireContext(),listImg){
 var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
 startActivityForResult(intent,IMAGE_REQUEST)
}

rv_img.adapter = adapter

...
}
</code>```

My CustomAdapter for RecyclerView:

```<code>class CustomerAdapter(val context: Context,
                  private val listImg:ArrayList<Int>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {

class MyCustomViewHolder(view: View):RecyclerView.ViewHolder(view) {
    //Unresolved reference: customImg
    val customImg:ImageView = view.findViewById(R.id.customImg)

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCustomViewHolder {
    //Unresolved reference: single_img
    val inflate = LayoutInflater.from(context).inflate(R.layout.single_img,parent,false)

    return MyCustomViewHolder(inflate)
}

override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
    holder.customImg.setImageResource(listImg[position])
    holder.customImg.setOnClickListener {
        this@CustomerAdapter.onClickFunction?.invoke(listImg[position])
    }
}

override fun getItemCount(): Int {
   return listImg.size
}
</code>```

}

fragment_add_new_home.xml:

```<code> <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewImgs"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</androidx.recyclerview.widget.RecyclerView>
</code>```

single_img.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
    android:layout_marginEnd="5dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/layout_for_imgs"
    android:id="@+id/customImg"
    app:layout_constraintDimensionRatio="1"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:src="@drawable/ic_baseline_add_home_24">
</ImageView>
</code>```

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
everyone. I suddenly get an Unresolved reference error displayed in my layouts in RecyclerView. I've already restarted Android Studio, rebuilt and cleaned the project. All without success.

AddNewHomeFragment.kt:

class AddNewHomeFragment : Fragment() {

listImg = ArrayList()
var rv_img:RecyclerView = view.findViewById(R.id.recyclerViewImgs)
rv_img.layoutManager = GridLayoutManager(requireContext(),3)

adapter = CustomerAdapter(requireContext(),listImg){
 var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
 startActivityForResult(intent,IMAGE_REQUEST)
}

rv_img.adapter = adapter

...
}

My CustomAdapter for RecyclerView:

class CustomerAdapter(val context: Context,
                  private val listImg:ArrayList<Int>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {

class MyCustomViewHolder(view: View):RecyclerView.ViewHolder(view) {
    //Unresolved reference: customImg
    val customImg:ImageView = view.findViewById(R.id.customImg)

}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCustomViewHolder {
    //Unresolved reference: single_img
    val inflate = LayoutInflater.from(context).inflate(R.layout.single_img,parent,false)

    return MyCustomViewHolder(inflate)
}

override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
    holder.customImg.setImageResource(listImg[position])
    holder.customImg.setOnClickListener {
        this@CustomerAdapter.onClickFunction?.invoke(listImg[position])
    }
}

override fun getItemCount(): Int {
   return listImg.size
}

}

fragment_add_new_home.xml:

 <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewImgs"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</androidx.recyclerview.widget.RecyclerView>

single_img.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<ImageView
    android:layout_marginEnd="5dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/layout_for_imgs"
    android:id="@+id/customImg"
    app:layout_constraintDimensionRatio="1"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:scaleType="centerCrop"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:src="@drawable/ic_baseline_add_home_24">
</ImageView>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
read ECONNRESET axios error in getServersideProps
I'm using getServerSideProps in my next.js project to have dynamic route. But I often receive the empty data from server! When I logged in getServersideProps I see this error:

```<code> cause: Error: read ECONNRESET
      at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
    errno: -4077,
    code: 'ECONNRESET',
    syscall: 'read'
  }
}
</code>```

This is my code:

```<code>const SingleBlog = ({ data }: { data: any }) => {
  console.log(data);
return(<>
//some thing to render here that I've commented
</>)
}

export async function getServerSideProps(context: any) {
  var id: number = context.params.id;
  console.log(context.params.id);
  var data: any = {};

  const getData = async () => {
    console.log('line 78 is',data)
    console.log('id is:',id)
    console.log('url is:',`https://api.someapidomain.com/api/v1/Blog/${id}`)
    const response: any = await axios.get(`https://api.someapidomain.com/api/v1/Blog/${id}`);
    console.log('line 79 is',data)

    data = response.data;
    console.log('line 81',data)
    return data;
  };
  try {
    data = await getData();
  } catch (er) {
    console.log(er);
  }
console.log('line 89 is',data)
  return {
    props: { data }, // will be passed to the page component as props
  };
}
export default SingleBlog;

</code>```

I can always see log line 78 and console.log(id is...) and id is correct value. But line 89 seldom is correct object (for example once in 5 times) and I often get empty object in log line 89 and I see the current error. in the log(url is...), I always see the correct url and when I request(get) to the url in another page, it works perfect.

Of course I used getServerSideProps in the page not component.

Body:
I'm using getServerSideProps in my next.js project to have dynamic route. But I often receive the empty data from server! When I logged in getServersideProps I see this error:

 cause: Error: read ECONNRESET
      at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
    errno: -4077,
    code: 'ECONNRESET',
    syscall: 'read'
  }
}

This is my code:

const SingleBlog = ({ data }: { data: any }) => {
  console.log(data);
return(<>
//some thing to render here that I've commented
</>)
}

export async function getServerSideProps(context: any) {
  var id: number = context.params.id;
  console.log(context.params.id);
  var data: any = {};

  const getData = async () => {
    console.log('line 78 is',data)
    console.log('id is:',id)
    console.log('url is:',`https://api.someapidomain.com/api/v1/Blog/${id}`)
    const response: any = await axios.get(`https://api.someapidomain.com/api/v1/Blog/${id}`);
    console.log('line 79 is',data)

    data = response.data;
    console.log('line 81',data)
    return data;
  };
  try {
    data = await getData();
  } catch (er) {
    console.log(er);
  }
console.log('line 89 is',data)
  return {
    props: { data }, // will be passed to the page component as props
  };
}
export default SingleBlog;

I can always see log line 78 and console.log(id is...) and id is correct value. But line 89 seldom is correct object (for example once in 5 times) and I often get empty object in log line 89 and I see the current error. in the log(url is...), I always see the correct url and when I request(get) to the url in another page, it works perfect.

Of course I used getServerSideProps in the page not component.


问:
How to define fault threshold using estimates of imu sensor bias faults
I have a mathematical model of aerial vehicle. I have developed a estimation strategy to estimate the biasses in IMU sensors (gyroscope and accelerometer), and finally got some estimation results. The estimated bias waveform contain lot of transients, small steady state errors and finally divergence after some time. But they clearly give indication of change of level when a substantial fault is injected. I need to do fault detection (0 or 1), then how to set threshold (this is fully new for me). Thanks any help will be highly appreciated

I do not have any prior knowledge about thresholding , how to do fault detection etc


问:
why I can't read json file in kotlin android project
```<code>    val jsonString_ = File("C:/Users/admin/Document/sample.json").readText()
    System.out.println(jsonString_)

    //or this
    val jsonString = applicationContext.assets.open("../res/sample.json")
        .bufferedReader()
        .use { it.readText() }

    System.out.println(jsonString)
</code>```

I tried both codes but I get "No such file or directory" or "java.io.FileNotFoundException" errors.I tried Intellij, it worked but it doesn't work on android

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
    android:requestLegacyExternalStorage="true"/>
</code>```

I added them to the manifest file,nothing changed.

Body:
    val jsonString_ = File("C:/Users/admin/Document/sample.json").readText()
    System.out.println(jsonString_)

    //or this
    val jsonString = applicationContext.assets.open("../res/sample.json")
        .bufferedReader()
        .use { it.readText() }

    System.out.println(jsonString)

I tried both codes but I get "No such file or directory" or "java.io.FileNotFoundException" errors.I tried Intellij, it worked but it doesn't work on android

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
    android:requestLegacyExternalStorage="true"/>

I added them to the manifest file,nothing changed.


问:
Trouble to reproduce Jetty idleTimeout Issue

runtime environment: OpenJDK version "1.8.0_322"

server: jetty-server version 9.2.2.v20140723

servlet: jetty-servlets version 9.2.2.v20140723

My goal is to try to reproduce locally the idle timeout error, full message is like:

```<code>{"error":true,"msg":"java.io.IOException: java.util.concurrent.TimeoutException: Idle timeout expired: 30000/30000 ms trace
</code>```

The error above is thrown by the rest endpoint for exporting data in different formats.

_idleTimeout is a property set on the ServerConnector.java class. The description of the _idleTimeout specifies that:

Sets the maximum Idle time for a connection, which roughly translates to the Socket.setSoTimeout(int) call, although with NIO implementations other mechanisms may be used to implement the timeout. The max idle time is applied:

When waiting for a new message to be received on a connection

When waiting for a new message to be sent on a connection

This value is interpreted as the maximum time between some progress being made on the connection. So if a single byte is read or written, then the timeout is reset.

This error happens infrequently and it is hard to reproduce.

First, I tried to create an endpoint that will sleep for more than 30 seconds like the below:

```<code>    @Path(value = "test", method = HttpMethod.GET)
    public void test(WebiContext ctxt) throws InterruptedException {
           Thread.sleep(550000);
    }
</code>```

I wasn't able to reproduce with the endpoint above, when I called the endpoint the connection remained for more than 30 s.

Then I modified the new test endpoint by copying code(skipping business logic part) from the export endpoint(the endpoint having this issue) to the test endpoint like below:

```<code>    @Path(value = "test", method = HttpMethod.GET)
    public void test(WebiContext ctxt) throws InterruptedException, IOException {
        ctxt.setHeader("Content-type", "application/json; charset=utf-8");
        ctxt.setHeader("Content-disposition", String.format("attachment; filename=test.json"));
        ctxt.flushBuffer();

        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator writer = jsonFactory.createGenerator(ctxt.getOutputStream(), JsonEncoding.UTF8);
        writer.writeStartObject();
        writer.flush();

        int i=0;
        while (i<10) {
            writer.writeRaw("{\"title\": \"example glossary\"}");
            Thread.sleep(550000);
        }

        writer.writeEndObject();
        writer.flush();
        ctxt.flushBuffer();
    }
</code>```

I will appreciate any help or guidance towards reproducing this issue.

Thanks in advance,
Rando.

P.S

I have used the python script below to reproduce the issue in production, but I failing to reproduce it locally.

```<code>import requests
import os
import time

local_filename = "LargeFile.csv"

url = "http://localhost:4010/rest/test/test"

querystring = {"format":"json"}

payload = ""
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

file_nr = 3

while 1:

    file_nr+=1

    local_filename = "LargeFile"+str(file_nr)+".csv"

    with requests.request("GET", url, data=payload, headers=headers, params=querystring, stream=True) as r:
        r.raise_for_status()

        with open(local_filename, 'wb') as f:

            size = 0
            for chunk in r.iter_content(chunk_size=None):
                r.raise_for_status()
                if chunk:
                    size+=len(chunk)
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
                    os.system('cls')
                    print("File: "+str(file_nr))
                    print(size/(1024*1024))
                else:
                    print("chunk error")
</code>```

Body:
runtime environment: OpenJDK version "1.8.0_322"

server: jetty-server version 9.2.2.v20140723

servlet: jetty-servlets version 9.2.2.v20140723

My goal is to try to reproduce locally the idle timeout error, full message is like:

{"error":true,"msg":"java.io.IOException: java.util.concurrent.TimeoutException: Idle timeout expired: 30000/30000 ms trace

The error above is thrown by the rest endpoint for exporting data in different formats.

_idleTimeout is a property set on the ServerConnector.java class. The description of the _idleTimeout specifies that:

Sets the maximum Idle time for a connection, which roughly translates to the Socket.setSoTimeout(int) call, although with NIO implementations other mechanisms may be used to implement the timeout. The max idle time is applied:

When waiting for a new message to be received on a connection

When waiting for a new message to be sent on a connection

This value is interpreted as the maximum time between some progress being made on the connection. So if a single byte is read or written, then the timeout is reset.

This error happens infrequently and it is hard to reproduce.

First, I tried to create an endpoint that will sleep for more than 30 seconds like the below:

    @Path(value = "test", method = HttpMethod.GET)
    public void test(WebiContext ctxt) throws InterruptedException {
           Thread.sleep(550000);
    }

I wasn't able to reproduce with the endpoint above, when I called the endpoint the connection remained for more than 30 s.

Then I modified the new test endpoint by copying code(skipping business logic part) from the export endpoint(the endpoint having this issue) to the test endpoint like below:

    @Path(value = "test", method = HttpMethod.GET)
    public void test(WebiContext ctxt) throws InterruptedException, IOException {
        ctxt.setHeader("Content-type", "application/json; charset=utf-8");
        ctxt.setHeader("Content-disposition", String.format("attachment; filename=test.json"));
        ctxt.flushBuffer();

        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator writer = jsonFactory.createGenerator(ctxt.getOutputStream(), JsonEncoding.UTF8);
        writer.writeStartObject();
        writer.flush();

        int i=0;
        while (i<10) {
            writer.writeRaw("{\"title\": \"example glossary\"}");
            Thread.sleep(550000);
        }

        writer.writeEndObject();
        writer.flush();
        ctxt.flushBuffer();
    }

I will appreciate any help or guidance towards reproducing this issue.

Thanks in advance,
Rando.

P.S

I have used the python script below to reproduce the issue in production, but I failing to reproduce it locally.

import requests
import os
import time

local_filename = "LargeFile.csv"

url = "http://localhost:4010/rest/test/test"

querystring = {"format":"json"}

payload = ""
headers = {
    "Accept": "application/json",
    "Content-Type": "application/json"
}

file_nr = 3

while 1:

    file_nr+=1

    local_filename = "LargeFile"+str(file_nr)+".csv"

    with requests.request("GET", url, data=payload, headers=headers, params=querystring, stream=True) as r:
        r.raise_for_status()

        with open(local_filename, 'wb') as f:

            size = 0
            for chunk in r.iter_content(chunk_size=None):
                r.raise_for_status()
                if chunk:
                    size+=len(chunk)
                    f.write(chunk)
                    f.flush()
                    os.fsync(f.fileno())
                    os.system('cls')
                    print("File: "+str(file_nr))
                    print(size/(1024*1024))
                else:
                    print("chunk error")


问:
Relative file paths not working on PHP website since hosting provider moved site from Grid server to cPanel Server
I created a PHP website that worked fine on a Grid Server with Media Temple until yesterday when they migrated the site to a newer cPanel server.  The errors say that it can't find included files.

My "includes" folder has always been in the same folder as the public html folder but not inside the public html folder (which I was taught was more secure) and that's also where it is on the new server.

The error says:
Warning: require_once(./includes/initialize.php): failed to open stream: No such file or directory in /home/e0qgg2hi4u4i/public_html/login.php on line 2

Line 2 in the login.php file reads:

require_once("../includes/initialize.php");

This should take it up one level in the file structure (out of the public_html directory) and then into the "includes" folder but it's obviously not working.

Again, this worked fine until the site was migrated to the new server.

Any help would be greatly appreciated.

I've tried putting the includes folder in a couple of different locations but none seem to be working.


问:
How can I make GCC Assert a Compile Time Error when an array of constant structs has a single uninitialized element?
I want to generate asserts at compile time, checking whether each element within a struct is initialized or not. I was wondering how I could generate a for loop of such static assert statements at compile time given that the assert is not a preprocessor command.

The issue was that uninitialized elements within such a struct of constants was causing undefined behavior in the system.

Tried modifying
GCC compiler flags -Wuninitialized or -Wmaybe-uninitialized do not detect when an element within an array of structs is not filled.

Followed the following thread Static assert in C

_Static_assert(fl_Button_List_SA[0].Button_constants_S.Button_Pressed_output != unintializedVariable.Button_constants_S.Button_Pressed_output ,"Struct is uninitialized.");

the fl_Button_List_SA is the array of structs.
the Button_constants_S is a struct containing constants only.
Button_pressed_output is an element defined as constant containing the output when the button is pressed.

unintializedVariable is a struct of the same type which was kept uninitialized.

The above assertion is currently returning the following error ' error: expression in static assertion is not constant ' but I will manage to get past this. However for more info the button struct inside the array is consisting of a struct containing two structs one containing only constants and the other containing only variables. And given that the structs themselves aren't constants this must be why this issue is coming up.

I would just like to generate code that goes through all the elements of each struct inside the array and checks that the elements are initialized.

As an example of an initialization:

//struct definition
typedef struct Button_properties_t
{
 Button_constants Button_constants_S;
 Button_variables Button_variables_S;
} Button_properties;

Button_properties Button_list[numberOfButtons] =
{
    [0].Button_constants_S.pressed_output=2u,
 [0].Button_constants_S.DTC_number=First_Button, //Enum
...
...

}
```
<p>What I am expecting is a rust like compile time error that if for example during initialization of button number [100] the programmer fails to define a DTC number for that button a compile time error is raised.</p>
<pre class="lang-c prettyprint-override"><code>[100].Button_constants_S.pressed_output = 4u,
//[100].Button_constants_S.DTC_number uninitialized
...
...
[101].Button_constants_S.pressed_output = 5u,
[101].Button_constants_S.DTC_number = Fifth_Button, //Enum
...
</code>```

Body:
I want to generate asserts at compile time, checking whether each element within a struct is initialized or not. I was wondering how I could generate a for loop of such static assert statements at compile time given that the assert is not a preprocessor command.

The issue was that uninitialized elements within such a struct of constants was causing undefined behavior in the system.

Tried modifying
GCC compiler flags -Wuninitialized or -Wmaybe-uninitialized do not detect when an element within an array of structs is not filled.

Followed the following thread Static assert in C

_Static_assert(fl_Button_List_SA[0].Button_constants_S.Button_Pressed_output != unintializedVariable.Button_constants_S.Button_Pressed_output ,"Struct is uninitialized.");

the fl_Button_List_SA is the array of structs.
the Button_constants_S is a struct containing constants only.
Button_pressed_output is an element defined as constant containing the output when the button is pressed.

unintializedVariable is a struct of the same type which was kept uninitialized.

The above assertion is currently returning the following error ' error: expression in static assertion is not constant ' but I will manage to get past this. However for more info the button struct inside the array is consisting of a struct containing two structs one containing only constants and the other containing only variables. And given that the structs themselves aren't constants this must be why this issue is coming up.

I would just like to generate code that goes through all the elements of each struct inside the array and checks that the elements are initialized.

As an example of an initialization:

//struct definition
typedef struct Button_properties_t
{
 Button_constants Button_constants_S;
 Button_variables Button_variables_S;
} Button_properties;

Button_properties Button_list[numberOfButtons] =
{
    [0].Button_constants_S.pressed_output=2u,
 [0].Button_constants_S.DTC_number=First_Button, //Enum
...
...

}

What I am expecting is a rust like compile time error that if for example during initialization of button number [100] the programmer fails to define a DTC number for that button a compile time error is raised.

[100].Button_constants_S.pressed_output = 4u,
//[100].Button_constants_S.DTC_number uninitialized
...
...
[101].Button_constants_S.pressed_output = 5u,
[101].Button_constants_S.DTC_number = Fifth_Button, //Enum
...


问:
Filter a python dataframe based on the nearest date
My dataframe index has datetime type. All date will be feature date already sorted starting nearest date from today. I need to filter the dataframe based on the nearest date.

I tried with below method but getting a KeyError: datetime.date(2023, 1, 4) error for today

```<code>fno_symbolList['expiry'] = pd.to_datetime(fno_symbolList['expiry'])
fno_symbolList = fno_symbolList.set_index(fno_symbolList['expiry'])
today = datetime.date.today()
fno_symbolList = fno_symbolList[fno_symbolList.index.get_loc(today, method='nearest')]
</code>```

Body:
My dataframe index has datetime type. All date will be feature date already sorted starting nearest date from today. I need to filter the dataframe based on the nearest date.

I tried with below method but getting a KeyError: datetime.date(2023, 1, 4) error for today

fno_symbolList['expiry'] = pd.to_datetime(fno_symbolList['expiry'])
fno_symbolList = fno_symbolList.set_index(fno_symbolList['expiry'])
today = datetime.date.today()
fno_symbolList = fno_symbolList[fno_symbolList.index.get_loc(today, method='nearest')]


问:
ERROR: CLI open cursor error: [Microsoft][SQL Server Native Client 11.0]TCP Provider: The semaphore timeout period has expired
PROC SQL; UPDATE CLEAN.Unknown_Provs AS A  SET ProviderAddress1=(SELECT COALESCEC(Prac1stAddr,Mail1stAddr) FROM HED.tblProviderNPI AS B WHERE A.UnknownFile_ProviderKey=B.NPI)  WHERE ProviderAddress1=''; quit;

HED is the libname created for the SQL server database.

How can i fix the error


问:
Ichimoku box - moving
moving box on chart (Pinescript)!!
how can moveing box on the chart?!(TNX)</p>
```<code>@version=5

indicator("box", overlay = true)

lowest9 = ta.lowest(low, 9)

highest9 = ta.highest(high, 9)

mybox9= box.new(left = bar_index[8], top = highest9 , right = bar_index[0], bottom = lowest9, border_color = color.rgb(59, 241, 99), border_width = 1, border_style = line.style_solid, bgcolor=na)

box.delete(mybox9[1])
</code>```

Title: Ichimoku box - moving

Body:
moving box on chart (Pinescript)!!
how can moveing box on the chart?!(TNX)

@version=5

indicator("box", overlay = true)

lowest9 = ta.lowest(low, 9)

highest9 = ta.highest(high, 9)

mybox9= box.new(left = bar_index[8], top = highest9 , right = bar_index[0], bottom = lowest9, border_color = color.rgb(59, 241, 99), border_width = 1, border_style = line.style_solid, bgcolor=na)

box.delete(mybox9[1])


问:
Question about copying action in a php function
I am total newbie but I am trying to modify this script:

```<code>public function fetchProducts($syncAll = true)
{

    $this->library = new B1([
        'apiKey' => $this->settings->get('api_key'),
        'privateKey' => $this->settings->get('private_key')
    ]);
    $i = 0;
    $enableQuantitySync = $this->settings->get('quantity_sync');
    $enableSyncItemName = $this->settings->get('sync_item_name');
    $enableSyncItemPrice = $this->settings->get('sync_item_price');
    $this->items->resetAllB1ReferenceId();
    $page = 0;
    $warehouseId = 7;
    $data = [];
    do {
        $i++;
        try {
            $response = $this->library->request('e-commerce/items/stock', [
                'warehouseId' => $warehouseId,
                'page' => ++$page,
                'pageSize' => 100,
                'filters' => [
                    'groupOp' => 'AND',
                    'rules' => [
                    ],
                ],
            ]);
            $data = $response->getContent();
            foreach ($data['data'] as $item) {
                if ($item['code'] != NULL) {
                    $this->items->updateProductReferenceId($item['id'], $item['code']);
                    if ($enableQuantitySync == 1) {
                        $this->items->updateProductQuantity2($item['quantity'], $item['id']);
                    }
                    if ($enableSyncItemName == 1) {
                        $this->items->updateItemName($item['name'], $item['id']);
                    }
                    if ($enableSyncItemPrice == 1) {
                        $this->items->updateItemPrice($item['priceWithoutVat'], $item['id']);
                    }
                }
            }
        } catch (B1Exception $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1DuplicateException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1DuplicateException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1ValidationException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1ResourceNotFoundException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1InternalErrorException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        }
        echo "$i;";
    } while (isset($data['pages']) && $page <= $data['pages'] && $i < self::MAX_ITERATIONS);
    echo 'OK';
}
</code>```

This script works fine, but I want to add another warehouse id = 2 in this function, so I am trying add this piece of code inside of function:

```<code>$warehouseId = 2;
$data = [];
do {
    $i++;
    try {
        $response = $this->library->request('e-commerce/items/stock', [
            'warehouseId' => $warehouseId,
            'page' => ++$page,
            'pageSize' => 100,
            'filters' => [
                'groupOp' => 'AND',
                'rules' => [
                ],
            ],
        ]);
        $data = $response->getContent();
        foreach ($data['data'] as $item) {
            if ($item['code'] != NULL) {
                $this->items->updateProductReferenceId2($item['id'], $item['code']);
                if ($enableQuantitySync == 1) {
                    $this->items->updateProductQuantity2($item['quantity'], $item['id']);
                }
                if ($enableSyncItemName == 1) {
                    $this->items->updateItemName2($item['name'], $item['id']);
                }
                if ($enableSyncItemPrice == 1) {
                    $this->items->updateItemPrice2($item['priceWithoutVat'], $item['id']);
                }
            }
        }
    }
</code>```

But I am getting errors.

Can someone help me to figure out a solution for this?

I was trying to add selected code in the function, but I am getting errors.

Body:
I am total newbie but I am trying to modify this script:

public function fetchProducts($syncAll = true)
{

    $this->library = new B1([
        'apiKey' => $this->settings->get('api_key'),
        'privateKey' => $this->settings->get('private_key')
    ]);
    $i = 0;
    $enableQuantitySync = $this->settings->get('quantity_sync');
    $enableSyncItemName = $this->settings->get('sync_item_name');
    $enableSyncItemPrice = $this->settings->get('sync_item_price');
    $this->items->resetAllB1ReferenceId();
    $page = 0;
    $warehouseId = 7;
    $data = [];
    do {
        $i++;
        try {
            $response = $this->library->request('e-commerce/items/stock', [
                'warehouseId' => $warehouseId,
                'page' => ++$page,
                'pageSize' => 100,
                'filters' => [
                    'groupOp' => 'AND',
                    'rules' => [
                    ],
                ],
            ]);
            $data = $response->getContent();
            foreach ($data['data'] as $item) {
                if ($item['code'] != NULL) {
                    $this->items->updateProductReferenceId($item['id'], $item['code']);
                    if ($enableQuantitySync == 1) {
                        $this->items->updateProductQuantity2($item['quantity'], $item['id']);
                    }
                    if ($enableSyncItemName == 1) {
                        $this->items->updateItemName($item['name'], $item['id']);
                    }
                    if ($enableSyncItemPrice == 1) {
                        $this->items->updateItemPrice($item['priceWithoutVat'], $item['id']);
                    }
                }
            }
        } catch (B1Exception $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1DuplicateException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1DuplicateException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1ValidationException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1ResourceNotFoundException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        } catch (B1InternalErrorException $e) {
            $content = $e->getResponse()->getContent();
            $this->helper->printPre($content['message']);
        }
        echo "$i;";
    } while (isset($data['pages']) && $page <= $data['pages'] && $i < self::MAX_ITERATIONS);
    echo 'OK';
}

This script works fine, but I want to add another warehouse id = 2 in this function, so I am trying add this piece of code inside of function:

$warehouseId = 2;
$data = [];
do {
    $i++;
    try {
        $response = $this->library->request('e-commerce/items/stock', [
            'warehouseId' => $warehouseId,
            'page' => ++$page,
            'pageSize' => 100,
            'filters' => [
                'groupOp' => 'AND',
                'rules' => [
                ],
            ],
        ]);
        $data = $response->getContent();
        foreach ($data['data'] as $item) {
            if ($item['code'] != NULL) {
                $this->items->updateProductReferenceId2($item['id'], $item['code']);
                if ($enableQuantitySync == 1) {
                    $this->items->updateProductQuantity2($item['quantity'], $item['id']);
                }
                if ($enableSyncItemName == 1) {
                    $this->items->updateItemName2($item['name'], $item['id']);
                }
                if ($enableSyncItemPrice == 1) {
                    $this->items->updateItemPrice2($item['priceWithoutVat'], $item['id']);
                }
            }
        }
    }

But I am getting errors.

Can someone help me to figure out a solution for this?

I was trying to add selected code in the function, but I am getting errors.


问:
Deployment ID in URL changes when app script runs causing the script to fail, how can I make the URL use the correct Deployment ID?
I'm using a script to create an annual leave request workflow that begins with a google form, collects responses in a sheet, then emails a manager for approval, then emails the requester with either an Approved/Denied confirmation email. The script runs and sends the email to the manager, but once either the approve or deny button is pressed, the URL generated uses a deployment ID that does not match the version of either the current /exec
or the /dev version.

Here is the code snippet for the section that should run when the buttons are used:

```<code>function SheetHandler(sheet) {
  var _sheet = sheet;
  var _data = getRowsData(_sheet);

  var _markPending = function(d) {

    d.state = PENDING_STATE;
    d.identifier = Utils.generateUUID();

    manager_email = d[SETTINGS.MANAGERS_EMAIL_COLUMN_NAME].match(EMAIL_REGEX);

    var scriptUri = ScriptApp.getService().getUrl();
    // hack some values on to the data just for email templates.
    d.approval_url = scriptUri + "?i=" + d.identifier + '&state=' + APPROVED_STATE;
    d.deny_url = scriptUri + "?i=" + d.identifier + '&state=' + DENIED_STATE;
    d.manager_email = manager_email

    message = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL, d);
    subject = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL_SUBJECT, d);

    MailApp.sendEmail(manager_email,subject,"",{ htmlBody: message });

    setRowData(_sheet, d);
  }
</code>```

Is there another way to get the correct deployment url for this?

I've tested it by copying the Head and Version deployment ID into the URL generated by the approve/deny buttons in the emails, if I copy the correct ID from the Deploy menu into the URL in place of the incorrect one then the remaining code executes as expected.

The link looks like this:
https://script.google.com/a/macros//s//exec?i=6b843ea2-7b2b-454a-ff2e-89bc9a54d48e&state=APPROVED

Body:
I'm using a script to create an annual leave request workflow that begins with a google form, collects responses in a sheet, then emails a manager for approval, then emails the requester with either an Approved/Denied confirmation email. The script runs and sends the email to the manager, but once either the approve or deny button is pressed, the URL generated uses a deployment ID that does not match the version of either the current /exec
or the /dev version.

Here is the code snippet for the section that should run when the buttons are used:

function SheetHandler(sheet) {
  var _sheet = sheet;
  var _data = getRowsData(_sheet);

  var _markPending = function(d) {

    d.state = PENDING_STATE;
    d.identifier = Utils.generateUUID();

    manager_email = d[SETTINGS.MANAGERS_EMAIL_COLUMN_NAME].match(EMAIL_REGEX);

    var scriptUri = ScriptApp.getService().getUrl();
    // hack some values on to the data just for email templates.
    d.approval_url = scriptUri + "?i=" + d.identifier + '&state=' + APPROVED_STATE;
    d.deny_url = scriptUri + "?i=" + d.identifier + '&state=' + DENIED_STATE;
    d.manager_email = manager_email

    message = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL, d);
    subject = Utils.processTemplate(SETTINGS.PENDING_MANAGER_EMAIL_SUBJECT, d);

    MailApp.sendEmail(manager_email,subject,"",{ htmlBody: message });

    setRowData(_sheet, d);
  }

Is there another way to get the correct deployment url for this?

I've tested it by copying the Head and Version deployment ID into the URL generated by the approve/deny buttons in the emails, if I copy the correct ID from the Deploy menu into the URL in place of the incorrect one then the remaining code executes as expected.

The link looks like this:
https://script.google.com/a/macros//s//exec?i=6b843ea2-7b2b-454a-ff2e-89bc9a54d48e&state=APPROVED


问:
Aeropspike Kafka Outbound Connector - using map data type with Kafka Avro format
Am trying to setup Aerospike Kafka Outbound Connector (Source Connector) for Change Data Capture (CDC). When using Kafka Avro format for messages (as explained in https://docs.aerospike.com/connect/kafka/from-asdb/formats/kafka-avro-serialization-format), am getting following error from the connector:

```<code>aerospike-kafka_connector-1  | 2022-12-22 20:27:17.607 GMT INFO  metrics-ticker - requests-total: rate(per second) mean=8.05313731102431, m1=9.48698171570335, m5=2.480116641993411, m15=0.8667674157832074
aerospike-kafka_connector-1  | 2022-12-22 20:27:17.613 GMT INFO  metrics-ticker - requests-total: duration(ms) min=1.441459, max=3101.488585, mean=15.582822432504553, stddev=149.48409869767494, median=4.713083, p75=7.851875, p95=17.496458, p98=28.421125, p99=85.418959, p999=3090.952252
aerospike-kafka_connector-1  | 2022-12-22 20:27:17.624 GMT ERROR metrics-ticker - **java.lang.Exception - Map type not allowed, has to be record type**: count=184
</code>```

My data contains a map field. The Avro schema for the data is as follows:

```<code>{
  "name": "mydata",
  "type": "record",
  "fields": [
    {
      "name": "metadata",
      "type": {
        "name": "com.aerospike.metadata",
        "type": "record",
        "fields": [
          {
            "name": "namespace",
            "type": "string"
          },
          {
            "name": "set",
            "type": [
              "null",
              "string"
            ],
            "default": null
          },
          {
            "name": "userKey",
            "type": [
              "null",
              "long",
              "double",
              "bytes",
              "string"
            ],
            "default": null
          },
          {
            "name": "digest",
            "type": "bytes"
          },
          {
            "name": "msg",
            "type": "string"
          },
          {
            "name": "durable",
            "type": [
              "null",
              "boolean"
            ],
            "default": null
          },
          {
            "name": "gen",
            "type": [
              "null",
              "int"
            ],
            "default": null
          },
          {
            "name": "exp",
            "type": [
              "null",
              "int"
            ],
            "default": null
          },
          {
            "name": "lut",
            "type": [
              "null",
              "long"
            ],
            "default": null
          }
        ]
      }
    },
    {
      "name": "test",
      "type": "string"
    },
    {
      "name": "testmap",
      "type": {
        "type": "map",
        "values": "string",
        "default": {}
      }
    }
  ]
}
</code>```

Has anyone tried and got this working?

Edit:

Looks like Aerospike connector doesn't support map type. I enabled verbose logging:

```<code>aerospike-kafka_connector-1  | 2023-01-06 18:41:31.098 GMT ERROR ErrorRegistry - Error stack trace
aerospike-kafka_connector-1  | java.lang.Exception: Map type not allowed, has to be record type
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertOnlyValidTypes(KafkaAvroOutboundRecordGenerator.kt:155)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertOnlyValidTypes(KafkaAvroOutboundRecordGenerator.kt:164)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertSchemaValid(KafkaAvroOutboundRecordGenerator.kt:101)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator.<init>(KafkaAvroOutboundRecordGenerator.kt:180)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule.getKafkaAvroStreamingRecordParser(KafkaOutboundGuiceModule.kt:59)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule.access$getKafkaAvroStreamingRecordParser(KafkaOutboundGuiceModule.kt:29)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule$bindKafkaAvroParserFactory$1.get(KafkaOutboundGuiceModule.kt:48)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.getInbuiltRecordFormatter(XdrExchangeConverter.kt:422)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.access$getInbuiltRecordFormatter(XdrExchangeConverter.kt:75)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter$RouterAndInbuiltFormatter.<init>(XdrExchangeConverter.kt:285)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.processXdrRecord(XdrExchangeConverter.kt:192)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.parse(XdrExchangeConverter.kt:134)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.OutboundBridge$processAsync$1.invokeSuspend(OutboundBridge.kt:182)
aerospike-kafka_connector-1  |  at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
aerospike-kafka_connector-1  |  at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
aerospike-kafka_connector-1  |  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
aerospike-kafka_connector-1  |  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
aerospike-kafka_connector-1  |  at java.base/java.lang.Thread.run(Thread.java:829)
</code>```

However its not mentioned in the documentation.

Body:
Am trying to setup Aerospike Kafka Outbound Connector (Source Connector) for Change Data Capture (CDC). When using Kafka Avro format for messages (as explained in https://docs.aerospike.com/connect/kafka/from-asdb/formats/kafka-avro-serialization-format), am getting following error from the connector:

aerospike-kafka_connector-1  | 2022-12-22 20:27:17.607 GMT INFO  metrics-ticker - requests-total: rate(per second) mean=8.05313731102431, m1=9.48698171570335, m5=2.480116641993411, m15=0.8667674157832074
aerospike-kafka_connector-1  | 2022-12-22 20:27:17.613 GMT INFO  metrics-ticker - requests-total: duration(ms) min=1.441459, max=3101.488585, mean=15.582822432504553, stddev=149.48409869767494, median=4.713083, p75=7.851875, p95=17.496458, p98=28.421125, p99=85.418959, p999=3090.952252
aerospike-kafka_connector-1  | 2022-12-22 20:27:17.624 GMT ERROR metrics-ticker - **java.lang.Exception - Map type not allowed, has to be record type**: count=184

My data contains a map field. The Avro schema for the data is as follows:

{
  "name": "mydata",
  "type": "record",
  "fields": [
    {
      "name": "metadata",
      "type": {
        "name": "com.aerospike.metadata",
        "type": "record",
        "fields": [
          {
            "name": "namespace",
            "type": "string"
          },
          {
            "name": "set",
            "type": [
              "null",
              "string"
            ],
            "default": null
          },
          {
            "name": "userKey",
            "type": [
              "null",
              "long",
              "double",
              "bytes",
              "string"
            ],
            "default": null
          },
          {
            "name": "digest",
            "type": "bytes"
          },
          {
            "name": "msg",
            "type": "string"
          },
          {
            "name": "durable",
            "type": [
              "null",
              "boolean"
            ],
            "default": null
          },
          {
            "name": "gen",
            "type": [
              "null",
              "int"
            ],
            "default": null
          },
          {
            "name": "exp",
            "type": [
              "null",
              "int"
            ],
            "default": null
          },
          {
            "name": "lut",
            "type": [
              "null",
              "long"
            ],
            "default": null
          }
        ]
      }
    },
    {
      "name": "test",
      "type": "string"
    },
    {
      "name": "testmap",
      "type": {
        "type": "map",
        "values": "string",
        "default": {}
      }
    }
  ]
}

Has anyone tried and got this working?

Edit:

Looks like Aerospike connector doesn't support map type. I enabled verbose logging:

aerospike-kafka_connector-1  | 2023-01-06 18:41:31.098 GMT ERROR ErrorRegistry - Error stack trace
aerospike-kafka_connector-1  | java.lang.Exception: Map type not allowed, has to be record type
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertOnlyValidTypes(KafkaAvroOutboundRecordGenerator.kt:155)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertOnlyValidTypes(KafkaAvroOutboundRecordGenerator.kt:164)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator$Companion.assertSchemaValid(KafkaAvroOutboundRecordGenerator.kt:101)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.parser.KafkaAvroOutboundRecordGenerator.<init>(KafkaAvroOutboundRecordGenerator.kt:180)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule.getKafkaAvroStreamingRecordParser(KafkaOutboundGuiceModule.kt:59)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule.access$getKafkaAvroStreamingRecordParser(KafkaOutboundGuiceModule.kt:29)
aerospike-kafka_connector-1  |  at com.aerospike.connect.kafka.outbound.inject.KafkaOutboundGuiceModule$bindKafkaAvroParserFactory$1.get(KafkaOutboundGuiceModule.kt:48)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.getInbuiltRecordFormatter(XdrExchangeConverter.kt:422)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.access$getInbuiltRecordFormatter(XdrExchangeConverter.kt:75)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter$RouterAndInbuiltFormatter.<init>(XdrExchangeConverter.kt:285)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.processXdrRecord(XdrExchangeConverter.kt:192)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.converter.XdrExchangeConverter.parse(XdrExchangeConverter.kt:134)
aerospike-kafka_connector-1  |  at com.aerospike.connect.outbound.OutboundBridge$processAsync$1.invokeSuspend(OutboundBridge.kt:182)
aerospike-kafka_connector-1  |  at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
aerospike-kafka_connector-1  |  at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
aerospike-kafka_connector-1  |  at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
aerospike-kafka_connector-1  |  at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
aerospike-kafka_connector-1  |  at java.base/java.lang.Thread.run(Thread.java:829)

However its not mentioned in the documentation.


问:
Creating a jump delay if you fall too far
I am trying to add a delay before the player can jump again if they fall from a height greater than for example 5.0f. Currently, there's no delay no matter what, which should not be the case.

```<code>// Player jumping
        if (Input.GetButtonDown("Jump") && isGrounded && Time.time > canJump)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
            if (!Physics.Raycast(transform.position, Vector3.down, out var hit)) return;

            if (hit.distance > 5.0f)
            {
                canJump = Time.time + 1.0f; // Delay next jump
            }
        }
</code>```

I have an empty game object called 'groundCheck' that sits directly below my player with a layer mask attached called 'Ground' which I use for my regular jumping and movement and all my terrain/objects have the 'Ground' layer. I tried to create an if statement so that if my player fell from at least 5.0f, they would have a very brief jump delay, but that didn't work and I'm now having issues with my raycast.

Body:
I am trying to add a delay before the player can jump again if they fall from a height greater than for example 5.0f. Currently, there's no delay no matter what, which should not be the case.

// Player jumping
        if (Input.GetButtonDown("Jump") && isGrounded && Time.time > canJump)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
            if (!Physics.Raycast(transform.position, Vector3.down, out var hit)) return;

            if (hit.distance > 5.0f)
            {
                canJump = Time.time + 1.0f; // Delay next jump
            }
        }

I have an empty game object called 'groundCheck' that sits directly below my player with a layer mask attached called 'Ground' which I use for my regular jumping and movement and all my terrain/objects have the 'Ground' layer. I tried to create an if statement so that if my player fell from at least 5.0f, they would have a very brief jump delay, but that didn't work and I'm now having issues with my raycast.


问:
Google authentication no longer working using Desktop app credentials (Google OAuth:2.0 Error 400: invalid_request)
Previously, this bit of python code worked:

```<code>
from google.cloud import bigquery
from google_auth_oauthlib import flow

appflow = flow.InstalledAppFlow.from_client_secrets_file(
            "credentials.json", scopes=["https://www.googleapis.com/auth/bigquery"])

appflow.run_console()

</code>```

However, I now get an Error 400: invalid_request message when it directs me to new browser. The details of the error are:

```<code>Error 400: invalid_request
The out-of-band (OOB) flow has been blocked in order to keep users secure. Follow the Out-of-Band (OOB) flow migration guide linked in the developer docs below to migrate your app to an alternative method.
Request details: redirect_uri=urn:ietf:wg:oauth:2.0:oob
</code>```

I know that Google has updated some of its policies in this space in recent months, but I've tried a lot of different things and it won't work (most that result in a uri_mismatch error).

As the credentials are for a Desktop App, I can't add specific URIs in the console like I would for others e.g. Web app. However, I can see in the JSON the redirect uri is set to "http://localhost"

I've tried manually updating the redirect uri (e.g. by adding '8080') in the json file, as outlined at the very bottom of this page. See also this and this article from Google but am getting the same invalid_request error.

This stack overflow answer gives a hacky suggestion, although it didn't work for me.

How do I 'update' my auth method to get it to work now? Ideally the browser pop-up should give me an authentication code that I can manually copy back into the python notebook.

Body:
Previously, this bit of python code worked:

from google.cloud import bigquery
from google_auth_oauthlib import flow

appflow = flow.InstalledAppFlow.from_client_secrets_file(
            "credentials.json", scopes=["https://www.googleapis.com/auth/bigquery"])

appflow.run_console()

However, I now get an Error 400: invalid_request message when it directs me to new browser. The details of the error are:

Error 400: invalid_request
The out-of-band (OOB) flow has been blocked in order to keep users secure. Follow the Out-of-Band (OOB) flow migration guide linked in the developer docs below to migrate your app to an alternative method.
Request details: redirect_uri=urn:ietf:wg:oauth:2.0:oob

I know that Google has updated some of its policies in this space in recent months, but I've tried a lot of different things and it won't work (most that result in a uri_mismatch error).

As the credentials are for a Desktop App, I can't add specific URIs in the console like I would for others e.g. Web app. However, I can see in the JSON the redirect uri is set to "http://localhost"

I've tried manually updating the redirect uri (e.g. by adding '8080') in the json file, as outlined at the very bottom of this page. See also this and this article from Google but am getting the same invalid_request error.

This stack overflow answer gives a hacky suggestion, although it didn't work for me.

How do I 'update' my auth method to get it to work now? Ideally the browser pop-up should give me an authentication code that I can manually copy back into the python notebook.


问:
Use after effects to create a blinking courser typewriter effect with highlight effect at the same time
I am trying to replicate the typing animation from - https://imgur.com/a/TqOypip - in after effects.

For the text I'm using:

```<code>`var sign = "|"; // change the blinking sign to "▌"or "_"
var blinkInterval = 15; // edit the blinking interval in frames
// slider with text length
var i = effect("Text")("ADBE Slider Control-0001");
// checkbox to turn the cursor on and off
var on = effect("On/Off")("ADBE Checkbox Control-0001");

var frames = timeToFrames(time);

var check = frames / blinkInterval;

if (on == 1) {
  if (i.valueAtTime(time + thisComp.frameDuration) > i) {
    end = sign;
  } else {
    if (Math.floor(check) % 2 == 0) {
      end = sign;
    } else {
      end = " ";
    }
  }
} else {
  end = " ";
}

text.sourceText.substr(0,parseInt(i)) + end; `
</code>```

Which works but then I have to manually add the white revealing lines behind the text. The example I'm trying to emulate seems to have this connected to the typewriter function somehow. This will also be of benefit as I won't have to modify many trim paths if I change the length of the text at any time.

Any help greatly appreciated.

Thanks!

See above for the code I tried.

Body:
I am trying to replicate the typing animation from - https://imgur.com/a/TqOypip - in after effects.

For the text I'm using:

`var sign = "|"; // change the blinking sign to "▌"or "_"
var blinkInterval = 15; // edit the blinking interval in frames
// slider with text length
var i = effect("Text")("ADBE Slider Control-0001");
// checkbox to turn the cursor on and off
var on = effect("On/Off")("ADBE Checkbox Control-0001");

var frames = timeToFrames(time);

var check = frames / blinkInterval;

if (on == 1) {
  if (i.valueAtTime(time + thisComp.frameDuration) > i) {
    end = sign;
  } else {
    if (Math.floor(check) % 2 == 0) {
      end = sign;
    } else {
      end = " ";
    }
  }
} else {
  end = " ";
}

text.sourceText.substr(0,parseInt(i)) + end; `

Which works but then I have to manually add the white revealing lines behind the text. The example I'm trying to emulate seems to have this connected to the typewriter function somehow. This will also be of benefit as I won't have to modify many trim paths if I change the length of the text at any time.

Any help greatly appreciated.

Thanks!

See above for the code I tried.