问:
i cant update itemcount
hey why is my itemcount not working i have 6 rows in my database but when i run the code it show me only one row and the other rows not showing it

this is my code:

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class my_ads extends StatefulWidget {
  const my_ads({Key? key}) : super(key: key);

  @override
  State<my_ads> createState() => _my_adsState();
}

List list = [];
int select_item = 0;

class _my_adsState extends State<my_ads> {
  @override
  Future ReadData() async {
    var url = "https://***.***.***.**/getData.php";
    var res = await http.get(Uri.parse(url));

    if (res.statusCode == 200) {
      var red = jsonDecode(res.body);

      setState(() {
        list.addAll(red);
      });

      print(list);
    }
  }

  @override
  void initState() {
    super.initState();

    GetData();
  }

  GetData() async {
    await ReadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.builder(
            itemCount: list.length,
            itemBuilder: ((cts, i) {
              return Container(
                height: 800,
                child: ListView(
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: 70, right: 60),
                      height: 54.0,
                      width: 224.0,
                      child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Color(0xffF4AC47), width: 5),
                              color: Color(0xff42A9D2),
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(40),
                                  bottomRight: Radius.circular(40))),
                          child: new Center(
                            child: new Text(
                              "MyAds",
                              style: TextStyle(
                                  fontSize: 25,
                                  color: Color(0xff072A52),
                                  fontFamily: 'Cairo'),
                              textAlign: TextAlign.center,
                            ),
                            //end logo
                          )),
                    ),

                    ///start Section
                    Container(
                      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
                      height: 180.0,
                      width: 430.0,
                      child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Color(0xff42A9D2), width: 5),
                              borderRadius: BorderRadius.circular(8)),
                          child: new Container(
                              child: Row(
                            children: [
                              Expanded(
                                  child: Image(
                                image: AssetImage("assets/book.jpg"),
                              )),
                              Container(
                                margin: EdgeInsets.only(
                                    left: 110, top: 30, right: 13),
                                child: Column(
                                  children: [
                                    Text(
                                      "test",
                                      style: TextStyle(
                                          fontSize: 20, color: Colors.black87),
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                    Row(
                                      children: [
                                        Text("test2"),
                                        Icon(Icons.perm_identity_rounded)
                                      ],
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Row(
                                      children: [
                                        Text("}"),
                                        Column(
                                          children: [Icon(Icons.store)],
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                              )
                            ],
                          )
                              //end logo

                              )),
                    ),
                  ],
                ),
              );
            })));
  }
}

</code>```

i tried to change ListView to ListTile but the design will be detroyed becuse i need to make the same design to other pages but my problem is with itemcount its not making any changes ! please if you have any ideas with my problem give me ansewrs

Title: i cant update itemcount

Body:
hey why is my itemcount not working i have 6 rows in my database but when i run the code it show me only one row and the other rows not showing it

this is my code:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class my_ads extends StatefulWidget {
  const my_ads({Key? key}) : super(key: key);

  @override
  State<my_ads> createState() => _my_adsState();
}

List list = [];
int select_item = 0;

class _my_adsState extends State<my_ads> {
  @override
  Future ReadData() async {
    var url = "https://***.***.***.**/getData.php";
    var res = await http.get(Uri.parse(url));

    if (res.statusCode == 200) {
      var red = jsonDecode(res.body);

      setState(() {
        list.addAll(red);
      });

      print(list);
    }
  }

  @override
  void initState() {
    super.initState();

    GetData();
  }

  GetData() async {
    await ReadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.builder(
            itemCount: list.length,
            itemBuilder: ((cts, i) {
              return Container(
                height: 800,
                child: ListView(
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: 70, right: 60),
                      height: 54.0,
                      width: 224.0,
                      child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Color(0xffF4AC47), width: 5),
                              color: Color(0xff42A9D2),
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(40),
                                  bottomRight: Radius.circular(40))),
                          child: new Center(
                            child: new Text(
                              "MyAds",
                              style: TextStyle(
                                  fontSize: 25,
                                  color: Color(0xff072A52),
                                  fontFamily: 'Cairo'),
                              textAlign: TextAlign.center,
                            ),
                            //end logo
                          )),
                    ),

                    ///start Section
                    Container(
                      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
                      height: 180.0,
                      width: 430.0,
                      child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color: Color(0xff42A9D2), width: 5),
                              borderRadius: BorderRadius.circular(8)),
                          child: new Container(
                              child: Row(
                            children: [
                              Expanded(
                                  child: Image(
                                image: AssetImage("assets/book.jpg"),
                              )),
                              Container(
                                margin: EdgeInsets.only(
                                    left: 110, top: 30, right: 13),
                                child: Column(
                                  children: [
                                    Text(
                                      "test",
                                      style: TextStyle(
                                          fontSize: 20, color: Colors.black87),
                                    ),
                                    SizedBox(
                                      height: 20,
                                    ),
                                    Row(
                                      children: [
                                        Text("test2"),
                                        Icon(Icons.perm_identity_rounded)
                                      ],
                                    ),
                                    SizedBox(
                                      height: 5,
                                    ),
                                    Row(
                                      children: [
                                        Text("}"),
                                        Column(
                                          children: [Icon(Icons.store)],
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                              )
                            ],
                          )
                              //end logo

                              )),
                    ),
                  ],
                ),
              );
            })));
  }
}

i tried to change ListView to ListTile but the design will be detroyed becuse i need to make the same design to other pages but my problem is with itemcount its not making any changes ! please if you have any ideas with my problem give me ansewrs


来源: stackexchange

问:
Is there a way to pass a lua array into a C function or to convert that array to a float *
I have a C function mesh_create_default(float *verts, uint32_t sizeof_verts):

void *mesh_create_default(float *verts, uint32_t sizeof_verts) {
    static void *mesh;
    mesh = mesh_create();
    mesh_data(mesh, verts, sizeof_verts);

    ...

    return &mesh;
}
```
<p>and a function for lua to use:</p>
<pre class="lang-c prettyprint-override"><code>int Lmesh_create_default(lua_State *L) {
    lua_pushinteger(L, (uint64_t)mesh_create_default(lua_touserdata(L, 1), lua_tointeger(L, 2)));
    return 0;
}
</code>```

I am passing the result of mesh as a a 64 bit integer (perhaps not the best solution, but it works fine). My problem is with the verts argument. I don't know how I can pass a lua array into C. I have tried researching this, but I haven't found anything that solves this problem.

Say I have this lua code (just an example of what I want to do, not actual working code):

Verts = { -- an array of vertices, perhaps it needs to be somehow converted into a float * (I would prefer to convert it on the C side though, and keep my lua scripts as clean as possible)
     0.0,  1.0, 0.0,
     1.0, -1.0, 0.0,
    -1.0, -1.0, 0.0,
}

function Ready()
    Mesh = mesh_create_default(Verts, 4 * 3 * 3) -- or 8? Lua uses doubles (I think) but my code
                                                 -- requires floats, so that could be a bit of a
                                                 -- problem...
end
```

I apologise if this is an easily solvable question. My knowledge of lua is not that good (thus why I decided to use it for my game engine, to learn it).

EDIT: I need the entire array because I don't know how large the verts array is. The other option is to just get the size of the array as well too though (although less ideal and probably slower)

EDIT 2: Actually I do have the size of the array -- the sizeof_verts variable. Because of this, I think that this question is a duplicate of the question posted by @larsks (Read Lua table from C).

ContentLicense: CC BY-SA 4.0

Body:
I have a C function mesh_create_default(float *verts, uint32_t sizeof_verts):

void *mesh_create_default(float *verts, uint32_t sizeof_verts) {
    static void *mesh;
    mesh = mesh_create();
    mesh_data(mesh, verts, sizeof_verts);

    ...

    return &mesh;
}

and a function for lua to use:

int Lmesh_create_default(lua_State *L) {
    lua_pushinteger(L, (uint64_t)mesh_create_default(lua_touserdata(L, 1), lua_tointeger(L, 2)));
    return 0;
}

I am passing the result of mesh as a a 64 bit integer (perhaps not the best solution, but it works fine). My problem is with the verts argument. I don't know how I can pass a lua array into C. I have tried researching this, but I haven't found anything that solves this problem.

Say I have this lua code (just an example of what I want to do, not actual working code):

Verts = { -- an array of vertices, perhaps it needs to be somehow converted into a float * (I would prefer to convert it on the C side though, and keep my lua scripts as clean as possible)
     0.0,  1.0, 0.0,
     1.0, -1.0, 0.0,
    -1.0, -1.0, 0.0,
}

function Ready()
    Mesh = mesh_create_default(Verts, 4 * 3 * 3) -- or 8? Lua uses doubles (I think) but my code
                                                 -- requires floats, so that could be a bit of a
                                                 -- problem...
end

I apologise if this is an easily solvable question. My knowledge of lua is not that good (thus why I decided to use it for my game engine, to learn it).

EDIT: I need the entire array because I don't know how large the verts array is. The other option is to just get the size of the array as well too though (although less ideal and probably slower)

EDIT 2: Actually I do have the size of the array -- the sizeof_verts variable. Because of this, I think that this question is a duplicate of the question posted by @larsks (Read Lua table from C).


问:
Is it possible to store an object in HttpHeaders in Java?
Forgive my ignorance - a jr developer here. I'm trying to make a PUT call to a client API. In the documentation it shows the request headers have an object in them. I thought headers could only have a String value. How can I add an object to my HttpHeaders object?

Request Model from API Documentation

```<code>requestHeader {
  "headerA": "valueA",
  "headerB": {
    "headerB1": "valueB1",
    "headerB2": "valueB2"
  },
  "headerC": "valueC"
}

requestBody {
  "object": {
              "variable1": 12345,
              "variable2": 54321
  },
  "sameNums": false }
</code>```

I'm using HttpHeaders from package org.springframework.http - the set() and add() methods take Strings as parameters. How can I add an object as a header value?

Body:
Forgive my ignorance - a jr developer here. I'm trying to make a PUT call to a client API. In the documentation it shows the request headers have an object in them. I thought headers could only have a String value. How can I add an object to my HttpHeaders object?

Request Model from API Documentation

requestHeader {
  "headerA": "valueA",
  "headerB": {
    "headerB1": "valueB1",
    "headerB2": "valueB2"
  },
  "headerC": "valueC"
}

requestBody {
  "object": {
              "variable1": 12345,
              "variable2": 54321
  },
  "sameNums": false }

I'm using HttpHeaders from package org.springframework.http - the set() and add() methods take Strings as parameters. How can I add an object as a header value?


问:
finding elements in an array containing numpy array
Is there a built in method to find a non numpy element in an array containing numpy arrays.

