问:
Another way to implement Filebase64
I'm trying to upload image using Filebase64, the configuration is working fine but I can't style the button, after searching I found that the button can't be customized and I sound configure my own uploading function, I found a code that implemented it, but I failed to implement it to my own configuration.

My configuration:

```<code>export default function NewPost() {
    const [newPost, setNewPost] = useState({
        userId: '',
        title: '',
        content: '',
        photo: '',
    });
    const [title, setTitle] = useState("");
    const [desc, setDesc] = useState("");
    const [file, setFile] = useState("");
    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');
        } catch (err) {
          console.log(err);
        }
    }
  return (
    <div  >
    <form onSubmit={handleSubmit}>
          <div >
          <div >
            <label >Post Title:</label>
            <input type="text"
            onChange={e => setNewPost({ ...newPost, title: e.target.value })} />
            </div>
            <div >
                <img src={newPost.photo} alt="" />
                <label for="file">
                    <PublishIcon />
                </label>
                <FileBase64
              type="file"
              multiple={false}
              onDone={({ base64 }) => setNewPost({ ...newPost, photo: base64 })}
              />
            </div>
            </div>
    </form>
</div>
  );
}
</code>```

What I found and I am trying to implement:

```<code>function App() {

  const [baseImage, setBaseImage] = useState("");

  const uploadImage = async (e) => {
    const file = e.target.files[0];
    const base64 = await convertBase64(file);
    setBaseImage(base64);
  };

  const convertBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };
  return (
    <div className="App">
      <input
        type="file"
        onChange={(e) => {uploadImage(e);}}
      />
      <br></br>
      <img src={baseImage} height="200px" />
    </div>
  );
}
</code>```

Any help here would be appreciated

Title: Another way to implement Filebase64

Body:
I'm trying to upload image using Filebase64, the configuration is working fine but I can't style the button, after searching I found that the button can't be customized and I sound configure my own uploading function, I found a code that implemented it, but I failed to implement it to my own configuration.

My configuration:

export default function NewPost() {
    const [newPost, setNewPost] = useState({
        userId: '',
        title: '',
        content: '',
        photo: '',
    });
    const [title, setTitle] = useState("");
    const [desc, setDesc] = useState("");
    const [file, setFile] = useState("");
    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const res = await axios.post("/posts/", newPost);
            window.location.replace("/post/" + res.data._id);
            console.log('Saved Successfully');
        } catch (err) {
          console.log(err);
        }
    }
  return (

    <form onSubmit={handleSubmit}>

            Post Title:
            <input type="text"
            onChange={e => setNewPost({ ...newPost, title: e.target.value })} />

                    <PublishIcon />

                <FileBase64
              type="file"
              multiple={false}
              onDone={({ base64 }) => setNewPost({ ...newPost, photo: base64 })}
              />

    </form>

  );
}

What I found and I am trying to implement:

function App() {

  const [baseImage, setBaseImage] = useState("");

  const uploadImage = async (e) => {
    const file = e.target.files[0];
    const base64 = await convertBase64(file);
    setBaseImage(base64);
  };

  const convertBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () => {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };
  return (

      <input
        type="file"
        onChange={(e) => {uploadImage(e);}}
      />

  );
}

Any help here would be appreciated


来源: stackexchange

问:
Function output stores in python dictionary
I am calling a function and convert the output into json. For each function output data comes under square bracket but i don't want separate square bracket. Every function output should come under single square bracket.

Tried below code for calling function:

```<code>    jsondata = {}
    df_data = input_data_merge()
    jsdf = df_data.to_json(orient="records")
    jsondata["Input"] = json.loads(jsdf)

    jsondata['Output'] = count_matrix_dct

    jsdf1 = merged_df.to_json(orient="records")
    jsondata["Mismatch"] = json.loads(jsdf1)
    df_final_str = (json.dumps(jsondata))

    return df_final_str
</code>```

Output:

```<code>{
    "Input": [
        {
         "src_table_name": "Table A",
        "src_column_name": "EMP",
        "src_business_key_name": "ID",
        "src_select_column_names": "NAME,SALARY,LASTNAME",
        "src_where_condition": "1=1",
        "src_schema_name": "testdb"
        }
    ],
    "Output": {
        "match_data": 1,
        "mismatch_data": 0,
        "missing_data": 0,
        "extra": 0
    },
    "Mismatch": []
}
</code>```

Expected output:

```<code>[{
  "OutputArray": [
    {
      "Input": {
        "src_table_name": "Table A",
        "src_column_name": "EMP",
        "src_business_key_name": "ID",
        "src_select_column_names": "NAME,SALARY,LASTNAME",
        "src_where_condition": "1=1",
        "src_schema_name": "testdb"

      },
      "Output": {
        "match_data": 1,
        "mismatch_data": 0,
        "missing_data": 0,
        "extra": 0
      },
      "Mismatch": {

      },

    }
  ]
}]
</code>```

Please suggest how can i achieve this?

ContentLicense: CC BY-SA 4.0

Body:
I am calling a function and convert the output into json. For each function output data comes under square bracket but i don't want separate square bracket. Every function output should come under single square bracket.

Tried below code for calling function:

    jsondata = {}
    df_data = input_data_merge()
    jsdf = df_data.to_json(orient="records")
    jsondata["Input"] = json.loads(jsdf)

    jsondata['Output'] = count_matrix_dct

    jsdf1 = merged_df.to_json(orient="records")
    jsondata["Mismatch"] = json.loads(jsdf1)
    df_final_str = (json.dumps(jsondata))

    return df_final_str

Output:

{
    "Input": [
        {
         "src_table_name": "Table A",
        "src_column_name": "EMP",
        "src_business_key_name": "ID",
        "src_select_column_names": "NAME,SALARY,LASTNAME",
        "src_where_condition": "1=1",
        "src_schema_name": "testdb"
        }
    ],
    "Output": {
        "match_data": 1,
        "mismatch_data": 0,
        "missing_data": 0,
        "extra": 0
    },
    "Mismatch": []
}

Expected output:

[{
  "OutputArray": [
    {
      "Input": {
        "src_table_name": "Table A",
        "src_column_name": "EMP",
        "src_business_key_name": "ID",
        "src_select_column_names": "NAME,SALARY,LASTNAME",
        "src_where_condition": "1=1",
        "src_schema_name": "testdb"

      },
      "Output": {
        "match_data": 1,
        "mismatch_data": 0,
        "missing_data": 0,
        "extra": 0
      },
      "Mismatch": {

      },

    }
  ]
}]

Please suggest how can i achieve this?


问:
docker-compose - HTTP_USER & HTTP_PASSWORD not working
I added to my docker-compose in environment:

```<code>HTTP_USER: admin
HTTP_PASSWORD: pass
</code>```

When I opened localhost, I see authentication, but bellow login and password not working.

What is wrong, what I should add?

I using nginx-reverse proxy as http server.

My complete docker-compose.yml

```<code>services:
  ubuntuvnc-withpass:
    container_name: sub.domain.com
    image: dorowu/ubuntu-desktop-lxde-vnc
    expose:
      - "5900"
    environment:
      VIRTUAL_HOST: sub.domain.com
      LETSENCRYPT_HOST:  sub.domain.com
      VNC_PASSWORD:  pass
      RESOLUTION: 800x600
      HTTP_USER: admin
      HTTP_PASSWORD: pass
    networks:
     - proxy

networks:
  proxy:
    external:
      name: nginx_default
</code>```

Body:
I added to my docker-compose in environment:

HTTP_USER: admin
HTTP_PASSWORD: pass

When I opened localhost, I see authentication, but bellow login and password not working.

What is wrong, what I should add?

I using nginx-reverse proxy as http server.

My complete docker-compose.yml

services:
  ubuntuvnc-withpass:
    container_name: sub.domain.com
    image: dorowu/ubuntu-desktop-lxde-vnc
    expose:
      - "5900"
    environment:
      VIRTUAL_HOST: sub.domain.com
      LETSENCRYPT_HOST:  sub.domain.com
      VNC_PASSWORD:  pass
      RESOLUTION: 800x600
      HTTP_USER: admin
      HTTP_PASSWORD: pass
    networks:
     - proxy

networks:
  proxy:
    external:
      name: nginx_default


问:
Npm install takes more than 2 hours when running "npm install"
configured node v16.17.0 in my machine(windows).

This is my package.json, when am try to run "npm install" it takes more than 2 hours

```<code>{
  "dependencies": {
    "shelljs":"0.8.5",
    "typo-js":"1.2.2",
    "simple-git":"3.15.0",
    "markdownlint":"0.26.2",
    "run-sequence":"2.2.1",
    "request-promise":"4.2.6",
    "single-line-log":"1.1.2",
    "ajv": "6.12.3",
    "aws-sdk": "2.1248.0",
    "require-dir":"1.2.0",
    "babel-plugin-remove-graphql-queries": "4.24.0",
    "babel-plugin-styled-components": "1.7.1",
    "cheerio": "1.0.0-rc.12",
    "core-js": "2.5.7",
    "eslint": "8.27.0",
    "eslint-plugin-react": "7.31.10",
    "loader-utils":"3.2.1",
    "gatsby": "4.24.0",
    "gatsby-cli": "4.24.0",
    "gatsby-link": "4.24.1",
    "gatsby-plugin-catch-links": "2.0.8",
    "gatsby-plugin-remove-generator": "1.2.0",
    "gatsby-plugin-client-side-redirect": "0.0.2",
    "gatsby-plugin-google-tagmanager": "2.0.7",
    "gatsby-plugin-react-helmet": "3.0.2",
    "gatsby-plugin-react-helmet-canonical-urls": "1.4.0",
    "gatsby-plugin-sharp": "4.24.0",
    "gatsby-plugin-styled-components": "3.0.2",
    "gatsby-plugin-typography": "4.24.0",
    "gatsby-remark-autolink-headers": "2.0.11",
    "gatsby-remark-copy-linked-files": "2.0.6",
    "gatsby-remark-external-links": "0.0.4",
    "gatsby-remark-image-attributes": "1.1.0",
    "gatsby-remark-prismjs": "3.0.3",
    "gatsby-remark-responsive-iframe": "2.0.6",
    "node-gyp":"9.3.0",
    "gatsby-remark-smartypants": "2.0.6",
    "gatsby-source-filesystem": "4.21.0-next.3",
    "gatsby-transformer-json": "2.1.5",
    "gatsby-transformer-remark": "5.24.0",
    "gatsby-transformer-sharp": "4.24.0",
    "gulp": "4.0.2",
    "markdown-spellcheck":"0.11.0",
    "gulp-jshint":"2.1.0",
    "gulp-htmllint":"0.0.19",
    "react-router-dom": "4.3.1",
    "react-typography": "0.16.13"
  }
}
</code>```

i checked this link to run "npm set progress=false" to speed up progress also taking same time. i specified the few of these depdencies(var shelljs = require('shelljs')) directly in my js files of my project folder which was throwing shelljs module not found so that i moved those kind of depdencies inside the packages.json(shelljs,gulp-gzip..etc).

Anyone have idea to reduce the time taken for npm install commands?

Body:
configured node v16.17.0 in my machine(windows).

This is my package.json, when am try to run "npm install" it takes more than 2 hours

{
  "dependencies": {
    "shelljs":"0.8.5",
    "typo-js":"1.2.2",
    "simple-git":"3.15.0",
    "markdownlint":"0.26.2",
    "run-sequence":"2.2.1",
    "request-promise":"4.2.6",
    "single-line-log":"1.1.2",
    "ajv": "6.12.3",
    "aws-sdk": "2.1248.0",
    "require-dir":"1.2.0",
    "babel-plugin-remove-graphql-queries": "4.24.0",
    "babel-plugin-styled-components": "1.7.1",
    "cheerio": "1.0.0-rc.12",
    "core-js": "2.5.7",
    "eslint": "8.27.0",
    "eslint-plugin-react": "7.31.10",
    "loader-utils":"3.2.1",
    "gatsby": "4.24.0",
    "gatsby-cli": "4.24.0",
    "gatsby-link": "4.24.1",
    "gatsby-plugin-catch-links": "2.0.8",
    "gatsby-plugin-remove-generator": "1.2.0",
    "gatsby-plugin-client-side-redirect": "0.0.2",
    "gatsby-plugin-google-tagmanager": "2.0.7",
    "gatsby-plugin-react-helmet": "3.0.2",
    "gatsby-plugin-react-helmet-canonical-urls": "1.4.0",
    "gatsby-plugin-sharp": "4.24.0",
    "gatsby-plugin-styled-components": "3.0.2",
    "gatsby-plugin-typography": "4.24.0",
    "gatsby-remark-autolink-headers": "2.0.11",
    "gatsby-remark-copy-linked-files": "2.0.6",
    "gatsby-remark-external-links": "0.0.4",
    "gatsby-remark-image-attributes": "1.1.0",
    "gatsby-remark-prismjs": "3.0.3",
    "gatsby-remark-responsive-iframe": "2.0.6",
    "node-gyp":"9.3.0",
    "gatsby-remark-smartypants": "2.0.6",
    "gatsby-source-filesystem": "4.21.0-next.3",
    "gatsby-transformer-json": "2.1.5",
    "gatsby-transformer-remark": "5.24.0",
    "gatsby-transformer-sharp": "4.24.0",
    "gulp": "4.0.2",
    "markdown-spellcheck":"0.11.0",
    "gulp-jshint":"2.1.0",
    "gulp-htmllint":"0.0.19",
    "react-router-dom": "4.3.1",
    "react-typography": "0.16.13"
  }
}

i checked this link to run "npm set progress=false" to speed up progress also taking same time. i specified the few of these depdencies(var shelljs = require('shelljs')) directly in my js files of my project folder which was throwing shelljs module not found so that i moved those kind of depdencies inside the packages.json(shelljs,gulp-gzip..etc).

Anyone have idea to reduce the time taken for npm install commands?


问:
Video playing slow on Rock 3a / Banana Pi 4 and Odroid
I want to play 1080p fullscreen video on another device as Raspberry Pi.
Currently i am testing Rock 3A

The video plays very laggy.

Can someone please help me on this one?

Which codec should i use? (currently libx264)

Which player should i use? (currently mplayer)

What are the player settings? (currently no extra settings)

Which OS should i use? (currently tested Ubuntu Mate and Armbian)

Regarding to this link: https://forum.armbian.com/topic/22476-video-playback/
i should patch ffmpeg. But how do i patch it.
Or should i use Kodi?


问:
sampler2DArray on IOS OpenGLES3.0
We're upgrading (!) our code on IOS from OpenGLES2.0 to OpenGLES3.0 so we can use texture arrays.

We build against OpenGLES3.0 defines and open a GL3.0 context, and I can initialise a texture array fine, but the shader code gives an error on this line when I compile it at runtime.

```<code>uniform sampler2DArray mySamplerName;
</code>```

It complains about a "syntax error" on mySamplerName as if it doesn't understand sampler2DArray as a keyword

If I use

```<code>uniform sampler3D mySamplerName;
</code>```

it compiles ok, but that's not what I want.

Yes, I know OpenGL is deprecated, but does anyone know if this should work on IOS ?

Thanks

Shaun

Title: sampler2DArray on IOS OpenGLES3.0

Body:
We're upgrading (!) our code on IOS from OpenGLES2.0 to OpenGLES3.0 so we can use texture arrays.

We build against OpenGLES3.0 defines and open a GL3.0 context, and I can initialise a texture array fine, but the shader code gives an error on this line when I compile it at runtime.

uniform sampler2DArray mySamplerName;

It complains about a "syntax error" on mySamplerName as if it doesn't understand sampler2DArray as a keyword

If I use

uniform sampler3D mySamplerName;

it compiles ok, but that's not what I want.

Yes, I know OpenGL is deprecated, but does anyone know if this should work on IOS ?

Thanks

Shaun


问:
In the model adding new Bilstm layer return error "bidirectional_1" is incompatible with the layer and the model is not working expected ndim=3,
i am trying to add new Bilstm layer to

```<code>model.add(Conv1D(500,9,strides=1,input_shape=(7680,1),activation='tanh'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(MaxPooling1D(pool_size=2,strides=2))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Bidirectional(LSTM(300),input_shape=(7680,1)))
model.add(Bidirectional(LSTM(300)))
model.add(Dense(9, activation='softmax'))
</code>```

Input 0 of layer "bidirectional_1" is incompatible with the layer:
expected ndim=3, found ndim=2. Full shape received: (None, 600)

Body:
i am trying to add new Bilstm layer to

model.add(Conv1D(500,9,strides=1,input_shape=(7680,1),activation='tanh'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(Conv1D(300, 3, activation='relu'))
model.add(MaxPooling1D(pool_size=2,strides=2))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Conv1D(200, 3, activation='relu'))
model.add(Bidirectional(LSTM(300),input_shape=(7680,1)))
model.add(Bidirectional(LSTM(300)))
model.add(Dense(9, activation='softmax'))

Input 0 of layer "bidirectional_1" is incompatible with the layer:
expected ndim=3, found ndim=2. Full shape received: (None, 600)


问:
how do I re-connect a stripe webhook local listener endpoint?
I have a stripe webhook endpoint that listens for checkout events. Stripe suggests setting up local endpoints via the Stripe CLI to test it. However, the status of my current local listener endpoint is "disconnected". Does anyone know how to make the status "active"? Thanks</p>


问:
how to correctly join multiple X-Forwarded-For headers in java
we are using a system which requires the X-Forwarded-For header from the request for security, but it can only handle a single value. The specification says that we can receive multiple X-Forwarded-For headers, and they MUST be combined in the right order (presumably first header found goes to the left of the resultant single string, and the last to the right).

Below is our guess at the right code, but this makes some big assumptions:

does the request.getHeaders() function return the headers in the right order?

does the Enumeration.getNext() return the right order?

```<code>  public String getForwardedFor(SlingHttpServletRequest request) {
      String result = null;
      Enumeration<String> forwaradedForHeaders = request.getHeaders("X-Forwarded-For");
      while (forwaradedForHeaders.hasMoreElements()) {
          String header = forwaradedForHeaders.nextElement();
          if (result == null) {
              result = header;
          } else {
              result = result + ", " + header;
          }
      }
      return result;
  }
</code>```

UPDATE

I realised I need to include the actual IP of the thing which called my middleware, and add this to the right end of the string (I think).

Now I have this:

```<code>  public String getForwardedFor(SlingHttpServletRequest request) {
      String result = "";
      Enumeration<String> forwaradedForHeaders = request.getHeaders("X-Forwarded-For");
      while (forwaradedForHeaders.hasMoreElements()) {
          String header = forwaradedForHeaders.nextElement();
          if (result.equals("")) {
              result = header;
          } else {
              result = result + ", " + header;
          }
      }

      String clientIP = request.getRemoteAddr();

      if (result.equals("")) {
          result += clientIP;
      } else {
          result += ", " + clientIP;
      }

      logger.debug("getForwardedFor:" + forwaradedForHeaders);
      return result;
  }
</code>```

However, this has a strange effect. If the request has an X-Forwarded-For header set, then request.getRemoteAddr() does NOT return the ip of the client who called the middleware, it returns the last value from X-Forwarded-For.  If the client doesnt send anything in X-Forwarded-For, then request.getRemoteAddr() returns the IP of the caller. what is going on here, and how do you get the callers IP if the X-Forwarded-For header is already set?

Body:
we are using a system which requires the X-Forwarded-For header from the request for security, but it can only handle a single value. The specification says that we can receive multiple X-Forwarded-For headers, and they MUST be combined in the right order (presumably first header found goes to the left of the resultant single string, and the last to the right).

Below is our guess at the right code, but this makes some big assumptions:

does the request.getHeaders() function return the headers in the right order?

does the Enumeration.getNext() return the right order?

  public String getForwardedFor(SlingHttpServletRequest request) {
      String result = null;
      Enumeration<String> forwaradedForHeaders = request.getHeaders("X-Forwarded-For");
      while (forwaradedForHeaders.hasMoreElements()) {
          String header = forwaradedForHeaders.nextElement();
          if (result == null) {
              result = header;
          } else {
              result = result + ", " + header;
          }
      }
      return result;
  }

UPDATE

I realised I need to include the actual IP of the thing which called my middleware, and add this to the right end of the string (I think).

Now I have this:

  public String getForwardedFor(SlingHttpServletRequest request) {
      String result = "";
      Enumeration<String> forwaradedForHeaders = request.getHeaders("X-Forwarded-For");
      while (forwaradedForHeaders.hasMoreElements()) {
          String header = forwaradedForHeaders.nextElement();
          if (result.equals("")) {
              result = header;
          } else {
              result = result + ", " + header;
          }
      }

      String clientIP = request.getRemoteAddr();

      if (result.equals("")) {
          result += clientIP;
      } else {
          result += ", " + clientIP;
      }

      logger.debug("getForwardedFor:" + forwaradedForHeaders);
      return result;
  }

However, this has a strange effect. If the request has an X-Forwarded-For header set, then request.getRemoteAddr() does NOT return the ip of the client who called the middleware, it returns the last value from X-Forwarded-For.  If the client doesnt send anything in X-Forwarded-For, then request.getRemoteAddr() returns the IP of the caller. what is going on here, and how do you get the callers IP if the X-Forwarded-For header is already set?


问:
inserting mysql date field into MySQL Database
I'm having an issue submitting a form into a database once I have added a Submitted_Date field.

The errors are as follows:

Fatal error: Uncaught mysqli_sql_exception: Incorrect date value:
'2022' for column 'Submitted_Date'

mysqli_sql_exception: Incorrect date value: '2022' for column
'Submitted_Date'

Prior to adding in $Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date'])); I was also getting an error for incorrect listed fields on the binding.

The Submitted_Date field is a date input field so needs to be handled as 'NULL' value if a date has not been entered. Instead I also get a

'Incorrect date value: '1970'

Any help would be great. Thanks.

```<code>     <?php
        if (isset($_POST['submit'])) {
            $sql = $conn->prepare("UPDATE orders SET Publisher_Email=? , Client_Name=? , Submitted_Date=? WHERE PC_Job_Number=?
            ");
            $Publisher_Email = $_POST['Publisher_Email'];
            $Client_Name = $_POST['Client_Name'];
            $Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date']));

            $sql->bind_param("ssii", $Publisher_Email, $Client_Name, $Submitted_Date, $_GET["PC_Job_Number"]);

            if (empty($Submitted_Date)) {
              $Submitted_Date = "NULL";
            }

            if($sql->execute()) {
                $success_message = "Edited Successfully";
            } else {
                $error_message = "Problem in Editing Record";
            }
        }
        $sql = $conn->prepare("SELECT * FROM orders WHERE PC_Job_Number=?");
        $sql->bind_param("i",$_GET["PC_Job_Number"]);
        $sql->execute();
        $result = $sql->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
        }
        $conn->close();
    ?>
</code>```

Body:
I'm having an issue submitting a form into a database once I have added a Submitted_Date field.

The errors are as follows:

Fatal error: Uncaught mysqli_sql_exception: Incorrect date value:
'2022' for column 'Submitted_Date'

mysqli_sql_exception: Incorrect date value: '2022' for column
'Submitted_Date'

Prior to adding in $Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date'])); I was also getting an error for incorrect listed fields on the binding.

The Submitted_Date field is a date input field so needs to be handled as 'NULL' value if a date has not been entered. Instead I also get a

'Incorrect date value: '1970'

Any help would be great. Thanks.

     <?php
        if (isset($_POST['submit'])) {
            $sql = $conn->prepare("UPDATE orders SET Publisher_Email=? , Client_Name=? , Submitted_Date=? WHERE PC_Job_Number=?
            ");
            $Publisher_Email = $_POST['Publisher_Email'];
            $Client_Name = $_POST['Client_Name'];
            $Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date']));

            $sql->bind_param("ssii", $Publisher_Email, $Client_Name, $Submitted_Date, $_GET["PC_Job_Number"]);

            if (empty($Submitted_Date)) {
              $Submitted_Date = "NULL";
            }

            if($sql->execute()) {
                $success_message = "Edited Successfully";
            } else {
                $error_message = "Problem in Editing Record";
            }
        }
        $sql = $conn->prepare("SELECT * FROM orders WHERE PC_Job_Number=?");
        $sql->bind_param("i",$_GET["PC_Job_Number"]);
        $sql->execute();
        $result = $sql->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
        }
        $conn->close();
    ?>


问:
MongoJack with Kotlin
I might be asking for trouble with this setup but I am trying to get MongoDB with MongoJack to work with Kotlin classes.
I've managed to overcome a few problems already for which I will outline my solutions if others have the same problem but I am still struggling with one issue.

Kotlin class:

```<code> data class TestDocument (
   @ObjectId @JsonProperty("_id") var id:String? = null,
   @JsonProperty("name") var name:String,
    var date: Date = Date(),
    var decimal: BigDecimal = BigDecimal.valueOf(123.456)
</code>```

)