I tried

arr = [np.array(1,0), np.array(0,1), 0]
print(0 in arr)

But it resulted in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


问:
Rider doesn't run UnityYamlMerge when a merge conflict occurs
I am using Rider as my code editor and version control tool, and I have configured it to use UnityYamlMerge as the external merge tool. The issue is that when a merge conflict occurs, Rider is not calling UnityYamlMerge to resolve the conflict.

I have checked the path to the UnityYamlMerge executable and it is correct. I have also configured the merge tool in my Git repository settings, and it works when I call it manually using git mergetool. However, when I try to resolve a merge conflict in Rider, the tool is not being called.

I have tried enabling verbose logging in Rider and looking for error messages in the log files, but I have not been able to find any clues as to why the tool is not being called.

Has anyone else experienced this issue or knows how to fix it? Any help would be greatly appreciated.

here's the screenshots :

external diff tools window
unity yaml merge configuration
tools&frameworks > unity engine configuration
proof that it works when "git mergetol" command is called
proof that it doesn't work when I try to merge it in Rider


问:
How do I do a DISTINCT count on a combination of columns in python?
I have my function here:

```<code>    def getS3Unique(self, s3_table_unique):
        session = boto3.session.Session()
        config=self.config
        bucket_name = config["data"]["COMPARE"]["S3_BUCKET"]
        prefix = config["data"]["COMPARE"]["S3_PREFIX"]
        schema = config["data"]["database"]["schema"]
        client_s3 = boto3.client('s3')
        total_unique_combination=0
        unique_combination_cols=self.config["data"]["RULES"]["RULE_UNIQUE_COMBO"]["UNIQUE_COMBO_TABLES"][self.table]

        s3_table_unique[self.table]={}
        for key in s3_client.list_objects(Bucket=bucket_name,Prefix=prefix+"/"+schema+"/"+self.table.lower()+"/")['Contents']:
            print("UNIQUE COMBINATION FILE KEY: "+key['Key'])
            k=key['Key']
            obj = s3_client.get_object(Bucket=bucket_name, Key=k)
            df=pd.read_parquet(io.BytesIO(obj['Body'].read()))
            unique_count=df.drop_duplicates()
            c=len(unique_count)
            total_unique_combination=total_unique_combination+int(c)
        s3_table_unique[self.table]=str(total_unique_combination)
        total_unique_combination=0
        return s3_table_unique

</code>```

Basically, it grabs the tables and columns listed in the parquet file I have in my S3 bucket, and I am trying to do a unique count on a combination of columns.

Here is my config:

```<code>  },
   "RULE_UNIQUE_COMBO":{
     "VALIDATION": true,
     "UNIQUE_COMBO_TABLES":{
       "TABLE1": "col1,col2",
       "TABLE2": "col1,col2,col3,col4,col5"
   }
  },
</code>```

The function as it's written now, does a unique count on the total number of records in the table, for each table. So the output .json files are:

```<code>File1: {TABLE1: 10}
File2: {TABLE2: 20}
</code>```

I want my output to be:

```<code>File1: {TABLE1:{col1,col2: 10}}
File2: {TABLE2:{col1,col2,col3,col4,col5: 20}}
</code>```

So basically I am trying to count the combination of unique/distinct columns in each table.

Body:
I have my function here:

    def getS3Unique(self, s3_table_unique):
        session = boto3.session.Session()
        config=self.config
        bucket_name = config["data"]["COMPARE"]["S3_BUCKET"]
        prefix = config["data"]["COMPARE"]["S3_PREFIX"]
        schema = config["data"]["database"]["schema"]
        client_s3 = boto3.client('s3')
        total_unique_combination=0
        unique_combination_cols=self.config["data"]["RULES"]["RULE_UNIQUE_COMBO"]["UNIQUE_COMBO_TABLES"][self.table]

        s3_table_unique[self.table]={}
        for key in s3_client.list_objects(Bucket=bucket_name,Prefix=prefix+"/"+schema+"/"+self.table.lower()+"/")['Contents']:
            print("UNIQUE COMBINATION FILE KEY: "+key['Key'])
            k=key['Key']
            obj = s3_client.get_object(Bucket=bucket_name, Key=k)
            df=pd.read_parquet(io.BytesIO(obj['Body'].read()))
            unique_count=df.drop_duplicates()
            c=len(unique_count)
            total_unique_combination=total_unique_combination+int(c)
        s3_table_unique[self.table]=str(total_unique_combination)
        total_unique_combination=0
        return s3_table_unique

Basically, it grabs the tables and columns listed in the parquet file I have in my S3 bucket, and I am trying to do a unique count on a combination of columns.

Here is my config:

  },
   "RULE_UNIQUE_COMBO":{
     "VALIDATION": true,
     "UNIQUE_COMBO_TABLES":{
       "TABLE1": "col1,col2",
       "TABLE2": "col1,col2,col3,col4,col5"
   }
  },

The function as it's written now, does a unique count on the total number of records in the table, for each table. So the output .json files are:

File1: {TABLE1: 10}
File2: {TABLE2: 20}

I want my output to be:

File1: {TABLE1:{col1,col2: 10}}
File2: {TABLE2:{col1,col2,col3,col4,col5: 20}}

So basically I am trying to count the combination of unique/distinct columns in each table.


问:
Creating multiple tables with single query statement using swift
I am trying to create two tables with a single query statement. However, below code is creating just 'myprofile' table only. It doesn't create 'groups' table. Am I missing something here? Can someone please help.</p>
```<code>let createTableString = """
                    CREATE TABLE `myprofile` (`profile_id` VARCHAR , `first_name` VARCHAR , `profile_type` VARCHAR ,`preferences` VARCHAR);
                    CREATE TABLE `groups` (`account_id` VARCHAR ,`unique_url` VARCHAR, `title` VARCHAR, `participant_id` VARCHAR ,`create_date` VARCHAR,`synced` VARCHAR);
    """

private func createTable() {
      var createTableStatement: OpaquePointer?
      if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
          if sqlite3_step(createTableStatement) == SQLITE_DONE {
              print("\table's are created.")
          } else {
              print("\table's are not created.")
        }
      } else {
          print("\nCREATE TABLE statement is not prepared.")
      }

      sqlite3_finalize(createTableStatement)
    }
</code>```

Body:
I am trying to create two tables with a single query statement. However, below code is creating just 'myprofile' table only. It doesn't create 'groups' table. Am I missing something here? Can someone please help.

let createTableString = """
                    CREATE TABLE `myprofile` (`profile_id` VARCHAR , `first_name` VARCHAR , `profile_type` VARCHAR ,`preferences` VARCHAR);
                    CREATE TABLE `groups` (`account_id` VARCHAR ,`unique_url` VARCHAR, `title` VARCHAR, `participant_id` VARCHAR ,`create_date` VARCHAR,`synced` VARCHAR);
    """

private func createTable() {
      var createTableStatement: OpaquePointer?
      if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
          if sqlite3_step(createTableStatement) == SQLITE_DONE {
              print("\table's are created.")
          } else {
              print("\table's are not created.")
        }
      } else {
          print("\nCREATE TABLE statement is not prepared.")
      }

      sqlite3_finalize(createTableStatement)
    }


问:
After updated wordpress 6.1.1 the page editor is just a white screen. Suggestions on how to find what is going wrong?
This warning is logged when opening the page editor.

```<code>Warning: Trying to access array offset on value of type bool in /wordpress/plugins/full-site-editing/3.52330/help-center/class-help-center.php on line 149
</code>```

In the browser the page editor is just a white page but I see this error in the browsers console.

```<code>gutenberg.js?ver=9.2.81:2 TypeError: a._reactRootContainer.unmount is not a function
    at metaboxes.min.js?ver=3.1.20:1:37620
    at Array.forEach (<anonymous>)
    at metaboxes.min.js?ver=3.1.20:1:37376
    at Object.next (vendor.min.js?ver=3.1.20:11:22957)
    at vendor.min.js?ver=3.1.20:11:13136
    at vendor.min.js?ver=3.1.20:11:10091
    at vendor.min.js?ver=3.1.20:11:11075
    at vendor.min.js?ver=3.1.20:1:4045
    at metaboxes.min.js?ver=3.1.20:1:12005
    at vendor.min.js?ver=3.1.20:11:11764
    at core.min.js?ver=3.1.20:47:156953
    at emitter.js:14:52
    at Array.forEach (<anonymous>)
</code>```

I have tried to enter trouble shooting mode, and changing the theme. After doing either of those the page editor does work.  I am just out of ideas on what to look for in the theme that could be causing the page editor to not load.

Body:
This warning is logged when opening the page editor.

Warning: Trying to access array offset on value of type bool in /wordpress/plugins/full-site-editing/3.52330/help-center/class-help-center.php on line 149

In the browser the page editor is just a white page but I see this error in the browsers console.

gutenberg.js?ver=9.2.81:2 TypeError: a._reactRootContainer.unmount is not a function
    at metaboxes.min.js?ver=3.1.20:1:37620
    at Array.forEach (<anonymous>)
    at metaboxes.min.js?ver=3.1.20:1:37376
    at Object.next (vendor.min.js?ver=3.1.20:11:22957)
    at vendor.min.js?ver=3.1.20:11:13136
    at vendor.min.js?ver=3.1.20:11:10091
    at vendor.min.js?ver=3.1.20:11:11075
    at vendor.min.js?ver=3.1.20:1:4045
    at metaboxes.min.js?ver=3.1.20:1:12005
    at vendor.min.js?ver=3.1.20:11:11764
    at core.min.js?ver=3.1.20:47:156953
    at emitter.js:14:52
    at Array.forEach (<anonymous>)

I have tried to enter trouble shooting mode, and changing the theme. After doing either of those the page editor does work.  I am just out of ideas on what to look for in the theme that could be causing the page editor to not load.


问:
Can't read models from cloud storage, so the app can't predict images
So I deployed the app that I had made to app engine and it was successful. But for some reason when I tried the /predict API I got an error where the image cannot be predicted. I tried testing the API using postman and the output is like this.
Postman Test

Even though I have called the storage bucket that stores the model. This is the code I have made

app.py

```<code> import os
 import numpy as np
 import tensorflow as tf
 from flask import Flask, request, jsonify
 #from tensorflow import keras
 #from keras.models import load_model
 from PIL import Image
 from flask_cors import CORS

 app = Flask(__name__)
 CORS(app)

 # global variable
 model = None #model
 #db = None

 # download model file from cloud storage
 def download_model_file():
     from google.cloud import storage

     # model bucket details
     BUCKET_NAME = "spezia-bucket"
     PROJECT_ID = "capstone-spezia"
     GCS_MODEL_FILE = "spezia_model.h5"

     # initialise a client
     client = storage.Client(PROJECT_ID)

     # create a bucket object for our bucket
     bucket = client.bucket(BUCKET_NAME)

     # create a blob object from the filepath
     blob = bucket.blob(GCS_MODEL_FILE)

     #with blob.open("r") as model:
     #    print(model.read())

     folder = '/tmp/'
     if not os.path.exists(folder) :
         os.makedirs(folder)
     # download the file to a destination
     blob.download_to_filename(folder + "model_spezia.h5")

 #model = load_model('spezia_model.h5')

 @app.route('/')
 def main():
     return 'Welcome to Spezia ML Team API for predict many spices'

 @app.route('/predict', methods=['POST'])
 def recognize_image():
     try:
         # deploy model
         global model
         if not model:
             download_model_file()
             model = tf.keras.models.load_model('/tmp/model_spezia.h5')

         # open image from request
         img_sample = Image.open(request.files['image'])
         image_path = img_sample
         image_path = image_path.convert('RGB')
         image_path.close()

         # prepare image for prediction
         img = np.array(img_sample.resize((150,150)))

         x = np.expand_dims(img, axis=0)
         images = np.vstack([x])
         image_path.close()

         # predict
          prediction_array = model.predict(images)

          class_names =  ['asam jawa', 'cengkeh', 'daun jeruk', 'daun salam',
                         'jahe', 'kayu manis', 'keluak', 'kemiri', 'ketumbar',
                         'kunyit', 'lada hitam', 'pekak','serai']
         result = {
             'prediction': class_names[np.argmax(prediction_array)],
             'confidence': '{:2.0f}%'.format(100 * np.max(prediction_array))
         }

         return jsonify(isError=False, message='Success', statusCode=200, data=result), 200

      except Exception as e:
         print(str(e))
         return jsonify(message='Something went wrong'), 500

 if __name__ == '__main__':
     app.run(debug=True, port=8080)
</code>```

requirement.txt

```<code> Flask==2.2.2
 Flask-Cors==3.0.10
 tensorflow==2.11.0
 keras==2.11.0
 numpy==1.23.5
 Pillow==9.3.0
 google-cloud-storage==2.7.0
</code>```

Thanks for help and sorry for my bad English

Body:
So I deployed the app that I had made to app engine and it was successful. But for some reason when I tried the /predict API I got an error where the image cannot be predicted. I tried testing the API using postman and the output is like this.
Postman Test

Even though I have called the storage bucket that stores the model. This is the code I have made

app.py

 import os
 import numpy as np
 import tensorflow as tf
 from flask import Flask, request, jsonify
 #from tensorflow import keras
 #from keras.models import load_model
 from PIL import Image
 from flask_cors import CORS

 app = Flask(__name__)
 CORS(app)

 # global variable
 model = None #model
 #db = None

 # download model file from cloud storage
 def download_model_file():
     from google.cloud import storage

     # model bucket details
     BUCKET_NAME = "spezia-bucket"
     PROJECT_ID = "capstone-spezia"
     GCS_MODEL_FILE = "spezia_model.h5"

     # initialise a client
     client = storage.Client(PROJECT_ID)

     # create a bucket object for our bucket
     bucket = client.bucket(BUCKET_NAME)

     # create a blob object from the filepath
     blob = bucket.blob(GCS_MODEL_FILE)

     #with blob.open("r") as model:
     #    print(model.read())

     folder = '/tmp/'
     if not os.path.exists(folder) :
         os.makedirs(folder)
     # download the file to a destination
     blob.download_to_filename(folder + "model_spezia.h5")

 #model = load_model('spezia_model.h5')

 @app.route('/')
 def main():
     return 'Welcome to Spezia ML Team API for predict many spices'

 @app.route('/predict', methods=['POST'])
 def recognize_image():
     try:
         # deploy model
         global model
         if not model:
             download_model_file()
             model = tf.keras.models.load_model('/tmp/model_spezia.h5')

         # open image from request
         img_sample = Image.open(request.files['image'])
         image_path = img_sample
         image_path = image_path.convert('RGB')
         image_path.close()

         # prepare image for prediction
         img = np.array(img_sample.resize((150,150)))

         x = np.expand_dims(img, axis=0)
         images = np.vstack([x])
         image_path.close()

         # predict
          prediction_array = model.predict(images)

          class_names =  ['asam jawa', 'cengkeh', 'daun jeruk', 'daun salam',
                         'jahe', 'kayu manis', 'keluak', 'kemiri', 'ketumbar',
                         'kunyit', 'lada hitam', 'pekak','serai']
         result = {
             'prediction': class_names[np.argmax(prediction_array)],
             'confidence': '{:2.0f}%'.format(100 * np.max(prediction_array))
         }

         return jsonify(isError=False, message='Success', statusCode=200, data=result), 200

      except Exception as e:
         print(str(e))
         return jsonify(message='Something went wrong'), 500

 if __name__ == '__main__':
     app.run(debug=True, port=8080)

requirement.txt

 Flask==2.2.2
 Flask-Cors==3.0.10
 tensorflow==2.11.0
 keras==2.11.0
 numpy==1.23.5
 Pillow==9.3.0
 google-cloud-storage==2.7.0

Thanks for help and sorry for my bad English


问:
Why does substr(clob,1) make query way faster in Oracle?
```<code>create table messages {
    id number(38,0) generated by default as identity not null,
    create_timestamp timestamp(6) default current_timestamp,
    message clob
}
</code>```

This table has about 5 million rows. There are no indexes except for the primary key which is auto generated.

The 2 following queries return the same data:

```<code>select m.id,
       m.create_timestamp,
       m.message
from message m;
</code>```
```<code>select m.id,
       m.create_timestamp,
       substr(m.message,1)
from message m;
</code>```

Fetching 1000 rows gives these results:

Query 1: Execution: 2503 ms, Fetch: 37988 ms

Query 2: Execution: 255 ms, Fetch: 7 ms

How could there be such a huge discrepancy in performance if the same data is returned? Also I would expect the 2nd query to actually be a bit slower because of the extra logic.

Body:
create table messages {
    id number(38,0) generated by default as identity not null,
    create_timestamp timestamp(6) default current_timestamp,
    message clob
}

This table has about 5 million rows. There are no indexes except for the primary key which is auto generated.

The 2 following queries return the same data:

select m.id,
       m.create_timestamp,
       m.message
from message m;

select m.id,
       m.create_timestamp,
       substr(m.message,1)
from message m;

Fetching 1000 rows gives these results:

Query 1: Execution: 2503 ms, Fetch: 37988 ms

Query 2: Execution: 255 ms, Fetch: 7 ms

How could there be such a huge discrepancy in performance if the same data is returned? Also I would expect the 2nd query to actually be a bit slower because of the extra logic.


问:
Post Image to facebook wall using angular
Need to share product details with image URL to facebook wall post . I Have written the code using omg tag but it is taking only static image url how to send dynamic image URL using angular</p>


问:
How to change relative image URLs in WordPress
Here after installing a wordpress theme I have this problem. published product images are not displayed. Therefore

I would like to display the image entered by the user at the sigle page of the publication. As on the demo version of the site.
Here is my installation: http://sekou.c-l-bon.com/listing/3-bed-apartment-67-sq-m-2/
Here is the demo link: https://finder.madrasthemes.com/real-estate/listing/3-bed-apartment-67-sq-m-2/


问:
GCP- in Deployment Manager - site address Service Unavailable
why site address in deployment manager not working -

error

Service Unavailable

The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.

what could be possible cause, please guide


问:
Adding Chinook database to MySQLWorkbench
I am a new learner in SQL and I need your help.
I need to use Chinook database to my exercise and I do not know how to add, please guide me
This is my Chinook database https://www.sqlitetutorial.net/sqlite-sample-database/

Thanks!

I opened the application and tried to find where I can add the data in this app but did not succeed. I wonder I will add the data in this application or I have to add in another place. I am using Mac and not familiar enough in setting up the program.


问:
VTK axis on PYQT5
I'm building a VTK viewer on my PYQT5 application.
I'm trying to put an axes widget fixed on a corner on my screen, but when I use vtkOrientationMarkerWidget() the axes are not visible.
I can only make the axes appear on the screen when adding the vtkAxesActor() to my renderer, but they are placed in a point of my 3D object following the camera movement, and it's not what I need.
I can easily do it with PyVista instead of VTK, but since as far as I know, PyVista deosn't support LOD and my objects are huge (18000000 polygons+), I'm forced to use VTK.

#Here a part of my code;

```<code>def TRD(self):
    self.ren = vtk.vtkRenderer()
    self.vtkWidget = QVTKRenderWindowInteractor()
    self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)

    style = vtkInteractorStyleTerrain()
    self.vtkWidget.SetInteractorStyle(style)

    fileName = 'Temp/temp.png' # Load a grayscale image.
    reader = vtkTIFFReader()
    reader.SetFileName(fileName)

    DEPTH=20
    warp = vtkWarpScalar() # Create the depthmap.
    warp.SetInputConnection(reader.GetOutputPort())
    warp.SetScaleFactor(DEPTH/256)

    mapper = vtkDataSetMapper()
    mapper.SetInputConnection(warp.GetOutputPort())
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor((.9,.8,.7))
    actor.GetProperty().SetInterpolationToPBR()
    actor.GetProperty().SetMetallic(.1)
    actor.GetProperty().SetAmbient(.5)

    # Create axes
    axes = vtkAxesActor()
    colors = vtkNamedColors()
    widget = vtkOrientationMarkerWidget()
    rgba = [0] * 4
    colors.GetColor('Carrot', rgba)
    widget.SetOutlineColor(rgba[0], rgba[1], rgba[2])
    widget.SetOrientationMarker(axes)
    widget.SetInteractor(self.vtkWidget)
    widget.SetViewport(0.0, 0.0, 0.4, 0.4)
    widget.SetEnabled(1)
    widget.InteractiveOn()

    self.ren.AddActor(actor)

    self.ren.GetActiveCamera().SetViewUp(0, 0, 1)
    self.ren.GetActiveCamera().SetPosition(-99900, -21354, 131801)
    self.ren.ResetCamera()
    self.ren.GetActiveCamera().Dolly(1.2)
    self.ren.ResetCameraClippingRange()

    self.vtkWidget.Initialize()
    self.setCentralWidget(self.vtkWidget)
</code>```

Title: VTK axis on PYQT5