If I use the default setup (using the ObjectMapper mongoJack configured) like this:

```<code>object  MongoClientTestDefault {
    val log: Log = Logging.getLog(MongoClientTest::class.java)
    val mongoClient : MongoClient
    val database: MongoDatabase
    val testCol: MongoCollection<TestDocument>
    init {
        val mongoUrl = "mongodb://localhost:27017/"
        log.info("Initialising MongoDB Client with $mongoUrl")
        try {
            mongoClient = MongoClients.create(mongoUrl)
            database = mongoClient.getDatabase("unitTest")
            testCol = JacksonMongoCollection.builder()
                .build(
                    mongoClient,
                    "unitTest",
                    "testCol",
                    TestDocument::class.java,
                    UuidRepresentation.STANDARD
                )
            log.info("Successfully initialised MongoDB client")
        }catch(e: Exception){
            log.error(Strings.EXCEPTION,e)
            log.error("Mongo URL: ", mongoUrl)
            throw e //we need to throw this as otherwise it complains that the val fields haven't been initialised
        }
    }
}
</code>```

Then the serialization (or persisting to Mongo) works ok but the deserialization from Mongo to the Kotlin class fails because without the Kotlin jackson module Jackson and MongoJack don't know how to handle the Kotlin constructor it seems.

To fix that you have to use the jacksonObjectMapper() and pass that to the builder:

```<code>testCol = JacksonMongoCollection.builder()
                .withObjectMapper(jacksonObjectMapper)
                .build(
                mongoClient,
                "unitTest",
                "testCol",
                TestDocument::class.java,
                UuidRepresentation.STANDARD
            )
</code>```

That will solve the deserialization but now the Dates are causing problems.
So in order to fix that I do the following

```<code>object  MongoClientTest {
    val log: Log = Logging.getLog(MongoClientTest::class.java)
    val mongoClient : MongoClient
    val database: MongoDatabase
    val testCol: MongoCollection<TestDocument>
    var jacksonObjectMapper = jacksonObjectMapper()
    init {
        val mongoUrl = "mongodb://localhost:27017/"
        MongoJackModule.configure(jacksonObjectMapper)
        log.info("Initialising MongoDB Client with $mongoUrl")
        try {
            mongoClient = MongoClients.create(mongoUrl)
            database = mongoClient.getDatabase("unitTest")
            testCol = JacksonMongoCollection.builder()
                .withObjectMapper(jacksonObjectMapper)
                .build(
                mongoClient,
                "unitTest",
                "testCol",
                TestDocument::class.java,
                UuidRepresentation.STANDARD
            )
            log.info("Successfully initialised MongoDB client")
        }catch(e: Exception){
            log.error(Strings.EXCEPTION,e)
            log.error("Mongo URL: ", mongoUrl)
            throw e //we need to throw this as otherwise it complains that the val fields haven't been initialised
        }
    }
}
</code>```

I take the jacksonObjectMapper and call MongoJackModule.configure(jacksonObjectMapper) and then pass it to the builder.

Now serialization (persiting to Mongo) and deserialization (loading from Mongo and converting to Pojo) works but there is one Exception thrown (which seems to be handled).

```<code>var testDoc = TestDocument(name="TestName")
    MongoClientTest.testCol.drop()
    var insertOneResult = MongoClientTest.testCol.insertOne(testDoc)
</code>```

This call works and it creates the document in Mongo but this exception is printed:

```<code>java.lang.UnsupportedOperationException: Cannot call setValue() on constructor parameter of com.acme.MongoJackTest$TestDocument
at com.fasterxml.jackson.databind.introspect.AnnotatedParameter.setValue(AnnotatedParameter.java:118)
at org.mongojack.internal.stream.JacksonCodec.lambda$getIdWriter$4(JacksonCodec.java:120)
at org.mongojack.internal.stream.JacksonCodec.generateIdIfAbsentFromDocument(JacksonCodec.java:77)
at com.mongodb.internal.operation.Operations.bulkWrite(Operations.java:450)
at com.mongodb.internal.operation.Operations.insertOne(Operations.java:375)
at com.mongodb.internal.operation.SyncOperations.insertOne(SyncOperations.java:177)
at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:476)
at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:459)
at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:453)
at org.mongojack.MongoCollectionDecorator.insertOne(MongoCollectionDecorator.java:528)
</code>```

It is trying to create and set the _id on the TestDocument but struggles with the primary constructor of the Kotlin class.
I've tried to add a 'default aka empty' constructor:

```<code> data class TestDocument (
       @ObjectId @JsonProperty("_id") var id:String? = null,
       @JsonProperty("name") var name:String,
        var date: Date = Date(),
        var decimal: BigDecimal = BigDecimal.valueOf(123.456)
   ){
       @JsonCreator constructor(): this(name = "")
   }
</code>```

But that doesn't fix it.

Any ideas how I could fix this?
This is the code in MongoJack that is catching the exception:

```<code> private Consumer<BsonObjectId> getIdWriter(final T t) {
    final Optional<BeanPropertyDefinition> maybeBpd = getIdElementSerializationDescription(t.getClass());
    return maybeBpd.<Consumer<BsonObjectId>>map(beanPropertyDefinition -> (bsonObjectId) -> {
        try {
            if (bsonObjectId != null) {
                beanPropertyDefinition.getMutator().setValue(
                    t,
                    extractIdValue(bsonObjectId, beanPropertyDefinition.getRawPrimaryType())
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).orElseGet(() -> (bsonObjectId) -> {
    });
}
</code>```

I guess it could just be ignored but that could flood the logs.

Title: MongoJack with Kotlin

Body:
I might be asking for trouble with this setup but I am trying to get MongoDB with MongoJack to work with Kotlin classes.
I've managed to overcome a few problems already for which I will outline my solutions if others have the same problem but I am still struggling with one issue.

Kotlin class:

 data class TestDocument (
   @ObjectId @JsonProperty("_id") var id:String? = null,
   @JsonProperty("name") var name:String,
    var date: Date = Date(),
    var decimal: BigDecimal = BigDecimal.valueOf(123.456)

)

If I use the default setup (using the ObjectMapper mongoJack configured) like this:

object  MongoClientTestDefault {
    val log: Log = Logging.getLog(MongoClientTest::class.java)
    val mongoClient : MongoClient
    val database: MongoDatabase
    val testCol: MongoCollection<TestDocument>
    init {
        val mongoUrl = "mongodb://localhost:27017/"
        log.info("Initialising MongoDB Client with $mongoUrl")
        try {
            mongoClient = MongoClients.create(mongoUrl)
            database = mongoClient.getDatabase("unitTest")
            testCol = JacksonMongoCollection.builder()
                .build(
                    mongoClient,
                    "unitTest",
                    "testCol",
                    TestDocument::class.java,
                    UuidRepresentation.STANDARD
                )
            log.info("Successfully initialised MongoDB client")
        }catch(e: Exception){
            log.error(Strings.EXCEPTION,e)
            log.error("Mongo URL: ", mongoUrl)
            throw e //we need to throw this as otherwise it complains that the val fields haven't been initialised
        }
    }
}

Then the serialization (or persisting to Mongo) works ok but the deserialization from Mongo to the Kotlin class fails because without the Kotlin jackson module Jackson and MongoJack don't know how to handle the Kotlin constructor it seems.

To fix that you have to use the jacksonObjectMapper() and pass that to the builder:

testCol = JacksonMongoCollection.builder()
                .withObjectMapper(jacksonObjectMapper)
                .build(
                mongoClient,
                "unitTest",
                "testCol",
                TestDocument::class.java,
                UuidRepresentation.STANDARD
            )

That will solve the deserialization but now the Dates are causing problems.
So in order to fix that I do the following