Body:
I'm building a VTK viewer on my PYQT5 application.
I'm trying to put an axes widget fixed on a corner on my screen, but when I use vtkOrientationMarkerWidget() the axes are not visible.
I can only make the axes appear on the screen when adding the vtkAxesActor() to my renderer, but they are placed in a point of my 3D object following the camera movement, and it's not what I need.
I can easily do it with PyVista instead of VTK, but since as far as I know, PyVista deosn't support LOD and my objects are huge (18000000 polygons+), I'm forced to use VTK.

#Here a part of my code;

def TRD(self):
    self.ren = vtk.vtkRenderer()
    self.vtkWidget = QVTKRenderWindowInteractor()
    self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)

    style = vtkInteractorStyleTerrain()
    self.vtkWidget.SetInteractorStyle(style)

    fileName = 'Temp/temp.png' # Load a grayscale image.
    reader = vtkTIFFReader()
    reader.SetFileName(fileName)

    DEPTH=20
    warp = vtkWarpScalar() # Create the depthmap.
    warp.SetInputConnection(reader.GetOutputPort())
    warp.SetScaleFactor(DEPTH/256)

    mapper = vtkDataSetMapper()
    mapper.SetInputConnection(warp.GetOutputPort())
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor((.9,.8,.7))
    actor.GetProperty().SetInterpolationToPBR()
    actor.GetProperty().SetMetallic(.1)
    actor.GetProperty().SetAmbient(.5)

    # Create axes
    axes = vtkAxesActor()
    colors = vtkNamedColors()
    widget = vtkOrientationMarkerWidget()
    rgba = [0] * 4
    colors.GetColor('Carrot', rgba)
    widget.SetOutlineColor(rgba[0], rgba[1], rgba[2])
    widget.SetOrientationMarker(axes)
    widget.SetInteractor(self.vtkWidget)
    widget.SetViewport(0.0, 0.0, 0.4, 0.4)
    widget.SetEnabled(1)
    widget.InteractiveOn()

    self.ren.AddActor(actor)

    self.ren.GetActiveCamera().SetViewUp(0, 0, 1)
    self.ren.GetActiveCamera().SetPosition(-99900, -21354, 131801)
    self.ren.ResetCamera()
    self.ren.GetActiveCamera().Dolly(1.2)
    self.ren.ResetCameraClippingRange()

    self.vtkWidget.Initialize()
    self.setCentralWidget(self.vtkWidget)


问:
Efficient way to clear 300k rows
I have a worksheet that has over 300k+ rows. I want to clear everything but the first row and column, but I also want to preserve the formatting. The script im working on seems to do the job on sheets fewer rows but always freezes when I try it with the 300k sheet. Is there any way to optimize this?

```<code>function clearsheet() {

       var ss = SpreadsheetApp.getActiveSpreadsheet();
       var sheet = ss.getSheetByName('Sheet1');

       // initial values
       var newLastColumn = dataSheet.getLastColumn();
       var newLastRow = dataSheet.getLastRow();
       var dataToProcess = dataSheet.getRange(2, 2, newLastRow, newLastColumn).getValues().filter(function(row) {
           return row[0]
       }).sort();
       var dLen = dataToProcess.length;

       var row = 2;

       // Clear intiial sheet
       for (var i = 0; i < dLen; ++i) {

           var orderNumber = dataToProcess[i][0].toString();
           var rdd = dataToProcess[i][1].toString();
           var submittedBy = dataToProcess[i][2].toString();
           var submittedOn = dataToProcess[i][3].toString();
           if (orderNumber && rdd && submittedBy && submittedOn) {
               dataSheet.getRange(row, 2, 1, newLastColumn).clear();
               row++;
           } else {
               row++; // Go to the next row
               continue;
           }
       }
   }
</code>```

tried clear by range but freezes as well

Title: Efficient way to clear 300k rows

Body:
I have a worksheet that has over 300k+ rows. I want to clear everything but the first row and column, but I also want to preserve the formatting. The script im working on seems to do the job on sheets fewer rows but always freezes when I try it with the 300k sheet. Is there any way to optimize this?

function clearsheet() {

       var ss = SpreadsheetApp.getActiveSpreadsheet();
       var sheet = ss.getSheetByName('Sheet1');

       // initial values
       var newLastColumn = dataSheet.getLastColumn();
       var newLastRow = dataSheet.getLastRow();
       var dataToProcess = dataSheet.getRange(2, 2, newLastRow, newLastColumn).getValues().filter(function(row) {
           return row[0]
       }).sort();
       var dLen = dataToProcess.length;

       var row = 2;

       // Clear intiial sheet
       for (var i = 0; i < dLen; ++i) {

           var orderNumber = dataToProcess[i][0].toString();
           var rdd = dataToProcess[i][1].toString();
           var submittedBy = dataToProcess[i][2].toString();
           var submittedOn = dataToProcess[i][3].toString();
           if (orderNumber && rdd && submittedBy && submittedOn) {
               dataSheet.getRange(row, 2, 1, newLastColumn).clear();
               row++;
           } else {
               row++; // Go to the next row
               continue;
           }
       }
   }

tried clear by range but freezes as well


问:
POST HTTP Login Request That Returns Crossbrowser Cookies
I am using #PostMan to complete a Post HTTP request to a website which returns the following cookies:

Cookie1:Value1 (Domain = MainDomain.com)

Cookie2:Value2 (Domain = Subdomain.MainDomain.com)

Cookie3:Value3 (Domain = Subdomain.MainDomain.com)

The above scenario returns the required Cookies that I need via PostMan; however, when I try this HTTP request via Make.com with the HTTP Module, I am only able to receive back the single cookie request.

I did notice that when reviewing the login within Google Chrome the request header includes:

Referrer Policy: strict-origin-when-cross-origin

The following HTTP modules are available within make as seen HERE. I picked the first HTTP request module, and these are the settings allowed within the HTTP Module BASIC, BASIC Continued and ADVANCED.

I am copying over everything required by PostMan to complete the HTTP Request that returns all of the cookies that I need. I am only able to receive the Cookie Titled RichDesk. I have tried so many possible senarios from POST to GET with set-cookie. And nothing seems to suffice to get the additional cookies to show up! I believe the following article touches some of the issues that I am facing.

I could really use someomes help on this as my end goal is to accomplish the following:

The site does not have an API, so I want to use an HTTP request to login as if I was on the site without using automation.

I will then send a request to create a note for a specific client as I have recorded the HTTP request via Postman and it works amazingly.

However, the issue is if the cookie expires, I will need to resend a login request. While the login request works fine, it simply does not return the additional Cookies that I must have to create the note as outlined in step 2 properly.


问:
Gams/mgcv: Interpretation of diagnostic criteria for random effect smooths?
Specifically, I have questions about the concurvity, estimated degrees of freedom, and significance of terms. Concurvity is the one that I'm most worried about, because it's actually really high.

Basically I'm using mgcv, building various GAMMs that have a very simple random effect structure (just one intercept effect with one variable, no factor smooths), so I'm using re splines. This way of implementing random effects provides me with quite a few spline diagnostics that seem like they don't make sense, and clearly need to be interpreted with care.

I understand what these diagnostics mean in standard splines, to some extent, but I'm having trouble propagating over my (limited) understanding of the connection between random effect coefficients and smoothing parameters.


问:
VSCode extensions are not able to find certain file in order to run
At startup, the GitHub Copilot Extension is unable to start because it can't find

```<code>/home/####/.vscode-server/bin/somebignumber/out/vs/workbench/workbench.desktop.main.js
</code>```

When I go to check what that file contains, it doesn't actually exist!
I want to use a certain extension to change my VSCode background which relies on this file as well, but it's unable to work. GitHub Copilot also doesn't work. Clicking on activate Copilot button doesn't do anything.

What does this file contain and what do I do to fix it?

Using WSL2 Ubuntu 20.04 btw.

Body:
At startup, the GitHub Copilot Extension is unable to start because it can't find

/home/####/.vscode-server/bin/somebignumber/out/vs/workbench/workbench.desktop.main.js

When I go to check what that file contains, it doesn't actually exist!
I want to use a certain extension to change my VSCode background which relies on this file as well, but it's unable to work. GitHub Copilot also doesn't work. Clicking on activate Copilot button doesn't do anything.

What does this file contain and what do I do to fix it?

Using WSL2 Ubuntu 20.04 btw.


问:
OpenGL Mesh class doesn't draw anything
I'm learning how to code graphics with OpenGL. So far I have created IndexBuffer, VertexBuffer, VertexArray, Camera, Texture and Shader. Now I'm trying to make a Mesh class with vertices, indices and textures. But when I call the "Draw(Shader& shader, Camera& camera)" function it doesn't show anything. All the vertices, indices and textures are passed in correctly (I've already checked this).

Here is my code for Mesh class

```<code>#pragma once

#include <vector>

#include"VAO.h"
#include"EBO.h"
#include"Camera.h"
#include"Texture.h"

class Mesh
{
public:
    Mesh(std::vector <Vertex>& vertices, std::vector <GLuint>& indices, std::vector <Texture>& textures);
    void Draw(Shader& shader, Camera& camera);
private:
    std::vector <Vertex> m_Vertices;
    std::vector <unsigned int> m_Indices;
    std::vector <Texture> m_Textures;
    VAO VAO;
};

---------------------------------------------

#include "Mesh.h"

#include <iostream>

Mesh::Mesh(std::vector<Vertex>& vertices, std::vector<GLuint>& indices, std::vector<Texture>& textures)
    : m_Vertices(vertices), m_Indices(indices), m_Textures(textures)
{
    VAO.Bind();
    // Generates Vertex Buffer Object and links it to vertices
    VBO VBO(vertices);
    // Generates Element Buffer Object and links it to indices
    EBO EBO(indices);
    // Links VBO attributes such as coordinates and colors to VAO
    VAO.LinkAttrib(VBO, 0, 3, GL_FLOAT, false, sizeof(Vertex), (void*)0);
    VAO.LinkAttrib(VBO, 1, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(3 * sizeof(float)));
    VAO.LinkAttrib(VBO, 2, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(6 * sizeof(float)));
    VAO.LinkAttrib(VBO, 3, 2, GL_FLOAT, false, sizeof(Vertex), (void*)(9 * sizeof(float)));
    // Unbind all to prevent accidentally modifying them
    VAO.Unbind();
    VBO.Unbind();
    EBO.Unbind();
}

void Mesh::Draw(Shader& shader, Camera& camera)
{
    // Bind shader to be able to access uniforms
    shader.Use();
    VAO.Bind();

    // Keep track of how many of each type of textures we have
    unsigned int numDiffuse = 0;
    unsigned int numSpecular = 0;

    for (unsigned int i = 0; i < m_Textures.size(); i++)
    {
        std::string num;
        std::string type = m_Textures[i].GetType();
        if (type == "diffuse")
        {
            num = std::to_string(numDiffuse++);
        }
        else if (type == "specular")
        {
            num = std::to_string(numSpecular++);
        }
        m_Textures[i].SetUniform(shader, (type + num).c_str(), i);
        m_Textures[i].Bind();
    }
    // Take care of the camera Matrix
    shader.SetUniform3f("camPos", camera.GetCameraPosition().x, camera.GetCameraPosition().y, camera.GetCameraPosition().z);
    camera.SetMatrix(shader, "camMatrix");

    // Draw the actual mesh
    glDrawElements(GL_TRIANGLES, m_Indices.size(), GL_UNSIGNED_INT, 0);
}
</code>```

My texture class:

```<code>#pragma once
#include <string>
#include "Shader.h"

class Texture
{
public:
    Texture(const std::string& filepath, const std::string& texType, unsigned int slot, unsigned int format, unsigned int pixelType);
    ~Texture();

    void SetUniform(const Shader& shader, const std::string& name, unsigned int unit) const;

    void Bind() const;
    void Unbind() const;

    inline unsigned int GetID() const { return m_ID; }
    inline std::string GetType() const { return m_Type; }
private:
    unsigned int m_ID;
    std::string m_Type;
    unsigned int m_Unit;
};

</code>```
```<code>#include "Texture.h"
#include <GL/glew.h>
#include "stb_image.h"

Texture::Texture(const std::string& filepath, const std::string& texType, unsigned int slot, unsigned int format, unsigned int pixelType)
    : m_Type(texType), m_Unit(slot)
{
    // Stores the width, height, and the number of color channels of the image
    int widthImg, heightImg, numColCh;
    // Flips the image so it appears right side up
    stbi_set_flip_vertically_on_load(true);
    // Reads the image from a file and stores it in bytes
    unsigned char* bytes = stbi_load(filepath.c_str(), &widthImg, &heightImg, &numColCh, 0);

    // Generates an OpenGL texture object
    glGenTextures(1, &m_ID);
    // Assigns the texture to a Texture Unit
    glActiveTexture(GL_TEXTURE0 + slot);
    glBindTexture(GL_TEXTURE_2D, m_ID);

    // Configures the type of algorithm that is used to make the image smaller or bigger
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // Configures the way the texture repeats (if it does at all)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    // Assigns the image to the OpenGL Texture object
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, format, pixelType, bytes);
    // Generates MipMaps
    glGenerateMipmap(GL_TEXTURE_2D);

    // Deletes the image data as it is already in the OpenGL Texture object
    stbi_image_free(bytes);

    // Unbinds the OpenGL Texture object so that it can't accidentally be modified
    glBindTexture(GL_TEXTURE_2D, 0);

}

Texture::~Texture()
{
    glDeleteTextures(1, &m_ID);
}

void Texture::SetUniform(const Shader& shader, const std::string& name, unsigned int unit) const
{
    shader.Use();
    shader.SetUniform1i(name, unit);
}

void Texture::Bind() const
{
    glActiveTexture(GL_TEXTURE0 + m_Unit);
    glBindTexture(GL_TEXTURE_2D, m_ID);
}

void Texture::Unbind() const
{
    glBindTexture(GL_TEXTURE_2D, 0);
}
</code>```

And, finally, my shader code

```<code>#pragma once

#include <string>
#include <glm/glm.hpp>

std::string readFileContents(const std::string& filepath);

class Shader
{
public:
    Shader(const std::string& vertexPath, const std::string& fragmentPath);
    ~Shader();

    void SetUniform1f(const std::string& name, float v0) const;
    void SetUniform2f(const std::string& name, float v0, float v1) const;
    void SetUniform3f(const std::string& name, float v0, float v1, float v2) const;
    void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) const;

    void SetUniform1i(const std::string& name, int v0) const;

    void SetUniformMatrix4f(const std::string& name, const glm::mat4& v0) const;

    void Use() const;

    inline unsigned int GetID() const { return m_ID; }
private:
    unsigned int m_ID;
};

#include "Shader.h"

#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>

#include <fstream>
#include <sstream>
#include <iostream>

#include <vector>

std::string readFileContents(const std::string& filepath)
{
    std::string contents;
    std::ifstream in(filepath, std::ios::binary);
    if (in)
    {
        std::stringstream sstr;
        sstr << in.rdbuf();
        contents = sstr.str();
        in.close();
    }
    return contents;
}

static unsigned int CompileShader(const std::string& shaderPath, unsigned int shaderType)
{
    unsigned int shader = glCreateShader(shaderType);
    std::string shaderCode = readFileContents(shaderPath);
    const char* shaderSource = shaderCode.c_str();
    glShaderSource(shader, 1, &shaderSource, NULL);
    glCompileShader(shader);

    int result;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int infoLogLength;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
        std::vector<char> errorMessage((long long)infoLogLength + 1);
        glGetShaderInfoLog(shader, infoLogLength, NULL, errorMessage.data());
        std::cout << errorMessage.data() << std::endl;
    }
    return shader;
}

Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath)
{
    unsigned int vertexShader = CompileShader(vertexPath, GL_VERTEX_SHADER);
    unsigned int fragmentShader = CompileShader(fragmentPath, GL_FRAGMENT_SHADER);
    m_ID = glCreateProgram();
    glAttachShader(m_ID, vertexShader);
    glAttachShader(m_ID, fragmentShader);
    glLinkProgram(m_ID);

    int result;
    glGetProgramiv(m_ID, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int infoLogLength;
        glGetProgramiv(m_ID, GL_INFO_LOG_LENGTH, &infoLogLength);
        std::vector<char> errorMessage((long long)infoLogLength + 1);
        glGetProgramInfoLog(m_ID, infoLogLength, NULL, errorMessage.data());
        std::cout << errorMessage.data() << std::endl;
    }

    glDetachShader(m_ID, vertexShader);
    glDetachShader(m_ID, fragmentShader);

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
}

Shader::~Shader()
{
    glDeleteProgram(m_ID);
}

void Shader::SetUniform1f(const std::string& name, float v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform1f(location, v0);
}

void Shader::SetUniform2f(const std::string& name, float v0, float v1) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform2f(location, v0, v1);
}

void Shader::SetUniform3f(const std::string& name, float v0, float v1, float v2) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform3f(location, v0, v1, v2);
}

void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform4f(location, v0, v1, v2, v3);

}

void Shader::SetUniform1i(const std::string& name, int v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform1i(location, v0);
}

void Shader::SetUniformMatrix4f(const std::string& name, const glm::mat4& v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(v0));

}

void Shader::Use() const
{
    glUseProgram(m_ID);
}
</code>```

ALso, every "Bind()" function is like "glBindX(ENUM, m_ID);" and every "Unbind()" is like "glBindX(ENUM, 0);"

Title: OpenGL Mesh class doesn't draw anything

Body:
I'm learning how to code graphics with OpenGL. So far I have created IndexBuffer, VertexBuffer, VertexArray, Camera, Texture and Shader. Now I'm trying to make a Mesh class with vertices, indices and textures. But when I call the "Draw(Shader& shader, Camera& camera)" function it doesn't show anything. All the vertices, indices and textures are passed in correctly (I've already checked this).

Here is my code for Mesh class

#pragma once

#include <vector>

#include"VAO.h"
#include"EBO.h"
#include"Camera.h"
#include"Texture.h"

class Mesh
{
public:
    Mesh(std::vector <Vertex>& vertices, std::vector <GLuint>& indices, std::vector <Texture>& textures);
    void Draw(Shader& shader, Camera& camera);
private:
    std::vector <Vertex> m_Vertices;
    std::vector <unsigned int> m_Indices;
    std::vector <Texture> m_Textures;
    VAO VAO;
};

---------------------------------------------

#include "Mesh.h"

#include <iostream>

Mesh::Mesh(std::vector<Vertex>& vertices, std::vector<GLuint>& indices, std::vector<Texture>& textures)
    : m_Vertices(vertices), m_Indices(indices), m_Textures(textures)
{
    VAO.Bind();
    // Generates Vertex Buffer Object and links it to vertices
    VBO VBO(vertices);
    // Generates Element Buffer Object and links it to indices
    EBO EBO(indices);
    // Links VBO attributes such as coordinates and colors to VAO
    VAO.LinkAttrib(VBO, 0, 3, GL_FLOAT, false, sizeof(Vertex), (void*)0);
    VAO.LinkAttrib(VBO, 1, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(3 * sizeof(float)));
    VAO.LinkAttrib(VBO, 2, 3, GL_FLOAT, false, sizeof(Vertex), (void*)(6 * sizeof(float)));
    VAO.LinkAttrib(VBO, 3, 2, GL_FLOAT, false, sizeof(Vertex), (void*)(9 * sizeof(float)));
    // Unbind all to prevent accidentally modifying them
    VAO.Unbind();
    VBO.Unbind();
    EBO.Unbind();
}

void Mesh::Draw(Shader& shader, Camera& camera)
{
    // Bind shader to be able to access uniforms
    shader.Use();
    VAO.Bind();

    // Keep track of how many of each type of textures we have
    unsigned int numDiffuse = 0;
    unsigned int numSpecular = 0;

    for (unsigned int i = 0; i < m_Textures.size(); i++)
    {
        std::string num;
        std::string type = m_Textures[i].GetType();
        if (type == "diffuse")
        {
            num = std::to_string(numDiffuse++);
        }
        else if (type == "specular")
        {
            num = std::to_string(numSpecular++);
        }
        m_Textures[i].SetUniform(shader, (type + num).c_str(), i);
        m_Textures[i].Bind();
    }
    // Take care of the camera Matrix
    shader.SetUniform3f("camPos", camera.GetCameraPosition().x, camera.GetCameraPosition().y, camera.GetCameraPosition().z);
    camera.SetMatrix(shader, "camMatrix");

    // Draw the actual mesh
    glDrawElements(GL_TRIANGLES, m_Indices.size(), GL_UNSIGNED_INT, 0);
}

My texture class:

#pragma once
#include <string>
#include "Shader.h"

class Texture
{
public:
    Texture(const std::string& filepath, const std::string& texType, unsigned int slot, unsigned int format, unsigned int pixelType);
    ~Texture();

    void SetUniform(const Shader& shader, const std::string& name, unsigned int unit) const;

    void Bind() const;
    void Unbind() const;

    inline unsigned int GetID() const { return m_ID; }
    inline std::string GetType() const { return m_Type; }
private:
    unsigned int m_ID;
    std::string m_Type;
    unsigned int m_Unit;
};