object  MongoClientTest {
    val log: Log = Logging.getLog(MongoClientTest::class.java)
    val mongoClient : MongoClient
    val database: MongoDatabase
    val testCol: MongoCollection<TestDocument>
    var jacksonObjectMapper = jacksonObjectMapper()
    init {
        val mongoUrl = "mongodb://localhost:27017/"
        MongoJackModule.configure(jacksonObjectMapper)
        log.info("Initialising MongoDB Client with $mongoUrl")
        try {
            mongoClient = MongoClients.create(mongoUrl)
            database = mongoClient.getDatabase("unitTest")
            testCol = JacksonMongoCollection.builder()
                .withObjectMapper(jacksonObjectMapper)
                .build(
                mongoClient,
                "unitTest",
                "testCol",
                TestDocument::class.java,
                UuidRepresentation.STANDARD
            )
            log.info("Successfully initialised MongoDB client")
        }catch(e: Exception){
            log.error(Strings.EXCEPTION,e)
            log.error("Mongo URL: ", mongoUrl)
            throw e //we need to throw this as otherwise it complains that the val fields haven't been initialised
        }
    }
}

I take the jacksonObjectMapper and call MongoJackModule.configure(jacksonObjectMapper) and then pass it to the builder.

Now serialization (persiting to Mongo) and deserialization (loading from Mongo and converting to Pojo) works but there is one Exception thrown (which seems to be handled).

var testDoc = TestDocument(name="TestName")
    MongoClientTest.testCol.drop()
    var insertOneResult = MongoClientTest.testCol.insertOne(testDoc)

This call works and it creates the document in Mongo but this exception is printed:

java.lang.UnsupportedOperationException: Cannot call setValue() on constructor parameter of com.acme.MongoJackTest$TestDocument
at com.fasterxml.jackson.databind.introspect.AnnotatedParameter.setValue(AnnotatedParameter.java:118)
at org.mongojack.internal.stream.JacksonCodec.lambda$getIdWriter$4(JacksonCodec.java:120)
at org.mongojack.internal.stream.JacksonCodec.generateIdIfAbsentFromDocument(JacksonCodec.java:77)
at com.mongodb.internal.operation.Operations.bulkWrite(Operations.java:450)
at com.mongodb.internal.operation.Operations.insertOne(Operations.java:375)
at com.mongodb.internal.operation.SyncOperations.insertOne(SyncOperations.java:177)
at com.mongodb.client.internal.MongoCollectionImpl.executeInsertOne(MongoCollectionImpl.java:476)
at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:459)
at com.mongodb.client.internal.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:453)
at org.mongojack.MongoCollectionDecorator.insertOne(MongoCollectionDecorator.java:528)

It is trying to create and set the _id on the TestDocument but struggles with the primary constructor of the Kotlin class.
I've tried to add a 'default aka empty' constructor:

 data class TestDocument (
       @ObjectId @JsonProperty("_id") var id:String? = null,
       @JsonProperty("name") var name:String,
        var date: Date = Date(),
        var decimal: BigDecimal = BigDecimal.valueOf(123.456)
   ){
       @JsonCreator constructor(): this(name = "")
   }

But that doesn't fix it.