#include "Texture.h"
#include <GL/glew.h>
#include "stb_image.h"

Texture::Texture(const std::string& filepath, const std::string& texType, unsigned int slot, unsigned int format, unsigned int pixelType)
    : m_Type(texType), m_Unit(slot)
{
    // Stores the width, height, and the number of color channels of the image
    int widthImg, heightImg, numColCh;
    // Flips the image so it appears right side up
    stbi_set_flip_vertically_on_load(true);
    // Reads the image from a file and stores it in bytes
    unsigned char* bytes = stbi_load(filepath.c_str(), &widthImg, &heightImg, &numColCh, 0);

    // Generates an OpenGL texture object
    glGenTextures(1, &m_ID);
    // Assigns the texture to a Texture Unit
    glActiveTexture(GL_TEXTURE0 + slot);
    glBindTexture(GL_TEXTURE_2D, m_ID);

    // Configures the type of algorithm that is used to make the image smaller or bigger
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // Configures the way the texture repeats (if it does at all)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    // Assigns the image to the OpenGL Texture object
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, widthImg, heightImg, 0, format, pixelType, bytes);
    // Generates MipMaps
    glGenerateMipmap(GL_TEXTURE_2D);

    // Deletes the image data as it is already in the OpenGL Texture object
    stbi_image_free(bytes);

    // Unbinds the OpenGL Texture object so that it can't accidentally be modified
    glBindTexture(GL_TEXTURE_2D, 0);

}

Texture::~Texture()
{
    glDeleteTextures(1, &m_ID);
}

void Texture::SetUniform(const Shader& shader, const std::string& name, unsigned int unit) const
{
    shader.Use();
    shader.SetUniform1i(name, unit);
}

void Texture::Bind() const
{
    glActiveTexture(GL_TEXTURE0 + m_Unit);
    glBindTexture(GL_TEXTURE_2D, m_ID);
}

void Texture::Unbind() const
{
    glBindTexture(GL_TEXTURE_2D, 0);
}

And, finally, my shader code

#pragma once

#include <string>
#include <glm/glm.hpp>

std::string readFileContents(const std::string& filepath);

class Shader
{
public:
    Shader(const std::string& vertexPath, const std::string& fragmentPath);
    ~Shader();

    void SetUniform1f(const std::string& name, float v0) const;
    void SetUniform2f(const std::string& name, float v0, float v1) const;
    void SetUniform3f(const std::string& name, float v0, float v1, float v2) const;
    void SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) const;

    void SetUniform1i(const std::string& name, int v0) const;

    void SetUniformMatrix4f(const std::string& name, const glm::mat4& v0) const;

    void Use() const;

    inline unsigned int GetID() const { return m_ID; }
private:
    unsigned int m_ID;
};

#include "Shader.h"

#include <GL/glew.h>
#include <glm/gtc/type_ptr.hpp>

#include <fstream>
#include <sstream>
#include <iostream>

#include <vector>

std::string readFileContents(const std::string& filepath)
{
    std::string contents;
    std::ifstream in(filepath, std::ios::binary);
    if (in)
    {
        std::stringstream sstr;
        sstr << in.rdbuf();
        contents = sstr.str();
        in.close();
    }
    return contents;
}

static unsigned int CompileShader(const std::string& shaderPath, unsigned int shaderType)
{
    unsigned int shader = glCreateShader(shaderType);
    std::string shaderCode = readFileContents(shaderPath);
    const char* shaderSource = shaderCode.c_str();
    glShaderSource(shader, 1, &shaderSource, NULL);
    glCompileShader(shader);

    int result;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int infoLogLength;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
        std::vector<char> errorMessage((long long)infoLogLength + 1);
        glGetShaderInfoLog(shader, infoLogLength, NULL, errorMessage.data());
        std::cout << errorMessage.data() << std::endl;
    }
    return shader;
}

Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath)
{
    unsigned int vertexShader = CompileShader(vertexPath, GL_VERTEX_SHADER);
    unsigned int fragmentShader = CompileShader(fragmentPath, GL_FRAGMENT_SHADER);
    m_ID = glCreateProgram();
    glAttachShader(m_ID, vertexShader);
    glAttachShader(m_ID, fragmentShader);
    glLinkProgram(m_ID);

    int result;
    glGetProgramiv(m_ID, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        int infoLogLength;
        glGetProgramiv(m_ID, GL_INFO_LOG_LENGTH, &infoLogLength);
        std::vector<char> errorMessage((long long)infoLogLength + 1);
        glGetProgramInfoLog(m_ID, infoLogLength, NULL, errorMessage.data());
        std::cout << errorMessage.data() << std::endl;
    }

    glDetachShader(m_ID, vertexShader);
    glDetachShader(m_ID, fragmentShader);

    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
}

Shader::~Shader()
{
    glDeleteProgram(m_ID);
}

void Shader::SetUniform1f(const std::string& name, float v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform1f(location, v0);
}

void Shader::SetUniform2f(const std::string& name, float v0, float v1) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform2f(location, v0, v1);
}

void Shader::SetUniform3f(const std::string& name, float v0, float v1, float v2) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform3f(location, v0, v1, v2);
}

void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform4f(location, v0, v1, v2, v3);

}

void Shader::SetUniform1i(const std::string& name, int v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniform1i(location, v0);
}

void Shader::SetUniformMatrix4f(const std::string& name, const glm::mat4& v0) const
{
    unsigned int location = glGetUniformLocation(m_ID, name.c_str());
    glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(v0));

}

void Shader::Use() const
{
    glUseProgram(m_ID);
}

ALso, every "Bind()" function is like "glBindX(ENUM, m_ID);" and every "Unbind()" is like "glBindX(ENUM, 0);"


问:
How can I debug my emulated programs with GDB?
I wrote a simple fake processor emulator (dcpu-16). I would like to know if it's possible (and how) to integrate my target into gdb such that I could debug the programs compiled and executed in that emulator.

It seems like it would be related to the gdb "target" or maybe "target exec" commands although I didn't manage to understand how to make it work.

Any help would be appreciated :) Thanks!


问:
CopyFromRecordset returns only 1 record even though multiple records are present in SQL SSAS cube
I want to connect to SQL SSAS Cube and import some records. Problem is that excel is importing only first row. In SQL SSAS there is much more rows and I don't know what to do, can somebody help me?
I think that problem is with point 3)

My code:

```<code>Sub OLAP_Connect()
    Dim Cn As ADODB.Connection
    Dim rs As New ADODB.Recordset

    Dim rowCount As Long

    Set Cn = New ADODB.Connection
Dim intMaxCol As Integer
Dim intMaxRow As Integer

'1) connection

    Cn.ConnectionString = "Provider=MSOLAP; Data Source=CZSTRDWHSQL01;  Initial Catalog=CPI_SSAS;"

'2) Query SQL
        Row_1 = "[Company].[Company].[Company]"
        Row_2 = "[Account].[Account Code].[Account Code]"
        Row_3 = "[Account].[Account Full Name].[Account Full Name]"
        Col_1 = "[Measures].[Turnover Accounting Currency]"

    SQL = " select " & _
        " non empty (" & Col_1 & ") on Columns, " & _
        " non empty (" & Row_1 & ", " & Row_2 & ", " & Row_3 & ") on Rows " & _
        " from [cpi dwh]" & _
        " where ([Company].[Company Code]. & [P004],[Company].[Company CountryCode].&[POL],[Transaction Date].[Month Number].&[1],[Transaction Date].[Year].&[2022])"

'3) connection to OLAP and import date
    Cn.Open

        Set rs = New ADODB.Recordset
        rs.ActiveConnection = Cn
        rs.Source = SQL
        rs.CursorType = ADODB.CursorTypeEnum.adOpenKeyset

        rs.Open SQL, Cn

        Range("A4").CopyFromRecordset rs

        rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
'add name of columns to excel
    Cells(1, 1) = Row_1
    Cells(1, 2) = Row_2
    Cells(1, 3) = Row_3
    Cells(1, 4) = Col_1
End Sub
</code>```

I made some changes in code (from forums) but all of them gives me same result only 1 row...

Body:
I want to connect to SQL SSAS Cube and import some records. Problem is that excel is importing only first row. In SQL SSAS there is much more rows and I don't know what to do, can somebody help me?
I think that problem is with point 3)

My code:

Sub OLAP_Connect()
    Dim Cn As ADODB.Connection
    Dim rs As New ADODB.Recordset

    Dim rowCount As Long

    Set Cn = New ADODB.Connection
Dim intMaxCol As Integer
Dim intMaxRow As Integer

'1) connection

    Cn.ConnectionString = "Provider=MSOLAP; Data Source=CZSTRDWHSQL01;  Initial Catalog=CPI_SSAS;"

'2) Query SQL
        Row_1 = "[Company].[Company].[Company]"
        Row_2 = "[Account].[Account Code].[Account Code]"
        Row_3 = "[Account].[Account Full Name].[Account Full Name]"
        Col_1 = "[Measures].[Turnover Accounting Currency]"

    SQL = " select " & _
        " non empty (" & Col_1 & ") on Columns, " & _
        " non empty (" & Row_1 & ", " & Row_2 & ", " & Row_3 & ") on Rows " & _
        " from [cpi dwh]" & _
        " where ([Company].[Company Code]. & [P004],[Company].[Company CountryCode].&[POL],[Transaction Date].[Month Number].&[1],[Transaction Date].[Year].&[2022])"

'3) connection to OLAP and import date
    Cn.Open

        Set rs = New ADODB.Recordset
        rs.ActiveConnection = Cn
        rs.Source = SQL
        rs.CursorType = ADODB.CursorTypeEnum.adOpenKeyset

        rs.Open SQL, Cn

        Range("A4").CopyFromRecordset rs

        rs.Close
    Set rs = Nothing
    Cn.Close
    Set Cn = Nothing
'add name of columns to excel
    Cells(1, 1) = Row_1
    Cells(1, 2) = Row_2
    Cells(1, 3) = Row_3
    Cells(1, 4) = Col_1
End Sub

I made some changes in code (from forums) but all of them gives me same result only 1 row...


问:
Why is App Check Admin SDK rejecting debug tokens?
I am using App Check with my Flutter Android debug App to validate my app with my Cloud Run Node API. I followed the steps required to get and add the debug token to the Firebase Console Admin UI but it is rejecting my requests.
Here is my backend code:

const authenticate = async (req, res, next) => {
    const appCheckToken = req.header('X-Firebase-AppCheck');
    if (!appCheckToken) {
        res.status(401);
        return next('Unauthorized');
    }
    try {
        const appCheckClaims = await firebaseAdmin.appCheck().verifyToken(appCheckToken);

        // If verifyToken() succeeds, continue with the next middleware
        // function in the stack.
        return next();
    } catch (err) {
        res.status(401);
        return next('Unauthorized');
    }
}
```
<p>And my main method in Flutter:</p>
<pre class="lang-dart prettyprint-override"><code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  await FirebaseAppCheck.instance.activate(
    webRecaptchaSiteKey: 'recaptcha-v3-site-key',
    // Default provider for Android is the Play Integrity provider. You can use the "AndroidProvider" enum to choose
    // your preferred provider. Choose from:
    // 1. debug provider
    // 2. safety net provider
    // 3. play integrity provider
    androidProvider: AndroidProvider.debug,
  );
  runApp(const MyApp());
}
</code>```

Body:
I am using App Check with my Flutter Android debug App to validate my app with my Cloud Run Node API. I followed the steps required to get and add the debug token to the Firebase Console Admin UI but it is rejecting my requests.
Here is my backend code:

const authenticate = async (req, res, next) => {
    const appCheckToken = req.header('X-Firebase-AppCheck');
    if (!appCheckToken) {
        res.status(401);
        return next('Unauthorized');
    }
    try {
        const appCheckClaims = await firebaseAdmin.appCheck().verifyToken(appCheckToken);

        // If verifyToken() succeeds, continue with the next middleware
        // function in the stack.
        return next();
    } catch (err) {
        res.status(401);
        return next('Unauthorized');
    }
}

And my main method in Flutter:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  await FirebaseAppCheck.instance.activate(
    webRecaptchaSiteKey: 'recaptcha-v3-site-key',
    // Default provider for Android is the Play Integrity provider. You can use the "AndroidProvider" enum to choose
    // your preferred provider. Choose from:
    // 1. debug provider
    // 2. safety net provider
    // 3. play integrity provider
    androidProvider: AndroidProvider.debug,
  );
  runApp(const MyApp());
}


问:
I am making a voice assistant in python and I need a code or maybe a module for a wake up system
I am using the speech_recognition module for taking voice commands. The problem is that I want a system like Alexa and Google voice assistant has. When we say "Alexa" or "Ok Google" they wake up and start listening. I have the listening function but not the wake up system.

```<code>def takeCommand():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Listening...")
        r.pause_threshold = 1
        audio =r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language="en-in")
        print(f"Recognized Command: {query}")

    except Exception as e:
        print(e)
        print("I didn't recognize what you said please repeat")
        return "None"

    return query
</code>```

This is the code of the listening function, please help me with this. I need a program that respond to a particular wake up word and then executes this takeCommand() function.

Please don't advise things like this:

```<code>if takeCommand().lower() == "hey jarvis":
    print("Yes?")
    takeCommand()
</code>```

Because here in speech_recognition, it waits for some time for the person to speak up and then goes to recognition state, for example, This assistant is working in the background and I am reading some articles on the web. This program is in a loop of going in a "listening" state and "recognition" state even if I am not saying anything. Imagine I said "hey jarvis" but this program was in a "recognition" state at that time, so it will not listen to me.

Body:
I am using the speech_recognition module for taking voice commands. The problem is that I want a system like Alexa and Google voice assistant has. When we say "Alexa" or "Ok Google" they wake up and start listening. I have the listening function but not the wake up system.

def takeCommand():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Listening...")
        r.pause_threshold = 1
        audio =r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language="en-in")
        print(f"Recognized Command: {query}")

    except Exception as e:
        print(e)
        print("I didn't recognize what you said please repeat")
        return "None"

    return query

This is the code of the listening function, please help me with this. I need a program that respond to a particular wake up word and then executes this takeCommand() function.

Please don't advise things like this:

if takeCommand().lower() == "hey jarvis":
    print("Yes?")
    takeCommand()

Because here in speech_recognition, it waits for some time for the person to speak up and then goes to recognition state, for example, This assistant is working in the background and I am reading some articles on the web. This program is in a loop of going in a "listening" state and "recognition" state even if I am not saying anything. Imagine I said "hey jarvis" but this program was in a "recognition" state at that time, so it will not listen to me.


问:
How to cast LoadLibraryA in the Rust windows crate into LPTHREAD_START_ROUTINE?
I am trying to convert the DLL Injection code in this article from C++ to Rust, using the windows crate.

I had little trouble up until the CreateRemoteThread function.

```<code>HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);
</code>```

In my Rust code, I cannot cast LoadLibraryA function to LP_THREAD_START_ROUTINE like in the C++ code, due to the mismatch in LoadLibraryA function signature to LP_THREAD_START_ROUTINE  type.

```<code>let remote_thread = CreateRemoteThread(
    injected_process,
    None,
    0,
    LoadLibraryA as LPTHREAD_START_ROUTINE,
    Some(allocate_mem),
    0,
    None,
).unwrap_or_else(|error| {
    panic!("CreateRemoteThread error \n {:?}", error);
});
</code>```
```<code>non-primitive cast: `unsafe fn(_) -> Result<HINSTANCE, windows::core::Error> {LoadLibraryA::<_>}` as `Option<unsafe extern "system" fn(*mut c_void) -> u32>`
an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
</code>```

I have tried to create a wrapper function around LoadLibraryA but that crashed the program when compiled and run.

```<code>unsafe extern "system" fn load_library_wrapper (allocate_mem: *mut c_void) -> u32 {
    LoadLibraryA(allocate_mem);
    0
}
</code>```

Body:
I am trying to convert the DLL Injection code in this article from C++ to Rust, using the windows crate.

I had little trouble up until the CreateRemoteThread function.

HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);

In my Rust code, I cannot cast LoadLibraryA function to LP_THREAD_START_ROUTINE like in the C++ code, due to the mismatch in LoadLibraryA function signature to LP_THREAD_START_ROUTINE  type.

let remote_thread = CreateRemoteThread(
    injected_process,
    None,
    0,
    LoadLibraryA as LPTHREAD_START_ROUTINE,
    Some(allocate_mem),
    0,
    None,
).unwrap_or_else(|error| {
    panic!("CreateRemoteThread error \n {:?}", error);
});

non-primitive cast: `unsafe fn(_) -> Result<HINSTANCE, windows::core::Error> {LoadLibraryA::<_>}` as `Option<unsafe extern "system" fn(*mut c_void) -> u32>`
an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object

I have tried to create a wrapper function around LoadLibraryA but that crashed the program when compiled and run.

unsafe extern "system" fn load_library_wrapper (allocate_mem: *mut c_void) -> u32 {
    LoadLibraryA(allocate_mem);
    0
}


问:
Why these strings don't concatanate and print?
I'm new to C++ and was learning about string concepts and was just experimenting around.
I have the following code:

```<code>int main(){

    string s1="loc";
    string s2="al var";

    cout<<s1.append(s2)<<endl<<s1<<endl<<s1+s2;
}
</code>```

Running it in Vs-code I get the output as:

local var
local var
local var
```

What I don't understand is I append s1 with s2 and it prints as "local var".
Then I print s1 and get the output "local var" meaning s1 is updated successfully.
But when I print s1+s2 I don't know why it still gives the same output as s1 and s2 isn't being concatenated with s1 in the output.
I was expecting answer as "local varal var.
I want to know about how and why is this happening.

Thanks!

Body:
I'm new to C++ and was learning about string concepts and was just experimenting around.
I have the following code:

int main(){

    string s1="loc";
    string s2="al var";

    cout<<s1.append(s2)<<endl<<s1<<endl<<s1+s2;
}

Running it in Vs-code I get the output as:

local var
local var
local var

What I don't understand is I append s1 with s2 and it prints as "local var".
Then I print s1 and get the output "local var" meaning s1 is updated successfully.
But when I print s1+s2 I don't know why it still gives the same output as s1 and s2 isn't being concatenated with s1 in the output.
I was expecting answer as "local varal var.
I want to know about how and why is this happening.

Thanks!


问:
Is there a way to make a capsule/ovoid shape with cannon using three JS with React?
The player of my 3d game using threeJS with react (R3F) cannon, fiber is currently a sphere. This is because i want it to slide with no friction, and the geometric shapes that has sides/vertexes dont.

The thing i wanted to achieve is to have the same no-friction movement but making the useSphere object (or any that i can use with cannon) taller. But as it is a sphere is completely rounded so that i can only increase radious and i only want to make it taller not wider.

Any solution to this problem is welcome as my game is first person camera so i dont even show the player just want the correct physics with cannon library.

Ive seen that three js includes geometries like capsules: https://threejs.org/docs/#api/en/geometries/CapsuleGeometry

That i feel might work if i had the chance to use it with cannon but i dont know how to. I simply want a no edge shape that is taller than a ball, like a ball but larger. I think there might be a way to make a custom shape but i sincerely havent found anything.

Thanks in advance for your help, would be really nice to me.


问:
Broadcast a column to all rows using Trigger Function on Update
I have a table:

uid
history
updatedAt

a
someOlderJson
2022-12-31:23:59:59

b
someNewerJson
2023-01-01:00:00:30

And I would like to update the table to the below state when the history column is updated to someNewestJson:

uid
history
updatedAt

a
someNewestJson
2023-01-02:00:00:30

b
someNewestJson
2023-01-02:00:00:30

Is there a way to do this in postgresql?

P/S: I only have access to the DB and would like the update to be automatically perform anytime the column is updated.


问:
Interaction has already been acknowledged although I compared it to other codes
so I was trying to make a slash command for kicking users on discord but for some reason there seems to be a mistake somewhere, it alwas says DiscordAPIError[40060]: Interaction has already been acknowledged

Code [Please ignore the german sentences]:

```<code>const { SlashCommandBuilder } = require('@discordjs/builders');
const { EmbedBuilder, PermissionsBitField } = require('discord.js');
const { execute } = require("./clear");