Any ideas how I could fix this?
This is the code in MongoJack that is catching the exception:

 private Consumer<BsonObjectId> getIdWriter(final T t) {
    final Optional<BeanPropertyDefinition> maybeBpd = getIdElementSerializationDescription(t.getClass());
    return maybeBpd.<Consumer<BsonObjectId>>map(beanPropertyDefinition -> (bsonObjectId) -> {
        try {
            if (bsonObjectId != null) {
                beanPropertyDefinition.getMutator().setValue(
                    t,
                    extractIdValue(bsonObjectId, beanPropertyDefinition.getRawPrimaryType())
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }).orElseGet(() -> (bsonObjectId) -> {
    });
}

I guess it could just be ignored but that could flood the logs.


问:
GAS GNU Assembly. Segmentation Fault calling printf. Jonathan-Bartlett book listing p98 (without comments): printf-example.s
```<code>This is the code (rid of most comments '#' for readability. "..._nude.s" in example namefile refers to this):
  1 #PURPOSE: This program is to demonstrate how to call printf
  2
  3  .section .data
  4
  5 firststring:
  6  .ascii "Hello! % is a %s who loves the number %d\n\0"
  7 name:
  8  .ascii "Jonathan\0"
  9 personstring:
 10  .ascii "person\0"
 11 numberloved:
 12  .long 3
 13
 14  .section .text
 15  .globl _start
 16 _start:
 17  pushl  numberloved     #This is the %d
 18  pushl  $personstring   #This is the second %s
 19  pushl  $name           #This is the first %s
 20  pushl  $firststring    #This is the format string in the prototype
 21  call   printf
 22
 23  pushl  $0
 24  call   exit
</code>```

$ as printf-example_nude.s -o printf-example_nude.o

$ ld printf-example_nude.o -o printf-example_nude -lc -dynamic-linker /lib/ld-linux.so.2

$ ./printf-example_nude

zsh: segmentation fault (core dumped)  ./printf-example_nude

(As we can see and i followed the assembly/linking instructions from the book:

Assembly went well.

Linking went well.

Execution failed. Machine: Linux (Debian) 32-bit.)

Any idea?
Thank you.

Body:
This is the code (rid of most comments '#' for readability. "..._nude.s" in example namefile refers to this):
  1 #PURPOSE: This program is to demonstrate how to call printf
  2
  3  .section .data
  4
  5 firststring:
  6  .ascii "Hello! % is a %s who loves the number %d\n\0"
  7 name:
  8  .ascii "Jonathan\0"
  9 personstring:
 10  .ascii "person\0"
 11 numberloved:
 12  .long 3
 13
 14  .section .text
 15  .globl _start
 16 _start:
 17  pushl  numberloved     #This is the %d
 18  pushl  $personstring   #This is the second %s
 19  pushl  $name           #This is the first %s
 20  pushl  $firststring    #This is the format string in the prototype
 21  call   printf
 22
 23  pushl  $0
 24  call   exit

$ as printf-example_nude.s -o printf-example_nude.o

$ ld printf-example_nude.o -o printf-example_nude -lc -dynamic-linker /lib/ld-linux.so.2

$ ./printf-example_nude

zsh: segmentation fault (core dumped)  ./printf-example_nude

(As we can see and i followed the assembly/linking instructions from the book:

Assembly went well.

Linking went well.

Execution failed. Machine: Linux (Debian) 32-bit.)

Any idea?
Thank you.


问:
How call C function in js with render SDL in canvas
I am trying to render in canvas the module that I built with SDL2, but I also need to call functions while the module is running and send data there, according to the examples I found it turns out so:

   var Module = {
         canvas: (function () {
             var canvas = document.getElementById('canvas');
             canvas.addEventListener('webglcontextlost', e => {
                 alert('WebGL context lost. You will need to reload the page.');
                 e.preventDefault();
             }, false);
             return canvas;
         })(),

     };

     SSE.onmessage = msg => {
         Module.onRuntimeInitialized = () => {
             Module.ccall('set_num', null, ['number'], [msg]);
        };
     }
```
<p>The function was called once, but I need to call it constantly in the event</p>
<p>make with</p>
```override CFLAGS += -std=c11\
                -Os\
                -sUSE_SDL_TTF=2\
                -sUSE_SDL_IMAGE=2\
                -sSDL2_IMAGE_FORMATS=["png"]\
                -sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']\
                -sUSE_SDL=2\
                -sWASM=1\
                -sASSERTIONS\
                --preload-file ./res

```
<p>C</p>
<pre class="lang-c prettyprint-override"><code>#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void set_num(int num) { g_obj->num = num; }
</code>```

Body:
I am trying to render in canvas the module that I built with SDL2, but I also need to call functions while the module is running and send data there, according to the examples I found it turns out so:

   var Module = {
         canvas: (function () {
             var canvas = document.getElementById('canvas');
             canvas.addEventListener('webglcontextlost', e => {
                 alert('WebGL context lost. You will need to reload the page.');
                 e.preventDefault();
             }, false);
             return canvas;
         })(),

     };

     SSE.onmessage = msg => {
         Module.onRuntimeInitialized = () => {
             Module.ccall('set_num', null, ['number'], [msg]);
        };
     }

The function was called once, but I need to call it constantly in the event

make with

override CFLAGS += -std=c11\
                -Os\
                -sUSE_SDL_TTF=2\
                -sUSE_SDL_IMAGE=2\
                -sSDL2_IMAGE_FORMATS=["png"]\
                -sEXPORTED_RUNTIME_METHODS=['ccall','cwrap']\
                -sUSE_SDL=2\
                -sWASM=1\
                -sASSERTIONS\
                --preload-file ./res

C

#ifdef __EMSCRIPTEN__
EMSCRIPTEN_KEEPALIVE
#endif
void set_num(int num) { g_obj->num = num; }


问:
Yii2 pagination without pager
I'm trying to make a selection of records from the database by a certain number, for example, the first 5, when passing through the page number, get the other 5.
For example my current request:

```<code>/api/get-doctors?id=null&search=null&specification=null&price_min=null&price_max=null&experience_min=null&experience_max=null&location=null&clinic=null&filter=null&top=null&lang=en
</code>```

I want to add a new parameter page=1

I usually get entries through the find

```<code>$all_doctors = Doctors::find()->localized($lang)->where(['status' => 1])->all();
</code>```

The standard solution through the pager does not suit me because I do not use the url.How can i bypass implementation via pager?

Title: Yii2 pagination without pager

Body:
I'm trying to make a selection of records from the database by a certain number, for example, the first 5, when passing through the page number, get the other 5.
For example my current request:

/api/get-doctors?id=null&search=null&specification=null&price_min=null&price_max=null&experience_min=null&experience_max=null&location=null&clinic=null&filter=null&top=null&lang=en

I want to add a new parameter page=1

I usually get entries through the find

$all_doctors = Doctors::find()->localized($lang)->where(['status' => 1])->all();

The standard solution through the pager does not suit me because I do not use the url.How can i bypass implementation via pager?


问:
Cross referencing algorithms
Scenario

Note: I am using the Java language for this effort.

Consider the following scenario. In a directory hierarchy, there are files that contain "template definitions". These definitions are then "included" by other files containing embedded templating logic. Here are some examples for reference.

A template definition:

_helpers.tpl:

```<code>...
{{- define "keycloak.selectorLabels" -}}
app.kubernetes.io/name: {{ include "keycloak.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
...
</code>```

The details of the defintion are not important. I only care about the existence of the definition, i.e. it's name ("keycloak.selectorLabels") and where it's found (line N of _helpers.tpl).

(Note that the definition includes another defintion.)

A templated file that includes the definition:

service-http.yaml:

```<code>  ...
  selector:
    {{- include "keycloak.selectorLabels" . | nindent 4 }}
  ...
</code>```

Definitions can be included by other definitions, in the same or other template files.

My objective

I want to scan these files to find 1) the definitions and 2) where they are included. I have working logic that collects this information now.

It would then output listings of the following information:

```<code>for each:
    definition (the containing file and definition "metadata" - name and line found):
        list of templated files that include the defintion (file and line(s) where included)
        -or- indication that NO references were found for this definition

for each:
    templated file:
        list of definition inclusions (definition "metadata" and line(s) where included)
</code>```

What I need help with

I'm trying to find or figure out an algorithm to do this "cross referencing" described above. I'm sure that with some trial and error I could come up with something that works (no saying how long it'll take or how well it would work), but am wondering if anyone has ideas or information about existing algorithms that do this kind of thing.

I tried to see if I could Google something, but not really sure what search terms to use. The things I did try didn't help.

Title: Cross referencing algorithms

Body:
Scenario

Note: I am using the Java language for this effort.

Consider the following scenario. In a directory hierarchy, there are files that contain "template definitions". These definitions are then "included" by other files containing embedded templating logic. Here are some examples for reference.

A template definition:

_helpers.tpl:

...
{{- define "keycloak.selectorLabels" -}}
app.kubernetes.io/name: {{ include "keycloak.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
...

The details of the defintion are not important. I only care about the existence of the definition, i.e. it's name ("keycloak.selectorLabels") and where it's found (line N of _helpers.tpl).

(Note that the definition includes another defintion.)

A templated file that includes the definition:

service-http.yaml:

  ...
  selector:
    {{- include "keycloak.selectorLabels" . | nindent 4 }}
  ...

Definitions can be included by other definitions, in the same or other template files.

My objective

I want to scan these files to find 1) the definitions and 2) where they are included. I have working logic that collects this information now.

It would then output listings of the following information:

for each:
    definition (the containing file and definition "metadata" - name and line found):
        list of templated files that include the defintion (file and line(s) where included)
        -or- indication that NO references were found for this definition

for each:
    templated file:
        list of definition inclusions (definition "metadata" and line(s) where included)

What I need help with

I'm trying to find or figure out an algorithm to do this "cross referencing" described above. I'm sure that with some trial and error I could come up with something that works (no saying how long it'll take or how well it would work), but am wondering if anyone has ideas or information about existing algorithms that do this kind of thing.

I tried to see if I could Google something, but not really sure what search terms to use. The things I did try didn't help.


问:
FDCAN in production mode cannot send messages
I am using a STM32MP157C-DK2 board to communicate via CAN. To do this, I have created a program in STM32CubeIDE and set the FDCAN parameters:

FDCAN configuration

I have been testing in engineering mode and I was able to receive and send CAN messages (I have connected to an IXXAT device) using the following function in the main function:

```<code>/* USER CODE BEGIN 3 */
if(HAL_FDCAN_GetRxFifoFillLevel(&hfdcan1, FDCAN_RX_FIFO0) > 0)
{
    HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_3);
    // Recoger mensaje de la cola
    if(HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_FIFO0, &RxHeader, RxData) != HAL_OK)
    {
        Error_Handler();
    }
    if(HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TxHeader, TxData))
    {
        Error_Handler();
    } */
}
</code>```

Then the tests have been carried out in production mode. In this case, first the A7 processor is initialized and then the M4 processor program is started with the following commands (Core_Communication is the name of the program):

```<code>echo Core_Communication_CM4.elf > /sys/class/remoteproc/remoteproc0/firmware
echo start > /sys/class/remoteproc/remoteproc0/state
</code>```

In this case, I try to send CAN messages through IXXAT but I get the following error:

```<code>ACK error
</code>```

Is there a parameter that I have to configure?

Body:
I am using a STM32MP157C-DK2 board to communicate via CAN. To do this, I have created a program in STM32CubeIDE and set the FDCAN parameters:

FDCAN configuration

I have been testing in engineering mode and I was able to receive and send CAN messages (I have connected to an IXXAT device) using the following function in the main function:

/* USER CODE BEGIN 3 */
if(HAL_FDCAN_GetRxFifoFillLevel(&hfdcan1, FDCAN_RX_FIFO0) > 0)
{
    HAL_GPIO_TogglePin(GPIOF, GPIO_PIN_3);
    // Recoger mensaje de la cola
    if(HAL_FDCAN_GetRxMessage(&hfdcan1, FDCAN_RX_FIFO0, &RxHeader, RxData) != HAL_OK)
    {
        Error_Handler();
    }
    if(HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TxHeader, TxData))
    {
        Error_Handler();
    } */
}

Then the tests have been carried out in production mode. In this case, first the A7 processor is initialized and then the M4 processor program is started with the following commands (Core_Communication is the name of the program):

echo Core_Communication_CM4.elf > /sys/class/remoteproc/remoteproc0/firmware
echo start > /sys/class/remoteproc/remoteproc0/state

In this case, I try to send CAN messages through IXXAT but I get the following error:

ACK error

Is there a parameter that I have to configure?


问:
How to use Google Session Token in Spark to connect to Google Cloud Storage bucket
I want to read data from Google Storage Bucket using Google Session Token in Spark Application.
Here instead of json.keyfile I want to use Google Session Key in spark conf option.

I tried with json.key file but Actually I am looking for Google Session Token approach.
Is there any spark conf option way like below :

spark.conf.set("fs.gs.impl", "com.google.cloud.hadoop.fs.gcs.GoogleHadoopFileSystem")   spark.conf.set("fs.AbstractFileSystem.gs.impl","com.google.cloud.hadoop.fs.gcs.GoogleHadoopFS")
spark.conf.set("google.cloud.auth.service.account.enable","true")
spark.conf.set("google.cloud.auth.service.account.json.keyfile","<key_file_path>")

Here instead of json.keyfile I want to use Google Session token


问:
Optimizing over different pandas grouby's

Intent

Calculating weighted averages for different combinations of columns in a DataFrame df, and identifying anomalies in these averages based on how far they deviate from the mean of the weighted averages.

The code iterates through all combinations of the category columns (i.e., columns that are not "weight" or "score") using the combinations function from the itertools module. For each combination, it groups the DataFrame by these columns, calculates the weighted average using the weighted_average function, and stores the resulting DataFrame as df_wa.

Next, the code calculates the mean and standard deviation of the weighted averages in df_wa and stores them as new columns in df_wa. It then identifies anomalies by selecting rows in which the absolute difference between the weighted average and the mean is greater than three times the standard deviation. These anomalous rows, along with the combination of columns used to group the data, are stored in the results dictionary as a list of dictionaries. Each dictionary contains information about the reference group (i.e., the combination of columns used to group the data), a description of the anomaly, and the score and reference score for the anomaly.

Problem

This code seems to take to long. On my laptop it takes about 90 seconds to perform on a dataset of 1000 rows and 9 category columns.
However when deployed to aws lambda, it takes about 6 minutes.

Looking for optimizations to help the speed.

from itertools import combinations

import pandas as pd

def weighted_average(df: pd.DataFrame):
    if "weight" in df.columns:
        return sum(df["weight"] * df["score"]) / df["weight"].sum()
    return sum(df["score"]) / df["score"].count()

def main() -> dict:

    # read all the data
    df = pd.read_csv("./review.csv")

    # Create a dictionary to store the results
    results = {"anomalies": []}

    # create list of the category columns
    categories = [item for item in df.columns if item not in ["weight", "score"]]

    # Iterate through each unique combination of columns
    for i in range(0, len(categories)):
        for cols in combinations(categories, i + 1):

            # group by combination of column, calculate the weighted average
            df_wa = df_wa = (
                            df.groupby(by=list(cols))
                            .apply(lambda x: weighted_average(x))
                            .reset_index()
                            .rename(columns={0: "weighted_average"})
                        )
            # print(df_wa.shape)
            if len(df_wa) < 30:
                continue
            # calculate the mean and std from the weighted average
            df_wa["weighted_average_mean"] = df_wa["weighted_average"].mean()
            df_wa["weighted_average_std"] = df_wa["weighted_average"].std()

            # calculate the anomalies
            anomalies = df_wa.query(
            "abs(weighted_average - weighted_average_mean) > (3 * weighted_average_std)"
            )

            # store the anomalous rows and the column combination in the results dictionary
            ref_group = " and ".join(cols)
            for _, row in anomalies.iterrows():

                perc = abs(100 - (row["weighted_average"] / row["weighted_average_mean"] * 100))
                aob = "above" if (perc > 100) else "below"
                group = " and ".join(
                    row.drop(
                        labels=[
                            "weighted_average",
                            "weighted_average_mean",
                            "weighted_average_std",
                        ]
                    ).values
                )
                srs = " and ".join(
                    [str(x) for x in row[["weighted_average", "weighted_average_mean"]].values]
                )

                anomaly = {
                    "reference_group": ref_group,
                    "description": f"{group} : score is {perc:.2f}% {aob} others.",
                    "Score_and_reference_score": srs,
                }
                results["anomalies"].append(anomaly)

    return results
```

So for I've chosen to do an early exit from a loop if df_wa has fewer than 30 rows, and move on to the next combination.

But this hasn't reduced the time mucha as most of the groupby dataframes have more than 30 rows...

Body:
Intent

Calculating weighted averages for different combinations of columns in a DataFrame df, and identifying anomalies in these averages based on how far they deviate from the mean of the weighted averages.

The code iterates through all combinations of the category columns (i.e., columns that are not "weight" or "score") using the combinations function from the itertools module. For each combination, it groups the DataFrame by these columns, calculates the weighted average using the weighted_average function, and stores the resulting DataFrame as df_wa.

Next, the code calculates the mean and standard deviation of the weighted averages in df_wa and stores them as new columns in df_wa. It then identifies anomalies by selecting rows in which the absolute difference between the weighted average and the mean is greater than three times the standard deviation. These anomalous rows, along with the combination of columns used to group the data, are stored in the results dictionary as a list of dictionaries. Each dictionary contains information about the reference group (i.e., the combination of columns used to group the data), a description of the anomaly, and the score and reference score for the anomaly.

Problem

This code seems to take to long. On my laptop it takes about 90 seconds to perform on a dataset of 1000 rows and 9 category columns.
However when deployed to aws lambda, it takes about 6 minutes.

Looking for optimizations to help the speed.

from itertools import combinations

import pandas as pd

def weighted_average(df: pd.DataFrame):
    if "weight" in df.columns:
        return sum(df["weight"] * df["score"]) / df["weight"].sum()
    return sum(df["score"]) / df["score"].count()

def main() -> dict:

    # read all the data
    df = pd.read_csv("./review.csv")

    # Create a dictionary to store the results
    results = {"anomalies": []}

    # create list of the category columns
    categories = [item for item in df.columns if item not in ["weight", "score"]]

    # Iterate through each unique combination of columns
    for i in range(0, len(categories)):
        for cols in combinations(categories, i + 1):

            # group by combination of column, calculate the weighted average
            df_wa = df_wa = (
                            df.groupby(by=list(cols))
                            .apply(lambda x: weighted_average(x))
                            .reset_index()
                            .rename(columns={0: "weighted_average"})
                        )
            # print(df_wa.shape)
            if len(df_wa) < 30:
                continue
            # calculate the mean and std from the weighted average
            df_wa["weighted_average_mean"] = df_wa["weighted_average"].mean()
            df_wa["weighted_average_std"] = df_wa["weighted_average"].std()

            # calculate the anomalies
            anomalies = df_wa.query(
            "abs(weighted_average - weighted_average_mean) > (3 * weighted_average_std)"
            )

            # store the anomalous rows and the column combination in the results dictionary
            ref_group = " and ".join(cols)
            for _, row in anomalies.iterrows():

                perc = abs(100 - (row["weighted_average"] / row["weighted_average_mean"] * 100))
                aob = "above" if (perc > 100) else "below"
                group = " and ".join(
                    row.drop(
                        labels=[
                            "weighted_average",
                            "weighted_average_mean",
                            "weighted_average_std",
                        ]
                    ).values
                )
                srs = " and ".join(
                    [str(x) for x in row[["weighted_average", "weighted_average_mean"]].values]
                )

                anomaly = {
                    "reference_group": ref_group,
                    "description": f"{group} : score is {perc:.2f}% {aob} others.",
                    "Score_and_reference_score": srs,
                }
                results["anomalies"].append(anomaly)

    return results

So for I've chosen to do an early exit from a loop if df_wa has fewer than 30 rows, and move on to the next combination.

But this hasn't reduced the time mucha as most of the groupby dataframes have more than 30 rows...


问:
How to configure a default pull repo?
I have multiple clones of the same remote repo. In order to decrease download time and (hopefully) increase pull speed, one of the clones is read only.

I would like to configure the other clones to pull from the read-only clone by default. Ideally, the read-only can be named ro and the remote repo that'll be pushed to can continue to be called origin.

Is there a way to do this? If so, how?

Title: How to configure a default pull repo?


问:
Emscripten threads and custom web workers
I wrote an app to process gcode files in C/C++ compiled using emscripten. File parsing and processing is done in std::threads. Displaying in webgl is done using Threejs on main browser thread.

Now, I need to do offscreen canvas with threejs in a web worker so I can speedup display. The ideal situation is where I could access Wasm from main browser thread and web worker, so I could load the 3d webgl data to send to threejs from the web worker, and fetch statistical data from the main browser thread to display to the user.

If I do send the wasm memory and wasm module to the javascript manually created webworker, I get some stack-pointer exception when calling wasm functions (as it seems emscripten with pthreads initialize a thread stack for every workers). I mean here that a copied, pasted some parts of myapp.worker.js generated by emscripten into a worker file, let's say myapp.threejs.worker.js.

I have these options:

Create a webworker form javascript, and access wasm only from this worker. Main browser thread must then communicate throught the worker to access wasm, affecting performance if some data is hardly transferable

Create a new thread in wasm, create a C api to call javascript and threejs in worker. The problem is, if a spawn a thread from wasm, I can not actually send the offscreen canvas to the web worker through wasm, unless I can communicate directly from javascript to web worker spawned by wasm.

Create a web worker from javascript, but communicate with wasm through main browser thread only. This approch suffers from UI blocking while receiving GL data, as it must pass on the UI thread.

My question is: is there a way to create a web worker from javascript and access wasm from web worker and main thread ? If not, is there a way to spawn a new web worker from wasm thread but post and receive message from javascript in main browser thread without passing through wasm ? Thanks.


问:
Issue with adding SES permissions to Terraform
I am very new to Terraform, so still finding my way around at the moment.

I am needing to add SES permissions to a Lambda function, for sending emails.

I thought it would be as simple as adding the DynamoDB permissions, but there seems to be a different format aws_ses_identity_policy instead of aws_iam_policy_attachment, and as a result, in the todo problem line, I can’t seem to just use .arn to link the policy to the Role.

Is there a different way of doing this? Am I looking at older versions of the library? Any help would be appreciated. Thanks.

```<code>### DynamoDB
…

resource "aws_iam_policy" "DynamoDBCrudPolicy" {
  name = "DynamoDBCrudPolicy"
  policy = data.aws_iam_policy_document.dynamodbPolicyDocument.json
}

### SES

data "aws_iam_policy_document" "sesPolicyDocument" {
  statement {
  actions = ["SES:SendEmail", "SES:SendRawEmail"]
  resources = [aws_ses_domain_identity.SESPolicy.arn]

  principals {
  identifiers = ["*"]
  type = "AWS"
  }
  }
}

resource "aws_ses_domain_identity" "SESPolicyDomainID" {
  domain = "example.com"
}

resource "aws_ses_identity_policy" "SESPolicy" {
  identity = aws_ses_domain_identity.SESPolicyDomainID.arn
  name = "SESPolicy"
  policy = data.aws_iam_policy_document.sesPolicyDocument.json
}

## Attach Policies to Role

resource "aws_iam_policy_attachment" "DynamoDBCrudPolicy_iam_policy_attachment" {
  name = "DynamoDBCrudPolicy_iam_policy_attachment"
  roles = [ aws_iam_role.DomainRole.name ]
  policy_arn = aws_iam_policy.DynamoDBCrudPolicy.arn
}

resource "aws_iam_policy_attachment" "SES_iam_policy_attachment" {
  name = "SESPolicy_iam_policy_attachment"
  roles = [ aws_iam_role.DomainRole.name ]

  # Todo problem here
  policy_arn = aws_ses_identity_policy.SESPolicy.arn
}
</code>```

Body:
I am very new to Terraform, so still finding my way around at the moment.

I am needing to add SES permissions to a Lambda function, for sending emails.

I thought it would be as simple as adding the DynamoDB permissions, but there seems to be a different format aws_ses_identity_policy instead of aws_iam_policy_attachment, and as a result, in the todo problem line, I can’t seem to just use .arn to link the policy to the Role.

Is there a different way of doing this? Am I looking at older versions of the library? Any help would be appreciated. Thanks.

### DynamoDB
…

resource "aws_iam_policy" "DynamoDBCrudPolicy" {
  name = "DynamoDBCrudPolicy"
  policy = data.aws_iam_policy_document.dynamodbPolicyDocument.json
}

### SES

data "aws_iam_policy_document" "sesPolicyDocument" {
  statement {
  actions = ["SES:SendEmail", "SES:SendRawEmail"]
  resources = [aws_ses_domain_identity.SESPolicy.arn]

  principals {
  identifiers = ["*"]
  type = "AWS"
  }
  }
}

resource "aws_ses_domain_identity" "SESPolicyDomainID" {
  domain = "example.com"
}

resource "aws_ses_identity_policy" "SESPolicy" {
  identity = aws_ses_domain_identity.SESPolicyDomainID.arn
  name = "SESPolicy"
  policy = data.aws_iam_policy_document.sesPolicyDocument.json
}

## Attach Policies to Role

resource "aws_iam_policy_attachment" "DynamoDBCrudPolicy_iam_policy_attachment" {
  name = "DynamoDBCrudPolicy_iam_policy_attachment"
  roles = [ aws_iam_role.DomainRole.name ]
  policy_arn = aws_iam_policy.DynamoDBCrudPolicy.arn
}

resource "aws_iam_policy_attachment" "SES_iam_policy_attachment" {
  name = "SESPolicy_iam_policy_attachment"
  roles = [ aws_iam_role.DomainRole.name ]

  # Todo problem here
  policy_arn = aws_ses_identity_policy.SESPolicy.arn
}


问:
Animating organisms motion with matplotlib
I am trying to create an organism evolution simulation with python. I have just started, so I am only at the very beginnig and I already failed miserably.

I have created the class for organism and the functions for plotting organisms and plotting the frames as well.

I have created already a very basic "motion" of the organism, but instead of getting to see the "movement" I get the final image displaying all the stages of the motion on one image. I have tried to place plt.show and sleep everywhere, but no awail.

Could you please and give me some hints where I should be putting (or what should I be changing) in order to make it work?

the code:

```<code>import matplotlib.pyplot as plt
from random import uniform

from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import matplotlib.lines as lines

from math import sin
from math import cos
from math import radians

from matplotlib.patches import Circle

settings={
    "max_x":300,
    "min_x":0,
    "max_y":300,
    "min_y":0,

    "v_max":0.5,

    "pop_size":1

}

class organism:
    def __init__(self, settings):
        self.x=uniform(settings['min_x'], settings['max_x'])
        self.y=uniform(settings['min_y'], settings['max_y'])

        self.r=uniform(0,360) #irány
        self.v=uniform(0,0.5)

    def move(self):
        self.x=self.x+5

def plot_organism(x1,y1,theta,ax):
    circle=Circle([x1,y1], 10, edgecolor='g', facecolor='lightgreen', zorder=8)
    ax.add_artist(circle)

    edge=Circle([x1,y1], 10, facecolor='None', edgecolor='darkgreen', zorder=8)
    ax.add_artist(edge)

    tail_len=0.075

    x2=cos(radians(theta))*tail_len+x1
    y2=sin(radians(theta))*tail_len+y1

    ax.add_line(lines.Line2D([x1,x2],[y1,y2], color='darkgreen', linewidth=1, zorder=10))

    pass

def plot_frame(settings, organisms,fig,ax):

    plt.xlim(settings["min_x"]*1.25, settings['max_x']*1.25)
    plt.ylim(settings["min_y"]*1.25, settings['max_y']*1.25)

    for organism in organisms:
        plot_organism(organism.x,organism.y,organism.r,ax)

    ax.set_aspect('equal')
    frame = plt.gca()

def simulate(total_time, organisms):
    fig,ax=plt.subplots()
    fig.set_size_inches(9.6,5.4)

    total_time_step=total_time

    for t_step in range(0,total_time_step):
        plot_frame(settings,organisms,fig,ax)

        for organism in organisms:
            organism.move()

    sleep(0.5)
    plt.show()

    return organisms

def run(settings):

    organisms=[]
    for i in range(0,settings["pop_size"]):
        organisms.append(organism(settings))

    simulate(10, organisms)

    pass

run(settings)
</code>```

the output I am getting:
[![enter image description here][1]][1]

I am trying to make the simulation based on [this/][2]

Thank you in advance for your help!
[1]: https://i.stack.imgur.com/NHbn4.png
[2]: https://nathanrooy.github.io/posts/2017-11-30/evolving-simple-organisms-using-a-genetic-algorithm-and-deep-learning/

Body:
I am trying to create an organism evolution simulation with python. I have just started, so I am only at the very beginnig and I already failed miserably.

I have created the class for organism and the functions for plotting organisms and plotting the frames as well.

I have created already a very basic "motion" of the organism, but instead of getting to see the "movement" I get the final image displaying all the stages of the motion on one image. I have tried to place plt.show and sleep everywhere, but no awail.

Could you please and give me some hints where I should be putting (or what should I be changing) in order to make it work?

the code:

import matplotlib.pyplot as plt
from random import uniform

from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import matplotlib.lines as lines

from math import sin
from math import cos
from math import radians

from matplotlib.patches import Circle

settings={
    "max_x":300,
    "min_x":0,
    "max_y":300,
    "min_y":0,

    "v_max":0.5,

    "pop_size":1

}

class organism:
    def __init__(self, settings):
        self.x=uniform(settings['min_x'], settings['max_x'])
        self.y=uniform(settings['min_y'], settings['max_y'])

        self.r=uniform(0,360) #irány
        self.v=uniform(0,0.5)

    def move(self):
        self.x=self.x+5

def plot_organism(x1,y1,theta,ax):
    circle=Circle([x1,y1], 10, edgecolor='g', facecolor='lightgreen', zorder=8)
    ax.add_artist(circle)

    edge=Circle([x1,y1], 10, facecolor='None', edgecolor='darkgreen', zorder=8)
    ax.add_artist(edge)

    tail_len=0.075

    x2=cos(radians(theta))*tail_len+x1
    y2=sin(radians(theta))*tail_len+y1

    ax.add_line(lines.Line2D([x1,x2],[y1,y2], color='darkgreen', linewidth=1, zorder=10))

    pass

def plot_frame(settings, organisms,fig,ax):

    plt.xlim(settings["min_x"]*1.25, settings['max_x']*1.25)
    plt.ylim(settings["min_y"]*1.25, settings['max_y']*1.25)

    for organism in organisms:
        plot_organism(organism.x,organism.y,organism.r,ax)

    ax.set_aspect('equal')
    frame = plt.gca()

def simulate(total_time, organisms):
    fig,ax=plt.subplots()
    fig.set_size_inches(9.6,5.4)

    total_time_step=total_time

    for t_step in range(0,total_time_step):
        plot_frame(settings,organisms,fig,ax)

        for organism in organisms:
            organism.move()

    sleep(0.5)
    plt.show()

    return organisms

def run(settings):

    organisms=[]
    for i in range(0,settings["pop_size"]):
        organisms.append(organism(settings))

    simulate(10, organisms)

    pass

run(settings)

the output I am getting:
[![enter image description here][1]][1]

I am trying to make the simulation based on [this/][2]

Thank you in advance for your help!
[1]: https://i.stack.imgur.com/NHbn4.png
[2]: https://nathanrooy.github.io/posts/2017-11-30/evolving-simple-organisms-using-a-genetic-algorithm-and-deep-learning/


问:
NotImplementedError: unable to open file: libtensorflow_io.so
I try to train a deep learning model with a data generator but when I do a .fit I have the following error message:

```<code>NotImplementedError: unable to open file: libtensorflow_io.so, from paths: ['/home/jacquin/.local/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so']
caused by: ['/home/jacquin/.local/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so: undefined symbol: _ZNK10tensorflow4data11DatasetBase8FinalizeEPNS_15OpKernelContextESt8functionIFN3tsl8StatusOrISt10unique_ptrIS1_NS5_4core15RefCountDeleterEEEEvEE']
</code>```

I have tensorflow v 2.8.0, tfio 0.28.0, python 3.9.12

I had some issues to install the GPU on tensorflow.

Thanks for your help.

I had a look on stack overflow and followed some instructions but it did not work.

Body:
I try to train a deep learning model with a data generator but when I do a .fit I have the following error message:

NotImplementedError: unable to open file: libtensorflow_io.so, from paths: ['/home/jacquin/.local/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so']
caused by: ['/home/jacquin/.local/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so: undefined symbol: _ZNK10tensorflow4data11DatasetBase8FinalizeEPNS_15OpKernelContextESt8functionIFN3tsl8StatusOrISt10unique_ptrIS1_NS5_4core15RefCountDeleterEEEEvEE']

I have tensorflow v 2.8.0, tfio 0.28.0, python 3.9.12

I had some issues to install the GPU on tensorflow.

Thanks for your help.

I had a look on stack overflow and followed some instructions but it did not work.


问:
Error: Liquid syntax error (/github/workspace/_includes/foot.html line 1): Expected end_of_string but found id included
I want to deploy in Github pages some code, but I get this error and I don't understand where the mistake is. The error is:

Error:  Liquid syntax error (/github/workspace/_includes/foot.html line 1): Expected end_of_string but found id included

And the page:

```<code>`<!-- Optional JS for Bootstrap: jQuery first, then Bootstrap bundle JS -->
<script src="{{ '/js/jquery-3.5.1.min.js' | prepend: site.digital-assets }}"></script>
<script src="{{ '/js/bootstrap.bundle.min.js' | prepend: site.digital-assets }}"></script>
<!-- load other js -->
<script src="{{ '/js/lazysizes.min.js' | prepend: site.digital-assets }}" async></script>
{% if layout.gallery == true or page.gallery == true %}{% include js/gallery-js.html %}{% endif %}
{% if page.layout == "browse" %}{% include js/browse-js.html %}{% endif %}
{% if page.layout == "data" %}{% include js/table-js.html %}{% endif %}
{% if page.layout == "subjects" and site.data.theme.subjects-fields %}{% include js/cloud-js.html fields=site.data.theme.subjects-fields min=site.data.theme.subjects-min stopwords=site.data.theme.subjects-stopwords %}{% endif %}
{% if page.layout == "locations" and site.data.theme.locations-fields %}{% include js/cloud-js.html fields=site.data.theme.locations-fields min=site.data.theme.locations-min stopwords=site.data.theme.locations-stopwords %}{% endif %}
{% if page.layout == "timeline" %}{% include js/timeline-js.html %}{% endif %}
{% if page.layout == "map" %}{% include js/map-js.html %}{% endif %}
{% if page.layout == "item" %}{% include js/arrow-page-control-js.html %}{% endif %}
{% if page.layout == "search" %}{% include js/lunr-js.html %}{% endif %}
{%- if page.layout == "home-infographic" %}{% include js/carousel-js.html %}{% endif -%}`
</code>```

If I delete the whole page the build works, but of course I need javascript.

I also tried deleting specific pieces of code but nothing.

Body:
I want to deploy in Github pages some code, but I get this error and I don't understand where the mistake is. The error is:

Error:  Liquid syntax error (/github/workspace/_includes/foot.html line 1): Expected end_of_string but found id included

And the page:

`

{% if layout.gallery == true or page.gallery == true %}{% include js/gallery-js.html %}{% endif %}
{% if page.layout == "browse" %}{% include js/browse-js.html %}{% endif %}
{% if page.layout == "data" %}{% include js/table-js.html %}{% endif %}
{% if page.layout == "subjects" and site.data.theme.subjects-fields %}{% include js/cloud-js.html fields=site.data.theme.subjects-fields min=site.data.theme.subjects-min stopwords=site.data.theme.subjects-stopwords %}{% endif %}
{% if page.layout == "locations" and site.data.theme.locations-fields %}{% include js/cloud-js.html fields=site.data.theme.locations-fields min=site.data.theme.locations-min stopwords=site.data.theme.locations-stopwords %}{% endif %}
{% if page.layout == "timeline" %}{% include js/timeline-js.html %}{% endif %}
{% if page.layout == "map" %}{% include js/map-js.html %}{% endif %}
{% if page.layout == "item" %}{% include js/arrow-page-control-js.html %}{% endif %}
{% if page.layout == "search" %}{% include js/lunr-js.html %}{% endif %}
{%- if page.layout == "home-infographic" %}{% include js/carousel-js.html %}{% endif -%}`

If I delete the whole page the build works, but of course I need javascript.

I also tried deleting specific pieces of code but nothing.


问:
Producing readable coloured terminal output
I want to produce coloured output from a terminal program. My problem is that some people use a 'light' terminal theme, while others use a 'dark' one.

Is there a standard way of ensuring that my output will be readable for all "reasonable" terminal configurations (for some definition of reasonable)?


问:
Move messages from pubsub dead-letter topic to original topic
I have set up pubsub subscription with dead lettering. So after five unsuccessful attempts my messages are being transfered to dead-letter topic. This works fine and I can peek this messages in dead-letter subscription.

What I want to do is after some time, transfer this messages back to the original topic and I want to do it manually. What is the easiest and fastes way to acheive this?


问:
Can't track events of Looker Embedded Dashborard (SSO embedded) in Nest.JS application
I have next.js project, on server side I generate Looker-sso url and on client side I use this url for embedded dashboard.

Here is how I generate SSO url at Next.js server side

```<code>
function getLookerSsoUrl(embeddedUserParams: UserInfo, dashboardId: string) : string {
    /** Returns Looker Embedded sso url. */

    const url_data : LookerEmbeddedUrlOptions = {
        "host": LOOKER_HOST,
        "secret": LOOKER_SECRET,
        "first_name": embeddedUserParams.firstName,
        "last_name": embeddedUserParams.lastName,
        "external_user_id": embeddedUserParams.firstName + " " + embeddedUserParams.lastName,
        "external_group_id": embeddedUserParams.companyName + " group",
        "group_ids": [1],
        "access_filters": {},
        "models": ['db_analytics'],
        "permissions": [
            'see_user_dashboards',
            'see_lookml_dashboards',
            'access_data',
            'see_looks'],
        "user_attributes": {
            "name": embeddedUserParams.firstName + " " + embeddedUserParams.lastName,
            "first_name": embeddedUserParams.firstName,
            "last_name": embeddedUserParams.lastName,
            "email": embeddedUserParams.email,
            "company_id": embeddedUserParams.companyId,
            "company_name": embeddedUserParams.companyName,
            "id": embeddedUserParams.id
        },
        "session_length": 15 * 60,
        "embed_url": `/embed/dashboards/${dashboardId}?embed_domain=http://localhost&company_id=${embeddedUserParams.companyId}`,
        "force_logout_login": true
    }

    return "https://" + getSignedEmbedUrl(url_data)
}

function getSignedEmbedUrl(options : LookerEmbeddedUrlOptions) : string {
    /** Build sso url with all Looker options and secret key and returns it. */

        // looker options
    const secret = options.secret
    const host = options.host

    // user options
    const json_external_user_id = JSON.stringify(options.external_user_id)
    const json_first_name = JSON.stringify(options.first_name)
    const json_last_name = JSON.stringify(options.last_name)
    const json_permissions = JSON.stringify(options.permissions)
    const json_models = JSON.stringify(options.models)
    const json_group_ids = JSON.stringify(options.group_ids)
    const json_external_group_id = JSON.stringify(options.external_group_id || "")
    const json_user_attributes = JSON.stringify(options.user_attributes || {})
    const json_access_filters = JSON.stringify(options.access_filters)

    // url/session specific options
    const embed_path = '/login/embed/' + encodeURIComponent(options.embed_url)
    const json_session_length = JSON.stringify(options.session_length)
    const json_force_logout_login = JSON.stringify(options.force_logout_login)

    // computed options
    const json_time = JSON.stringify(Math.floor((new Date()).getTime() / 1000))
    const json_nonce = JSON.stringify(getNonce(16))

    // compute signature
    let string_to_sign = ""
    string_to_sign += host + "\n"
    string_to_sign += embed_path + "\n"
    string_to_sign += json_nonce + "\n"
    string_to_sign += json_time + "\n"
    string_to_sign += json_session_length + "\n"
    string_to_sign += json_external_user_id + "\n"
    string_to_sign += json_permissions + "\n"
    string_to_sign += json_models + "\n"
    string_to_sign += json_group_ids + "\n"
    string_to_sign += json_external_group_id + "\n"
    string_to_sign += json_user_attributes + "\n"
    string_to_sign += json_access_filters

    const signature = createHmac('sha1', secret).update(ForceUnicodeEncoding(string_to_sign)).digest('base64').trim()

    // construct query string
    const query_params = {
        nonce: json_nonce,
        time: json_time,
        session_length: json_session_length,
        external_user_id: json_external_user_id,
        permissions: json_permissions,
        models: json_models,
        access_filters: json_access_filters,
        first_name: json_first_name,
        last_name: json_last_name,
        group_ids: json_group_ids,
        external_group_id: json_external_group_id,
        user_attributes: json_user_attributes,
        force_logout_login: json_force_logout_login,
        signature: signature
    }

    const query_string = stringify(query_params)

    return host + embed_path + '?' + query_string
}

function getNonce(len : number) : string {
    /** Returns nonce characters. */

    let text = ""
    const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

    for (let i = 0; i < len; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length))

    return text
}

function ForceUnicodeEncoding(string : string) : string {
    /** Decodes a URI component previously created by encodeURIComponent. */

    return decodeURIComponent(encodeURIComponent(string))
}

</code>```

Here is client side code:

```<code>import React, {useCallback} from "react"
import {LookerEmbedSDK} from "@looker/embed-sdk"
import {ENV_VAR} from "env"

type embeddedDashboardType = {
    id : number
    setError? :  ((errorMsg : string) => void)
}

export const EmbeddedDashboard = ({id, setError} : embeddedDashboardType) => {
    const canceller = (event : any) => {
        return { cancel: !event.modal }
    }
    document.addEventListener("click", ()=>console.log("r"))

    const embedCtrRef = useCallback((el) => {
        const authUrl = "/api/looker-sso"

        if (el) {
            LookerEmbedSDK.init("...", authUrl)
            LookerEmbedSDK.createDashboardWithId(id)
                .withNext()
                .appendTo(el)
                .on("drillmenu:click", canceller)
                .on("drillmodal:explore", canceller)
                .on("dashboard:tile:explore", canceller)
                .on("look:ready", ()=> console.log("ready"))
                .on("explore:ready", ()=>console.log("ready"))
                .on("dashboard:run:start", ()=>console.log("ready"))
                .on("dashboard:tile:view", canceller)
                .build()
                .connect()
                .catch((error) => {
                    console.error("Connection error", error)

                    if (setError){
                        setError(error)
                    }
                })
        }
    }, [])

  return <>
    <style jsx>{`
      :global(.container-dashboard) {
        width: 100%;
        height: 95vh;
      }
      :global(.container-dashboard > iframe) {
         width: 100%;
         height: 100%;
      }
    `}</style>
      <div className="container-dashboard" ref={embedCtrRef} />
  </>
}
</code>```

The dashboard displays correctly, but I cant track events, that happen in Looker Iframe

I except, that I would see clicks, which are made on looker iframe

Body:
I have next.js project, on server side I generate Looker-sso url and on client side I use this url for embedded dashboard.

Here is how I generate SSO url at Next.js server side

function getLookerSsoUrl(embeddedUserParams: UserInfo, dashboardId: string) : string {
    /** Returns Looker Embedded sso url. */

    const url_data : LookerEmbeddedUrlOptions = {
        "host": LOOKER_HOST,
        "secret": LOOKER_SECRET,
        "first_name": embeddedUserParams.firstName,
        "last_name": embeddedUserParams.lastName,
        "external_user_id": embeddedUserParams.firstName + " " + embeddedUserParams.lastName,
        "external_group_id": embeddedUserParams.companyName + " group",
        "group_ids": [1],
        "access_filters": {},
        "models": ['db_analytics'],
        "permissions": [
            'see_user_dashboards',
            'see_lookml_dashboards',
            'access_data',
            'see_looks'],
        "user_attributes": {
            "name": embeddedUserParams.firstName + " " + embeddedUserParams.lastName,
            "first_name": embeddedUserParams.firstName,
            "last_name": embeddedUserParams.lastName,
            "email": embeddedUserParams.email,
            "company_id": embeddedUserParams.companyId,
            "company_name": embeddedUserParams.companyName,
            "id": embeddedUserParams.id
        },
        "session_length": 15 * 60,
        "embed_url": `/embed/dashboards/${dashboardId}?embed_domain=http://localhost&company_id=${embeddedUserParams.companyId}`,
        "force_logout_login": true
    }

    return "https://" + getSignedEmbedUrl(url_data)
}

function getSignedEmbedUrl(options : LookerEmbeddedUrlOptions) : string {
    /** Build sso url with all Looker options and secret key and returns it. */

        // looker options
    const secret = options.secret
    const host = options.host

    // user options
    const json_external_user_id = JSON.stringify(options.external_user_id)
    const json_first_name = JSON.stringify(options.first_name)
    const json_last_name = JSON.stringify(options.last_name)
    const json_permissions = JSON.stringify(options.permissions)
    const json_models = JSON.stringify(options.models)
    const json_group_ids = JSON.stringify(options.group_ids)
    const json_external_group_id = JSON.stringify(options.external_group_id || "")
    const json_user_attributes = JSON.stringify(options.user_attributes || {})
    const json_access_filters = JSON.stringify(options.access_filters)

    // url/session specific options
    const embed_path = '/login/embed/' + encodeURIComponent(options.embed_url)
    const json_session_length = JSON.stringify(options.session_length)
    const json_force_logout_login = JSON.stringify(options.force_logout_login)

    // computed options
    const json_time = JSON.stringify(Math.floor((new Date()).getTime() / 1000))
    const json_nonce = JSON.stringify(getNonce(16))

    // compute signature
    let string_to_sign = ""
    string_to_sign += host + "\n"
    string_to_sign += embed_path + "\n"
    string_to_sign += json_nonce + "\n"
    string_to_sign += json_time + "\n"
    string_to_sign += json_session_length + "\n"
    string_to_sign += json_external_user_id + "\n"
    string_to_sign += json_permissions + "\n"
    string_to_sign += json_models + "\n"
    string_to_sign += json_group_ids + "\n"
    string_to_sign += json_external_group_id + "\n"
    string_to_sign += json_user_attributes + "\n"
    string_to_sign += json_access_filters

    const signature = createHmac('sha1', secret).update(ForceUnicodeEncoding(string_to_sign)).digest('base64').trim()

    // construct query string
    const query_params = {
        nonce: json_nonce,
        time: json_time,
        session_length: json_session_length,
        external_user_id: json_external_user_id,
        permissions: json_permissions,
        models: json_models,
        access_filters: json_access_filters,
        first_name: json_first_name,
        last_name: json_last_name,
        group_ids: json_group_ids,
        external_group_id: json_external_group_id,
        user_attributes: json_user_attributes,
        force_logout_login: json_force_logout_login,
        signature: signature
    }

    const query_string = stringify(query_params)

    return host + embed_path + '?' + query_string
}