module.exports = {
    data: new SlashCommandBuilder()
    .setName('kick')
    .setDescription('Dieser Command wird ein Mitglied des Servers von diesem kicken')
    .addUserOption(option => option.setName('target').setDescription('Welches Mitglied möchtest du vom Server kicken?').setRequired(true))
    .addStringOption(option => option.setName('reason').setDescription('Grund:')),
    async execute (interaction, client) {

        const kickUser = interaction.options.getUser('target');
        const kickMember = await interaction.guild.members.fetch(kickUser.id);
        const channel = interaction.channel;

        if (!interaction.member.permissions.has(PermissionsBitField.Flags.KickMembers)) return await interaction.reply({ content: "Du kannst das Mitglied aufgrund deiner fehlenden Rechte nicht nutzen", ephemeral: true});
        if (!kickMember) return await interaction.reply({ content: 'Der ausgewählte Nutzer ist nicht mehr auf dem Server!', ephemeral: true});
        if (!kickMember.kickable) return await interaction.reply({ content: "Dieses Mitglied kann nicht von mir gekickt werden, da dieser über mir steht", ephemeral: true});

        let reason = interaction.options.getString('reason');
        if (!reason) reason = "Kein Grund angegeben.";

        const dmEmbed = new EmbedBuilder()
        .setColor('Aqua')
        .setDescription(`:white_check_mark: Du wurdest von Otaku Haven gekickt | ${reason}`)

        const embed = new EmbedBuilder()
        .setColor('Aqua')
        .setDescription(`:white_check_mark: ${kickUser.tag} wurde vom Server **gekickt** | ${reason}`)

        await kickMember.send({ embeds: [dmEmbed] }).catch(err => {
            return;
        });

        await kickMember.kick({ reason: reason}).catch(err => {
             interaction.reply({ content: "Es gab einen Fehler", ephemeral: true});
        });

        await interaction.reply({ embeds: [embed] });

    }
}

</code>```

I expected the code to work because I compared it to another example code to make sure that there is no mistake!

Body:
so I was trying to make a slash command for kicking users on discord but for some reason there seems to be a mistake somewhere, it alwas says DiscordAPIError[40060]: Interaction has already been acknowledged

Code [Please ignore the german sentences]:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { EmbedBuilder, PermissionsBitField } = require('discord.js');
const { execute } = require("./clear");

module.exports = {
    data: new SlashCommandBuilder()
    .setName('kick')
    .setDescription('Dieser Command wird ein Mitglied des Servers von diesem kicken')
    .addUserOption(option => option.setName('target').setDescription('Welches Mitglied möchtest du vom Server kicken?').setRequired(true))
    .addStringOption(option => option.setName('reason').setDescription('Grund:')),
    async execute (interaction, client) {

        const kickUser = interaction.options.getUser('target');
        const kickMember = await interaction.guild.members.fetch(kickUser.id);
        const channel = interaction.channel;

        if (!interaction.member.permissions.has(PermissionsBitField.Flags.KickMembers)) return await interaction.reply({ content: "Du kannst das Mitglied aufgrund deiner fehlenden Rechte nicht nutzen", ephemeral: true});
        if (!kickMember) return await interaction.reply({ content: 'Der ausgewählte Nutzer ist nicht mehr auf dem Server!', ephemeral: true});
        if (!kickMember.kickable) return await interaction.reply({ content: "Dieses Mitglied kann nicht von mir gekickt werden, da dieser über mir steht", ephemeral: true});

        let reason = interaction.options.getString('reason');
        if (!reason) reason = "Kein Grund angegeben.";

        const dmEmbed = new EmbedBuilder()
        .setColor('Aqua')
        .setDescription(`:white_check_mark: Du wurdest von Otaku Haven gekickt | ${reason}`)

        const embed = new EmbedBuilder()
        .setColor('Aqua')
        .setDescription(`:white_check_mark: ${kickUser.tag} wurde vom Server **gekickt** | ${reason}`)

        await kickMember.send({ embeds: [dmEmbed] }).catch(err => {
            return;
        });

        await kickMember.kick({ reason: reason}).catch(err => {
             interaction.reply({ content: "Es gab einen Fehler", ephemeral: true});
        });

        await interaction.reply({ embeds: [embed] });

    }
}

I expected the code to work because I compared it to another example code to make sure that there is no mistake!


问:
Lines not being pushed into github
I started learning git yesterday, please bear with me.
I am trying to "push" code from Visual Studio Code into Github. The commit is happening, and the file is showing up in my repository, but they are just empty (the code i typed in VS Code is not showing up in Github).

I created a repository on Github, copied the https code and cloned it onto my desktop (local), and opened it in terminal with [<xyzaddressofrepositry> code .], which opens up VSCode.

I then created a doc, and edited it (my repository name is PersonalWeb). Now I have this:

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>PersonalWeb</h1>
    <p>Lorem Lorem1</p>
    <p>Lorem Lorem2</p>
    <p>Lorem Lorem3</p>
</body>
</html>
</code>```

Then i opened terminal (In VSCode) and put in these:

```<code>git status #ensure it is in main branch
git add .
git commit -m initialcommit
git push origin main
</code>```

It pushes into my github repository on my website, but the lines (as pasted above from doc) dont come up (photo attached).

Title: Lines not being pushed into github

Body:
I started learning git yesterday, please bear with me.
I am trying to "push" code from Visual Studio Code into Github. The commit is happening, and the file is showing up in my repository, but they are just empty (the code i typed in VS Code is not showing up in Github).

I created a repository on Github, copied the https code and cloned it onto my desktop (local), and opened it in terminal with [<xyzaddressofrepositry> code .], which opens up VSCode.

I then created a doc, and edited it (my repository name is PersonalWeb). Now I have this:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

PersonalWeb

Lorem Lorem1

Lorem Lorem2

Lorem Lorem3

Then i opened terminal (In VSCode) and put in these:

git status #ensure it is in main branch
git add .
git commit -m initialcommit
git push origin main

It pushes into my github repository on my website, but the lines (as pasted above from doc) dont come up (photo attached).


问:
How to pass object to client using Websockets? (use object class from js file in html script)
In my index.js I have a class

```<code>class Digit() {
//construct

add() {
//do whatever
}
}

</code>```

and

```<code>let C = new Digit();
</code>```

I pass this to the client using

```<code>WS.send(JSON.stringify(C))
</code>```

which is recieved/interpreted in index.html. This all works perfectly and the issue is not with this proccess.

However when I try to use C.add(), I get the TypeError: function add does not exist. In my eyes either the error is that there is no 'context' for the class and thus the methods cannot be accessed, there is some namespace error, or JSON.stringify cannot properly send objects of custom classes. So how do I fix this error?

Body:
In my index.js I have a class

class Digit() {
//construct

add() {
//do whatever
}
}

and

let C = new Digit();

I pass this to the client using

WS.send(JSON.stringify(C))

which is recieved/interpreted in index.html. This all works perfectly and the issue is not with this proccess.

However when I try to use C.add(), I get the TypeError: function add does not exist. In my eyes either the error is that there is no 'context' for the class and thus the methods cannot be accessed, there is some namespace error, or JSON.stringify cannot properly send objects of custom classes. So how do I fix this error?


问:
What is the correct way to configure ASGI application for channels in Django?
I've just started to learn about channels and asgi in django
in few tutorials that i've seen they do this to configure the asgi apllication

asgi.py

```<code>import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

application = ProtocolTypeRouter({
    'http':get_asgi_application(),
})

</code>```

settings.py

```<code>INSTALLED_APPS = [
    'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'chat'
]

ASGI_APPLICATION = 'config.asgi.application'

</code>```

to check when i run my server it was supposed to be running on asgi/channel server like this

```<code>Starting ASGI/Channels version development server at http://127.0.0.1:8000/
</code>```

but mine is still running on the default one

```<code>Starting development server at http://127.0.0.1:8000/
</code>```

when i use daphne and put inside installed apps instead of channels

```<code>    'daphne',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'chat'
]

</code>```

it works fine

```<code>Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
</code>```

can someone tell me what is going on here?and how exactly django works with asgi?

Body:
I've just started to learn about channels and asgi in django
in few tutorials that i've seen they do this to configure the asgi apllication

asgi.py

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')

application = ProtocolTypeRouter({
    'http':get_asgi_application(),
})

settings.py

INSTALLED_APPS = [
    'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'chat'
]

ASGI_APPLICATION = 'config.asgi.application'

to check when i run my server it was supposed to be running on asgi/channel server like this

Starting ASGI/Channels version development server at http://127.0.0.1:8000/

but mine is still running on the default one

Starting development server at http://127.0.0.1:8000/

when i use daphne and put inside installed apps instead of channels

    'daphne',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'chat'
]

it works fine

Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/

can someone tell me what is going on here?and how exactly django works with asgi?


问:
Android IME, use custom layout instead of Keyboard and support KeyboardView's setKeyboard and setOnKeyboardActionListener listeners
I'm creating a custom keyboard in android but in android to create a custom keyboard we need to pass the keyboard XML to generate the keyboard view(XML code below). I want to design my own keyboard using layouts that should like to support the KeyboardView's setKeyboard() and setOnKeyboardActionListener(), How can I do that?  Thanks in Advance

```<code>@Override
    public View onCreateInputView() {

        KeyboardView keyboardView=(KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view,null);

        Keyboard keyboard=new Keyboard(this,R.xml.numberpad);
        keyboardView.setKeyboard(keyboard);
        keyboardView.setOnKeyboardActionListener(this);

        return keyboardView;
}
</code>```

current XML numberpad

```<code><?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="2dp"
    android:verticalGap="2dp"
    android:keyHeight="55dp"
    android:keyTextColor="@color/design_default_color_primary"
    android:keyBackground="@drawable/ic_baseline_keyboard_24">
    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5"/>
        <Key android:codes="54" android:keyLabel="6"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0"/>
    </Row>

</Keyboard>
</code>```

Body:
I'm creating a custom keyboard in android but in android to create a custom keyboard we need to pass the keyboard XML to generate the keyboard view(XML code below). I want to design my own keyboard using layouts that should like to support the KeyboardView's setKeyboard() and setOnKeyboardActionListener(), How can I do that?  Thanks in Advance

@Override
    public View onCreateInputView() {

        KeyboardView keyboardView=(KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view,null);

        Keyboard keyboard=new Keyboard(this,R.xml.numberpad);
        keyboardView.setKeyboard(keyboard);
        keyboardView.setOnKeyboardActionListener(this);

        return keyboardView;
}

current XML numberpad

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="10%p"
    android:horizontalGap="2dp"
    android:verticalGap="2dp"
    android:keyHeight="55dp"
    android:keyTextColor="@color/design_default_color_primary"
    android:keyBackground="@drawable/ic_baseline_keyboard_24">
    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5"/>
        <Key android:codes="54" android:keyLabel="6"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0"/>
    </Row>

</Keyboard>


问:
ANSYS Fluent: Blower flow through an oven
I am creating an 2D transient simulation environment in Ansis Fluent for a industrial oven, where a blower have to create air and hit flow inside the oven through a heat exchanger. I can create a pressure inlet and pressure outlet back to back for creating a similar environment, but that was not fulfill the conditions.Continuous air reheating is needed. The oven geometry created in ansys fluent

How can I define the blower so that it can take the oven heat exchanger air as inlet and flow it inside the oven by adding pressure or velocity maintaining the inlet temperature?