function getNonce(len : number) : string {
    /** Returns nonce characters. */

    let text = ""
    const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

    for (let i = 0; i < len; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length))

    return text
}

function ForceUnicodeEncoding(string : string) : string {
    /** Decodes a URI component previously created by encodeURIComponent. */

    return decodeURIComponent(encodeURIComponent(string))
}

Here is client side code:

import React, {useCallback} from "react"
import {LookerEmbedSDK} from "@looker/embed-sdk"
import {ENV_VAR} from "env"

type embeddedDashboardType = {
    id : number
    setError? :  ((errorMsg : string) => void)
}

export const EmbeddedDashboard = ({id, setError} : embeddedDashboardType) => {
    const canceller = (event : any) => {
        return { cancel: !event.modal }
    }
    document.addEventListener("click", ()=>console.log("r"))

    const embedCtrRef = useCallback((el) => {
        const authUrl = "/api/looker-sso"

        if (el) {
            LookerEmbedSDK.init("...", authUrl)
            LookerEmbedSDK.createDashboardWithId(id)
                .withNext()
                .appendTo(el)
                .on("drillmenu:click", canceller)
                .on("drillmodal:explore", canceller)
                .on("dashboard:tile:explore", canceller)
                .on("look:ready", ()=> console.log("ready"))
                .on("explore:ready", ()=>console.log("ready"))
                .on("dashboard:run:start", ()=>console.log("ready"))
                .on("dashboard:tile:view", canceller)
                .build()
                .connect()
                .catch((error) => {
                    console.error("Connection error", error)

                    if (setError){
                        setError(error)
                    }
                })
        }
    }, [])

  return <>

  </>
}

The dashboard displays correctly, but I cant track events, that happen in Looker Iframe

I except, that I would see clicks, which are made on looker iframe


问:
Creating a script component with error in SSIS
I am trying to get data from a IT ticketing system through API in SSIS using Script Component, very new to this:

I am just starting with 1 field called Supplier, for that i have so far written below scripts:

Script Component

Created a class called ResultAPI:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
    public class ResultAPI
    {
       public string Supplier { get; set; }

    }
}
</code>```

Another class called GenericResponse:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
    public class GenericResponse

    {
        public ResultAPI[] ListData { get; set; }
    }
    public class ResultGen
    {
        public GenericResponse Result { get; set; }
    }
}
</code>```

Main:

```<code>public override void CreateNewOutputRows()
    {

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://***************");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var cred = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "pwd")));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", cred);

            string APIUrl = string.Format("https://**************");

        var response = client.GetAsync(APIUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync().Result;
                var serializer = new JavaScriptSerializer();
                var data = serializer.Deserialize<ResultAPI>(result);

                APIResultsBuffer.AddRow();
                //APIResultsBuffer.SupplierType = data.SupplierType;
                APIResultsBuffer.Supplier = data.Supplier;
                //APIResultsBuffer.nextpage = data.nextpage;
                //APIResultsBuffer.previouspage = data.previouspage;
                //APIResultsBuffer.recordcount = data.recordcount;
                //APIResultsBuffer.HREF = data.HREF;
            }

        }

    }
</code>```

When I execute the package, i get the attached error:
Error

Not sure exactly where this error is.

Hoping to download this file in SQL Server table

Body:
I am trying to get data from a IT ticketing system through API in SSIS using Script Component, very new to this:

I am just starting with 1 field called Supplier, for that i have so far written below scripts:

Script Component

Created a class called ResultAPI:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
    public class ResultAPI
    {
       public string Supplier { get; set; }

    }
}

Another class called GenericResponse:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SC_b15eeeff0e3544d3a882578b3eb9bbba
{
    public class GenericResponse

    {
        public ResultAPI[] ListData { get; set; }
    }
    public class ResultGen
    {
        public GenericResponse Result { get; set; }
    }
}

Main:

public override void CreateNewOutputRows()
    {

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://***************");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            var cred = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "pwd")));
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", cred);

            string APIUrl = string.Format("https://**************");

        var response = client.GetAsync(APIUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var result = response.Content.ReadAsStringAsync().Result;
                var serializer = new JavaScriptSerializer();
                var data = serializer.Deserialize<ResultAPI>(result);

                APIResultsBuffer.AddRow();
                //APIResultsBuffer.SupplierType = data.SupplierType;
                APIResultsBuffer.Supplier = data.Supplier;
                //APIResultsBuffer.nextpage = data.nextpage;
                //APIResultsBuffer.previouspage = data.previouspage;
                //APIResultsBuffer.recordcount = data.recordcount;
                //APIResultsBuffer.HREF = data.HREF;
            }

        }

    }

When I execute the package, i get the attached error:
Error

Not sure exactly where this error is.

Hoping to download this file in SQL Server table