问:
What does an SQL_NULL_DATA return from SQLPrimaryKey mean?
I'm trying to get the name of the Primary Key column from a table in an Access database. I followed the example in the SQLForeignKeys documentation, but I can't seem to make it work.

I have:

```<code>        // Check if we have an old style Documents table with a primary key (which we don't want)
        AFX_SQL_SYNC(::SQLAllocStmt(m_pDatabase->m_hdbc, &hstmt));
        if (m_pDatabase->CheckHstmt(nRetCode, hstmt))
        {
            char szTable[] = _T("Documents");   // Table to display

            UCHAR szPkTable[TAB_LEN];       // Primary key table name
            UCHAR szFkTable[TAB_LEN];       // Foreign key table name
            UCHAR szPkCol[COL_LEN];         // Primary key column
            UCHAR szFkCol[COL_LEN];         // Foreign key column

            SQLINTEGER cbPkTable, cbPkCol, cbFkTable, cbFkCol, cbKeySeq;
            SQLSMALLINT iKeySeq;
            SQLRETURN retcode;

            // Bind the columns that describe the primary and foreign keys.
            // Ignore the table schema, name, and catalog for this example.
            SQLBindCol(hstmt, 3, SQL_C_CHAR, szPkTable, TAB_LEN, &cbPkTable);
            SQLBindCol(hstmt, 4, SQL_C_CHAR, szPkCol, COL_LEN, &cbPkCol);
            SQLBindCol(hstmt, 5, SQL_C_SSHORT, &iKeySeq, TAB_LEN, &cbKeySeq);
            SQLBindCol(hstmt, 7, SQL_C_CHAR, szFkTable, TAB_LEN, &cbFkTable);
            SQLBindCol(hstmt, 8, SQL_C_CHAR, szFkCol, COL_LEN, &cbFkCol);

            // Get the names of the columns in the primary key.
            retcode = SQLPrimaryKeys(hstmt, NULL, 0, NULL, 0, (SQLCHAR*)szTable, SQL_NTS);

            while ((retcode == SQL_SUCCESS) || (retcode == SQL_SUCCESS_WITH_INFO))
            {
                // Fetch and display the result set. This will be a list of the columns in the primary key of the ORDERS table.
                retcode = SQLFetch(hstmt);
                if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
                {
                    CString sMsg;
                    sMsg.Format(_T("Table: %s Column: %s Key Seq: %hd \n"), szPkTable, szPkCol, iKeySeq);
                }
            }
        }
        // Close the cursor (the hstmt is still allocated).
        SQLFreeStmt(hstmt, SQL_CLOSE);
        SQLFreeStmt(hstmt, SQL_UNBIND);
        SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
</code>```

But my call to SQLPrimaryKeys always returns SQL_NULL_DATA (-1) - but I don't know what that means? Any ideas what I may have done wrong? (Or easier ways to do this?)

Cheers!

Body:
I'm trying to get the name of the Primary Key column from a table in an Access database. I followed the example in the SQLForeignKeys documentation, but I can't seem to make it work.

I have:

        // Check if we have an old style Documents table with a primary key (which we don't want)
        AFX_SQL_SYNC(::SQLAllocStmt(m_pDatabase->m_hdbc, &hstmt));
        if (m_pDatabase->CheckHstmt(nRetCode, hstmt))
        {
            char szTable[] = _T("Documents");   // Table to display

            UCHAR szPkTable[TAB_LEN];       // Primary key table name
            UCHAR szFkTable[TAB_LEN];       // Foreign key table name
            UCHAR szPkCol[COL_LEN];         // Primary key column
            UCHAR szFkCol[COL_LEN];         // Foreign key column

            SQLINTEGER cbPkTable, cbPkCol, cbFkTable, cbFkCol, cbKeySeq;
            SQLSMALLINT iKeySeq;
            SQLRETURN retcode;

            // Bind the columns that describe the primary and foreign keys.
            // Ignore the table schema, name, and catalog for this example.
            SQLBindCol(hstmt, 3, SQL_C_CHAR, szPkTable, TAB_LEN, &cbPkTable);
            SQLBindCol(hstmt, 4, SQL_C_CHAR, szPkCol, COL_LEN, &cbPkCol);
            SQLBindCol(hstmt, 5, SQL_C_SSHORT, &iKeySeq, TAB_LEN, &cbKeySeq);
            SQLBindCol(hstmt, 7, SQL_C_CHAR, szFkTable, TAB_LEN, &cbFkTable);
            SQLBindCol(hstmt, 8, SQL_C_CHAR, szFkCol, COL_LEN, &cbFkCol);

            // Get the names of the columns in the primary key.
            retcode = SQLPrimaryKeys(hstmt, NULL, 0, NULL, 0, (SQLCHAR*)szTable, SQL_NTS);

            while ((retcode == SQL_SUCCESS) || (retcode == SQL_SUCCESS_WITH_INFO))
            {
                // Fetch and display the result set. This will be a list of the columns in the primary key of the ORDERS table.
                retcode = SQLFetch(hstmt);
                if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
                {
                    CString sMsg;
                    sMsg.Format(_T("Table: %s Column: %s Key Seq: %hd \n"), szPkTable, szPkCol, iKeySeq);
                }
            }
        }
        // Close the cursor (the hstmt is still allocated).
        SQLFreeStmt(hstmt, SQL_CLOSE);
        SQLFreeStmt(hstmt, SQL_UNBIND);
        SQLFreeStmt(hstmt, SQL_RESET_PARAMS);

But my call to SQLPrimaryKeys always returns SQL_NULL_DATA (-1) - but I don't know what that means? Any ideas what I may have done wrong? (Or easier ways to do this?)

Cheers!


来源: stackexchange

问:
Pywinauto run a script on the background
I have a certain script that i want to run on the background. I know that similar questions have been asked but i am still having a hard time achieving this.
Here is my code

```<code>import pywinauto
from pywinauto import Application
import time

app = Application().start("notepad.exe")
#app = Application().connect(title="test.txt-Σημειωματάριο")
app.window().set_focus()
app.window().minimize()
time.sleep(2)
app.window().send_keystrokes("{ENTER}")
</code>```

The above code is minmizing the notepad window but i cant see that enter was indeed pressed. Same goes for other keystrokes that i tried. What am i doing wrong?

ContentLicense: CC BY-SA 4.0

Body:
I have a certain script that i want to run on the background. I know that similar questions have been asked but i am still having a hard time achieving this.
Here is my code

import pywinauto
from pywinauto import Application
import time

app = Application().start("notepad.exe")
#app = Application().connect(title="test.txt-Σημειωματάριο")
app.window().set_focus()
app.window().minimize()
time.sleep(2)
app.window().send_keystrokes("{ENTER}")

The above code is minmizing the notepad window but i cant see that enter was indeed pressed. Same goes for other keystrokes that i tried. What am i doing wrong?


问:
How do I set cookies that say "Hello, Name" or "Welcome Back, Name" depending on if the user has logged in with details that are new or already exist?
So I am making an HTML online store for my Gr. 11 culminating and my teacher says that we need some sort of data persistence, so I chose cookies, but he also said that the data should be usable as well, in other words, he wants me to be able to save the cookies (which I have already done) and then use them (just like I said in the title).

I want it so that when a user puts in a new username and password, it says "Hello, Username!", but if they use a username and password that already has a saved cookie, I want it to say "Welcome Back, Username!"

This is the link to my code, you can run it and check all the files as well: https://replit.com/@AR719947/Comp-Sci-Culminating-1#index.html

The file that uses the cookies is the "signup.html" file

All I've done right now is look at websites and YouTube videos but nothing really seems to be helping.


问:
How to download PyYAML whl file for Linux
From PEP documentation wheel file format is as follows {distribution}-{version}{build tag}-{python tag}-{abi tag}-{platform tag}.whl

So for Windows OS we need to download whl file with platform tag win, win32, etc...

While trying to download PyYAML 5.3.1 whl file from pypi, I noticed that it does not have a platform tag for Linux. Where can I download PyYAML 5.3.1 for Linux?

EDIT : due to network contrainst, unable to download straight from pypi. Must download file from somewhere then send it to linux server.


问:
Update from api level 30 to level 31 for google play, using ionic
My ionic info
this is my ionic info

This my config.xml

I am using gradle 7.6 and java jdk 8u341
When i generate the level 30 apk it works correctly, when i generate the level 31 or 32 apk, it compiles normally, but does not open the app when installed on the device, but when running it shows the message "the application has a bug" and closes by itself. I can't open the app.

I have sdks 30, 31 and 32 installed, and sdk build-tools 28.0.3, 29.0.2 and 29.0.3 installed

To compile, I already corrected the "android:exported" in activities, services and broadcasts.

Help-me plesase!!!

I need update the level of the apk for 31 or 32, for send to google play.


问:
Homepage in ASP.NET SPA
I am developing a project from the .NET React template. I want to create a homepage that would be indexed by search engines with Razor, since React pages aren't SEO friendly.
How could I achieve this?

I tried creating a Home controller and Home view, using it as default route

```<code>app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
  name: "default",
  pattern: "{controller=home}/{action=Index}/{id?}");

//app.MapFallbackToFile("index.html");
</code>```

And adding the route in the setupProxy.js

const context =  [
  "/api",
  "/home"
];

module.exports = function(app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  });

  app.use(appProxy);
};
```

Title: Homepage in ASP.NET SPA

Body:
I am developing a project from the .NET React template. I want to create a homepage that would be indexed by search engines with Razor, since React pages aren't SEO friendly.
How could I achieve this?

I tried creating a Home controller and Home view, using it as default route

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
  name: "default",
  pattern: "{controller=home}/{action=Index}/{id?}");

//app.MapFallbackToFile("index.html");

And adding the route in the setupProxy.js

const context =  [
  "/api",
  "/home"
];

module.exports = function(app) {
  const appProxy = createProxyMiddleware(context, {
    target: target,
    secure: false,
    headers: {
      Connection: 'Keep-Alive'
    }
  });

  app.use(appProxy);
};


问:
How Do I List Wordpress Posts with ID Less Than Some Number with WP-CLI
The following WP-CLI command works great for getting all posts in a specific category, but I need to restrict it further to just those with an ID number less than a specific number. This is because I just exported a bunch of posts below a specific ID number and now need to remove them from the original site.

wp post list --cat=34 --format=ids

What must I add to the above so that the list only includes posts with ID<16163

I thought --post__in might do the trick but this only seems to list specific posts if you list their ID numbers separated by a comma. The description from Wordpress looks like it takes a range but it seems like a specific list.


问:
workaround for not being able to use natural log in constant assignment
I am trying to write a program to find the nth prime. To do this I use the limit given by the prime number theorem:

p(n) < n(ln(n) + ln(ln(n))

to calculate an upper bound for the nth prime number, use constant generics to create an array of that length and then perform a sieve of Eratosthenes to find all primes in that array. However, I have run into the issue that my current code will not compile due to the line:

const N_PRIME: i32 = 10_001;
// ceil use instead of floor to remove possibility of floating point error causing issue with bound
// 1 added to account for array indices starting from 0
const UP_TO: i32 = {let np = N_PRIME as f64; (np * (np.ln() + np.ln().ln())).ceil() as i32 + 1};
```
<p>with the error message</p>
<pre class="lang-rust prettyprint-override"><code> const UP_TO: i32 = {let np = N_PRIME as f64; (np * (np.ln() + np.ln().ln())).ceil() as i32 + 1};
  |                                                        ^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants
</code>```

naturally I could simply calculate UP_TO and hardcode it, or I could rewrite the code to use vectors. However, the former approach is more clunky and the latter would be slightly slower so a workaround would be preferable. Can anyone think of a way to get the needed value into the UP_TO constant?

Thanks

Edit: Code suggested by pigionhands (as I understand it), this code results in the same error:

const N_PRIME: i32 = 10_001;

fn up_to<const N_PRIME: i32>() -> usize {
    let np = N_PRIME as f64;
    (np * (np.ln() + np.ln().ln())).ceil() as usize + 1
}

fn main() {
    println!("{}", UP_TO);
    let test_arr = [0; up_to::<N_PRIME>()];
}
```

Body:
I am trying to write a program to find the nth prime. To do this I use the limit given by the prime number theorem:

p(n) < n(ln(n) + ln(ln(n))

to calculate an upper bound for the nth prime number, use constant generics to create an array of that length and then perform a sieve of Eratosthenes to find all primes in that array. However, I have run into the issue that my current code will not compile due to the line:

const N_PRIME: i32 = 10_001;
// ceil use instead of floor to remove possibility of floating point error causing issue with bound
// 1 added to account for array indices starting from 0
const UP_TO: i32 = {let np = N_PRIME as f64; (np * (np.ln() + np.ln().ln())).ceil() as i32 + 1};

with the error message

 const UP_TO: i32 = {let np = N_PRIME as f64; (np * (np.ln() + np.ln().ln())).ceil() as i32 + 1};
  |                                                        ^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants

naturally I could simply calculate UP_TO and hardcode it, or I could rewrite the code to use vectors. However, the former approach is more clunky and the latter would be slightly slower so a workaround would be preferable. Can anyone think of a way to get the needed value into the UP_TO constant?

Thanks

Edit: Code suggested by pigionhands (as I understand it), this code results in the same error:

const N_PRIME: i32 = 10_001;

fn up_to<const N_PRIME: i32>() -> usize {
    let np = N_PRIME as f64;
    (np * (np.ln() + np.ln().ln())).ceil() as usize + 1
}

fn main() {
    println!("{}", UP_TO);
    let test_arr = [0; up_to::<N_PRIME>()];
}


问:
how do i make my foreign key the actual ID instead of it being NULL?
I'm creating two tables and I would like to use UserID in User_info_table as a foreign key in the Trail_info_table, but it keeps showing as NULL.

```<code>CREATE TABLE CW2.User_info_table
(
    UserID int IDENTITY PRIMARY KEY,
    User_name varchar(255),
    Email_Address varchar(255) NOT NULL,
    User_password varchar(255) NOT NULL,
    User_access_level int NOT NULL,
);

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Grace Hopper', 'grace@plymouth.ac.uk', 'ISAD123!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Tim Berners-Lee', 'tim@plymouth.ac.uk', 'COMP2001!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Ada Lovelace', 'ada@plymouth.ac.uk', 'insecurePassword', 1)

CREATE TABLE CW2.Trail_info_table
(
    TrailID int IDENTITY,
    Trail_name char(255) NOT NULL,
    Trail_owner varchar(255),
    Trail_owner_ID int
        FOREIGN KEY REFERENCES CW2.User_info_table(UserID),
    Trail_difficulty int NOT NULL,
    Trail_length int NOT NULL,

    CONSTRAINT Trail_primary PRIMARY KEY (TrailID),
);

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Spring Sprint', 'Grace Hopper', 1, 10)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Summer Stroll', 'Tim Berners-Lee', 2, 15)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Winter Waltz', 'Ada Lovelace', 3, 20)
</code>```

I tried to get the UserID (1,2,3) in the Trail_owner_ID column as a foreign key but it keeps showing up as NULL

Body:
I'm creating two tables and I would like to use UserID in User_info_table as a foreign key in the Trail_info_table, but it keeps showing as NULL.

CREATE TABLE CW2.User_info_table
(
    UserID int IDENTITY PRIMARY KEY,
    User_name varchar(255),
    Email_Address varchar(255) NOT NULL,
    User_password varchar(255) NOT NULL,
    User_access_level int NOT NULL,
);

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Grace Hopper', 'grace@plymouth.ac.uk', 'ISAD123!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Tim Berners-Lee', 'tim@plymouth.ac.uk', 'COMP2001!', 1)

INSERT INTO CW2.User_info_table (User_name, Email_Address, User_password, User_access_level)
VALUES ('Ada Lovelace', 'ada@plymouth.ac.uk', 'insecurePassword', 1)

CREATE TABLE CW2.Trail_info_table
(
    TrailID int IDENTITY,
    Trail_name char(255) NOT NULL,
    Trail_owner varchar(255),
    Trail_owner_ID int
        FOREIGN KEY REFERENCES CW2.User_info_table(UserID),
    Trail_difficulty int NOT NULL,
    Trail_length int NOT NULL,

    CONSTRAINT Trail_primary PRIMARY KEY (TrailID),
);

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Spring Sprint', 'Grace Hopper', 1, 10)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Summer Stroll', 'Tim Berners-Lee', 2, 15)

INSERT INTO CW2.Trail_info_table (Trail_name, Trail_owner, Trail_difficulty, Trail_length)
VALUES ('Winter Waltz', 'Ada Lovelace', 3, 20)

I tried to get the UserID (1,2,3) in the Trail_owner_ID column as a foreign key but it keeps showing up as NULL


问:
How to import JS file as a module?
I am working on three projects(server, tv client and mobile client). They communicate through a web socket using message types. It's essential that message types should be consistent across the three projects. I've already setup git to manage the three projects within 1 root folder.

```<code>projectA // server project
projectB // tv client project
projectC // mobile react client project
shared-files <--- this is where i'd like to place any shared files ( in this case my message type constants )
</code>```

At the moment i am stuck with importing outside assets to my react project.
I have tried by simply specifying the path to the file but react complains about importing assets outside src.
I also realized that when i do deploy my react app, the file wont be bundled so this wont work. My next idea was something along the lines of including the .js file as project dependencies thru an install but I have no clue how to do that.  Have you done something like this yourself? any suggestions?

Title: How to import JS file as a module?

Body:
I am working on three projects(server, tv client and mobile client). They communicate through a web socket using message types. It's essential that message types should be consistent across the three projects. I've already setup git to manage the three projects within 1 root folder.

projectA // server project
projectB // tv client project
projectC // mobile react client project
shared-files <--- this is where i'd like to place any shared files ( in this case my message type constants )

At the moment i am stuck with importing outside assets to my react project.
I have tried by simply specifying the path to the file but react complains about importing assets outside src.
I also realized that when i do deploy my react app, the file wont be bundled so this wont work. My next idea was something along the lines of including the .js file as project dependencies thru an install but I have no clue how to do that.  Have you done something like this yourself? any suggestions?


问:
How to add onClosed event listener from Chrome notifications API for chrome extension in javascript?
I was wondering on how to add a listener on whenever a Chrome notification is closed. Here's my code:

```<code>chrome.notifications.onClosed.addListener(function (notifId, byUser) {
  console.log(byUser);
  console.log("notification closed");
});
</code>```

I'm simply trying to log the event for now, and I can't seem to understand why nothing logs when I close the notification. I've checked the official documentation and it seems like I'm calling it correctly.

After a certain amount of time (I think like 20-30 minutes?) it seems to finally register all the closed events at once as per this screenshot of the log, perhaps accounting for all the times I closed it?

I should also mention that the other chrome notification events work fine, that is chrome.notifications.onButtonClicked.addListener() works and so does chrome.notifications.onClicked.addListener().

The only way I can seem to "force" call the listener to execute is by calling
chrome.notifications.onClosed.dispatch(); which proves the listener works, it just isn't listening, haha.

Body:
I was wondering on how to add a listener on whenever a Chrome notification is closed. Here's my code:

chrome.notifications.onClosed.addListener(function (notifId, byUser) {
  console.log(byUser);
  console.log("notification closed");
});

I'm simply trying to log the event for now, and I can't seem to understand why nothing logs when I close the notification. I've checked the official documentation and it seems like I'm calling it correctly.

After a certain amount of time (I think like 20-30 minutes?) it seems to finally register all the closed events at once as per this screenshot of the log, perhaps accounting for all the times I closed it?

I should also mention that the other chrome notification events work fine, that is chrome.notifications.onButtonClicked.addListener() works and so does chrome.notifications.onClicked.addListener().

The only way I can seem to "force" call the listener to execute is by calling
chrome.notifications.onClosed.dispatch(); which proves the listener works, it just isn't listening, haha.


问:
How to improve the accuracy of region detection based on GPS
Imagine you have a map with multiple GPS regions next to each other, and a function that executes every 5 seconds with new GPS coordinates when it comes in:

```<code>GPSModel.observe { it =>
  // it.latitude, it.longtitude
  currentRegion = getRegionByCoordinates(it)
  if (lastRegion != currentRegion){
     doSomeThing() // region changes
  }

  lastRegion = currentRegion
}
</code>```

The problem is that, due to the fact that GPS may not always be accurate, I don't want to fire doSomeThing() when it comes in automatically. Instead I want to confirm that the incoming GPS coordinates remain in the same new region for at least 20 seconds, and only then would the doSomeThing() function execute.

How is this possible?

Body:
Imagine you have a map with multiple GPS regions next to each other, and a function that executes every 5 seconds with new GPS coordinates when it comes in:

GPSModel.observe { it =>
  // it.latitude, it.longtitude
  currentRegion = getRegionByCoordinates(it)
  if (lastRegion != currentRegion){
     doSomeThing() // region changes
  }

  lastRegion = currentRegion
}

The problem is that, due to the fact that GPS may not always be accurate, I don't want to fire doSomeThing() when it comes in automatically. Instead I want to confirm that the incoming GPS coordinates remain in the same new region for at least 20 seconds, and only then would the doSomeThing() function execute.

How is this possible?


问:
HAR file to Open API convertor
Disclaimer, I'm about a day into TypeScript right now. I've finally got everything set up in VS Code. I've imported the har-to-openapi tool. But I'm puzzled by the documentation. Under "Usage" we find:

```<code>import { generateSpec } from "har-to-openapi";
const openapi = await generateSpec(har);
const { spec, yamlSpec } = openapi;
// spec = { ... } openapi spec schema document
// yamlSpec = string, "info: ..."
</code>```

But I don't see anywhere in the docs how I would pass in the HAR file I have. Is it assumed that if I'm at this level I should know what I'm doing?

I have a hunch that I need to somehow pass the file so when I run this it will output what I need (in the current directory). Anybody use this before or are you able to provide some assistance?

Thanks.

I've read through the MDN docs, TypeScript Docs/tutorials, VS Code docs, and some of the JavaScript docs on MDN. An actual example would be helpful for me to understand the workflow.

Title: HAR file to Open API convertor

Body:
Disclaimer, I'm about a day into TypeScript right now. I've finally got everything set up in VS Code. I've imported the har-to-openapi tool. But I'm puzzled by the documentation. Under "Usage" we find:

import { generateSpec } from "har-to-openapi";
const openapi = await generateSpec(har);
const { spec, yamlSpec } = openapi;
// spec = { ... } openapi spec schema document
// yamlSpec = string, "info: ..."

But I don't see anywhere in the docs how I would pass in the HAR file I have. Is it assumed that if I'm at this level I should know what I'm doing?

I have a hunch that I need to somehow pass the file so when I run this it will output what I need (in the current directory). Anybody use this before or are you able to provide some assistance?

Thanks.

I've read through the MDN docs, TypeScript Docs/tutorials, VS Code docs, and some of the JavaScript docs on MDN. An actual example would be helpful for me to understand the workflow.


问:
How can arbitrary JS request locked mode? (Chromebook)
Google Forms can enter locked mode on managed Chromebooks to lock the user into the test. I'm trying to accomplish the same functionality - lock the managed Chromebook user into the test, preventing them from opening tabs, using bookmarks, copy/paste, etc. This is impossible by regular JavaScript, but I can guarantee that the only people who will use my website are people using managed Chromebooks.

If it exists, what JavaScript/Google API do I need to take advantage of to request the user's Chromebook to enter locked mode (and how do I use it)?


问:
Cannot resolve relative URL, without having a base path?
I am using swagger-ui-express in my nodejs server

```<code>app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDoc, options));
</code>```

and have my swagger yaml defined like

```<code>openapi: 3.0.0
info:
  version: 1.0.0
  title: API
  license:
    name: UNLICENSED
servers:
  - url: http://localhost:3000
security:
  - bearer: []
paths:
  /status:
    get:
      summary: Health check
      operationId: index
      security: [] #exclude from security check
      tags:
        - Home
      responses:
        "200":
          description: Success
          content:
            application/json:
              schema:
                type: object

  /v1/api/test:
     $ref: '../request-bodies/test/test.yaml'
</code>```

However, it's throwing error on $ref

Could not resolve reference: Tried to resolve a relative URL, without having a basePath.

What am I missing?

Body:
I am using swagger-ui-express in my nodejs server

app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDoc, options));

and have my swagger yaml defined like

openapi: 3.0.0
info:
  version: 1.0.0
  title: API
  license:
    name: UNLICENSED
servers:
  - url: http://localhost:3000
security:
  - bearer: []
paths:
  /status:
    get:
      summary: Health check
      operationId: index
      security: [] #exclude from security check
      tags:
        - Home
      responses:
        "200":
          description: Success
          content:
            application/json:
              schema:
                type: object

  /v1/api/test:
     $ref: '../request-bodies/test/test.yaml'

However, it's throwing error on $ref

Could not resolve reference: Tried to resolve a relative URL, without having a basePath.

What am I missing?


问:
Webpack build gives javascript memory heap error
I have my Webpack configuration as follows for a NodeJS project with TypeScript. When it is compiling it gives the "JavaScript memory Heap" error in the terminal. I usually increase the memory limit in the local terminal in order to do have the output build folder. But this is not the case with the server as it has some memory limitations. Can someone help me to sort out this issue either with the parallel build or any memory optimization technics.

This is my package.json.

```<code>"devDependencies": {
        "fs": "^0.0.1-security",
        "glob": "^8.0.3",
        "path": "^0.12.7",
        "ts-loader": "^9.4.1",
        "ts-node": "^10.9.1",
        "typescript": "^4.9.3",
        "webpack": "^5.75.0",
        "webpack-cli": "^5.0.0",
        "zip-webpack-plugin": "^4.0.1"
    },
    "dependencies": {
        "@types/aws-lambda": "^8.10.109",
        "@types/tedious": "^4.0.9",
        "aws-sdk": "^2.1257.0",
        "axios": "^1.2.0",
        "jsonwebtoken": "^8.5.1",
        "node-tls": "^0.10.2",
        "sequelize": "^6.28.0",
        "tedious": "^15.1.2"
    }
</code>```

as per the above dependencies I use Webpack 5.

This is the Webpack.config.js

```<code>const webpack = require('webpack');
const path = require("path");
const glob = require("glob");
const ZipPlugin = require("zip-webpack-plugin");
const tedious = require("tedious");
const TerserPlugin = require('terser-webpack-plugin');

const entries = () => {
  const src = path.resolve(__dirname, "functions");
  const files = glob.sync(src + "/**/*");
  return files
    .filter((f) => f.indexOf("index.ts") > -1)
    .map((f) => "./" + path.relative(path.resolve(__dirname), f));
};

const getBundleName = (path) =>
  path
    .substring("./functions/".length, path.lastIndexOf("/"))
    .replaceAll("/", "-")
    .toLowerCase();

const config = () => {
  let modules = [];
  const files = entries();
  files.forEach((f) => {
    console.log(f)
    const bundleName = getBundleName(f);

    const outputPath = path.resolve(
      __dirname,
      "dist/" +
        bundleName.substring(0, bundleName.lastIndexOf("-")) +
        "/" +
        bundleName.substring(bundleName.lastIndexOf("-") + 1)
    );

    const moduleConfig = {
      name: bundleName,
      entry: f,
      output: {
        path: outputPath,
        filename: "index.js",
        libraryTarget: "commonjs",
        clean: true,
      },
      module: {
        rules: [
          {
            test: /\.ts?$/,
            use: "ts-loader",
            exclude: [/node_modules/, /\.test.ts?$/],
          },
        ],
      },
      target: "node",
      plugins: [
        new ZipPlugin({
          path: "./",
          filename: `${bundleName}.zip`,
        }),
        new webpack.ids.DeterministicChunkIdsPlugin({
          maxLength: 5,
        }),
      ],
      optimization: {
        minimizer: [
          new TerserPlugin({
            parallel: true,
          }),
        ],
        chunkIds: 'named',
        concatenateModules: true,
        emitOnErrors: true,
        mangleWasmImports: true,
        moduleIds: 'deterministic',
        runtimeChunk: {
          name: 'runtime',
        },
        sideEffects: 'flag',
        usedExports: 'global',
      },
      resolve: {
        mainFields: ["main"],
        extensions: [".tsx", ".ts", ".js", ".json", "..."],
        alias: {'tedious': path.join(__dirname, './node_modules/tedious')},
      },
      resolveLoader: {
        modules: ["node_modules"],
      },
      externals: ['pg', 'sqlite3', 'tedious', 'pg-hstore'],
      /*devtool: "source-map",*/
    };

    modules.push(moduleConfig);
  });

  return modules;
};

module.exports = config();

</code>```

I am expecting to understand the issues or any improvements of my Webpack configuration for the memory optimization for the code build with this nodejs TS project.

Body:
I have my Webpack configuration as follows for a NodeJS project with TypeScript. When it is compiling it gives the "JavaScript memory Heap" error in the terminal. I usually increase the memory limit in the local terminal in order to do have the output build folder. But this is not the case with the server as it has some memory limitations. Can someone help me to sort out this issue either with the parallel build or any memory optimization technics.

This is my package.json.

"devDependencies": {
        "fs": "^0.0.1-security",
        "glob": "^8.0.3",
        "path": "^0.12.7",
        "ts-loader": "^9.4.1",
        "ts-node": "^10.9.1",
        "typescript": "^4.9.3",
        "webpack": "^5.75.0",
        "webpack-cli": "^5.0.0",
        "zip-webpack-plugin": "^4.0.1"
    },
    "dependencies": {
        "@types/aws-lambda": "^8.10.109",
        "@types/tedious": "^4.0.9",
        "aws-sdk": "^2.1257.0",
        "axios": "^1.2.0",
        "jsonwebtoken": "^8.5.1",
        "node-tls": "^0.10.2",
        "sequelize": "^6.28.0",
        "tedious": "^15.1.2"
    }

as per the above dependencies I use Webpack 5.

This is the Webpack.config.js

const webpack = require('webpack');
const path = require("path");
const glob = require("glob");
const ZipPlugin = require("zip-webpack-plugin");
const tedious = require("tedious");
const TerserPlugin = require('terser-webpack-plugin');

const entries = () => {
  const src = path.resolve(__dirname, "functions");
  const files = glob.sync(src + "/**/*");
  return files
    .filter((f) => f.indexOf("index.ts") > -1)
    .map((f) => "./" + path.relative(path.resolve(__dirname), f));
};

const getBundleName = (path) =>
  path
    .substring("./functions/".length, path.lastIndexOf("/"))
    .replaceAll("/", "-")
    .toLowerCase();

const config = () => {
  let modules = [];
  const files = entries();
  files.forEach((f) => {
    console.log(f)
    const bundleName = getBundleName(f);

    const outputPath = path.resolve(
      __dirname,
      "dist/" +
        bundleName.substring(0, bundleName.lastIndexOf("-")) +
        "/" +
        bundleName.substring(bundleName.lastIndexOf("-") + 1)
    );

    const moduleConfig = {
      name: bundleName,
      entry: f,
      output: {
        path: outputPath,
        filename: "index.js",
        libraryTarget: "commonjs",
        clean: true,
      },
      module: {
        rules: [
          {
            test: /\.ts?$/,
            use: "ts-loader",
            exclude: [/node_modules/, /\.test.ts?$/],
          },
        ],
      },
      target: "node",
      plugins: [
        new ZipPlugin({
          path: "./",
          filename: `${bundleName}.zip`,
        }),
        new webpack.ids.DeterministicChunkIdsPlugin({
          maxLength: 5,
        }),
      ],
      optimization: {
        minimizer: [
          new TerserPlugin({
            parallel: true,
          }),
        ],
        chunkIds: 'named',
        concatenateModules: true,
        emitOnErrors: true,
        mangleWasmImports: true,
        moduleIds: 'deterministic',
        runtimeChunk: {
          name: 'runtime',
        },
        sideEffects: 'flag',
        usedExports: 'global',
      },
      resolve: {
        mainFields: ["main"],
        extensions: [".tsx", ".ts", ".js", ".json", "..."],
        alias: {'tedious': path.join(__dirname, './node_modules/tedious')},
      },
      resolveLoader: {
        modules: ["node_modules"],
      },
      externals: ['pg', 'sqlite3', 'tedious', 'pg-hstore'],
      /*devtool: "source-map",*/
    };

    modules.push(moduleConfig);
  });

  return modules;
};

module.exports = config();

I am expecting to understand the issues or any improvements of my Webpack configuration for the memory optimization for the code build with this nodejs TS project.


问:
Bluetooth will not find device unless I turn bluetooth off and then back on
I am working on some bluetooth code and the bluetooth adapter will not find the device unless I turn off bluetooth and then turn it back on.  I think I might be missing a step somewhere. Thank you for your time</p>
```<code> ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(uuids[0])).build();
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
scanner.startScan(new ArrayList<ScanFilter>(Collections.singleton(filter)), new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mLeScanCallback);
</code>```

Body:
I am working on some bluetooth code and the bluetooth adapter will not find the device unless I turn off bluetooth and then turn it back on.  I think I might be missing a step somewhere. Thank you for your time

 ScanFilter filter = new ScanFilter.Builder().setServiceUuid(new ParcelUuid(uuids[0])).build();
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
scanner.startScan(new ArrayList<ScanFilter>(Collections.singleton(filter)), new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mLeScanCallback);


问:
In flutter,how do I sync actions between Flutter layer and Android navtive layer when I called Android's Telephony intent?
As title,this problem confused me a while,
first, Android "MainActivity.kt" of my flutter app that embeded a section of code, it will be given Flutter layer to call:

```<code>class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.fluttertest7sms";

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "setDefaultSms") {
                try {
                    var intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                    intent.putExtra(
                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName
                    );
                    startActivity(intent);
                    result.success(Telephony.Sms.getDefaultSmsPackage(context));
                } catch (ex: Exception) {
                    result.error("UNAVAILABLE", "Setting default sms.", null);
                }
            } else {
                result.notImplemented()
            }
        }
    }
}
</code>```

In flutter layer,the mapped call section is:

```<code>Future<dynamic> _setToDefault() async {
    dynamic result;
    try {
      result = await platform.invokeMethod('setDefaultSms');
      setState(() {
        currDefaultSmsApp = result;
      });
      print('curr: $currDefaultSmsApp');
    } on PlatformException catch (e) {
      print("Error: $e");
      result = e;
    }
    return result;
  }
</code>```

I called the function and clicked "change" to set the current app as default SMS app,
but returned unchanged package name - "",in generally, should return "com.example.fluttertest7" immediately~

Actually,the app is already default,why I do know it's been changed?Because it showed "fluttertest7" in the default SMS application of Android settings~

It seems like a synchronicition/flush problem?

Once clicked "change", the expected returned result should be "fluttertest7", not next time~

Please help if anyone knows how to solve!

Thanks a lot.

Jonas

Body:
As title,this problem confused me a while,
first, Android "MainActivity.kt" of my flutter app that embeded a section of code, it will be given Flutter layer to call:

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.example.fluttertest7sms";

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "setDefaultSms") {
                try {
                    var intent = Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
                    intent.putExtra(
                        Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName
                    );
                    startActivity(intent);
                    result.success(Telephony.Sms.getDefaultSmsPackage(context));
                } catch (ex: Exception) {
                    result.error("UNAVAILABLE", "Setting default sms.", null);
                }
            } else {
                result.notImplemented()
            }
        }
    }
}

In flutter layer,the mapped call section is:

Future<dynamic> _setToDefault() async {
    dynamic result;
    try {
      result = await platform.invokeMethod('setDefaultSms');
      setState(() {
        currDefaultSmsApp = result;
      });
      print('curr: $currDefaultSmsApp');
    } on PlatformException catch (e) {
      print("Error: $e");
      result = e;
    }
    return result;
  }

I called the function and clicked "change" to set the current app as default SMS app,
but returned unchanged package name - "",in generally, should return "com.example.fluttertest7" immediately~

Actually,the app is already default,why I do know it's been changed?Because it showed "fluttertest7" in the default SMS application of Android settings~

It seems like a synchronicition/flush problem?

Once clicked "change", the expected returned result should be "fluttertest7", not next time~

Please help if anyone knows how to solve!

Thanks a lot.

Jonas


问:
Nan Loss during training - MaskRCNN
I am training a custom Dataset sample_data where each image annotation is in the Pascal VOC XML format.
When training the MaskRCNN model from the matterport repo for TensorFlow 1.15 and the maskrcnn for Tensorflow 2.2.0

config for the matterport using tensorflow-cpu :
config

When running the model (using both versions) tensorflow-cpu, data generation is pretty fast(almost instantly) and training happens as expected with proper loss values

But when using the tensorflow-gpu,
The model loading is too long, then epochs start after another 7-10 minutes and the loss generated is nan,

I've tried to

lower the Learning rate to 1e-5,

multiprocessing off,

workers = 1,

changed optimizer to Adam,

System Specs:
i5 12400f,
12gb Ram,
12Gb RTX 3060,

all cudnn and cudatoolkit version according to tensorflow documentation installed.

Training Code :

```<code>from os import listdir
import imgaug
import numpy as np
from xml.etree import ElementTree
from numpy import zeros
from numpy import asarray
from mrcnn.utils import Dataset
from matplotlib import pyplot
from mrcnn.visualize import display_instances
from mrcnn.utils import extract_bboxes

from mrcnn.config import Config
from mrcnn.model import MaskRCNN
import mrcnn.model as mrmodel
import warnings
import tensorflow as tf
import time
warnings.filterwarnings('ignore')
# gpu_available = tf.config.list_physical_devices('GPU')
gpu_available = tf.test.is_gpu_available()
gpu_available

class CornDataset(Dataset):
    # load the dataset definitions
    def load_dataset(self, dataset_dir, is_train=True):
#         start = time.perf_counter()
        # define classes
        self.add_class("dataset", 1, "fall-armyworm-larva")
        self.add_class("dataset", 2, "fall-armyworm-larval-damage")
        self.add_class("dataset", 3, "fall-armyworm-frass")
        self.add_class("dataset", 4, "fall-armyworm-egg")
        self.add_class("dataset", 5, "healthy-maize")
        self.add_class("dataset", 6, "maize-streak-disease")

        # define data locations
        images_dir = dataset_dir + '/images/'
        annotations_dir = dataset_dir + '/annots/'

    # find all images
        count = 1
        for filename in listdir(images_dir):
            print(filename)
            # extract image id
            image_id = filename[:-4]
            name1 = ''
            if filename[-4:] != 'jpeg':
                name1 = filename[:-4]
            else:
                name1 = filename[:-5]
            image_id = name1

            # skip all images after 115 if we are building the train set
            if is_train and int(image_id) >= 6770:
                continue
            # skip all images before 115 if we are building the test/val set
            if not is_train and int(image_id) < 6770:
                continue

            img_path = images_dir + filename
            ann_path = annotations_dir + image_id + '.xml'
            # add to dataset
            self.add_image('dataset', image_id=image_id, path=img_path, annotation=ann_path, class_ids = [0,1,2,3,4,5,6])
#         stop = time.perf_counter()
#         print("time for load_dataset",(stop-start))

    # extract bounding boxes from an annotation file
    def extract_boxes(self, filename):
#         start = time.perf_counter()
        # load and parse the file
        tree = ElementTree.parse(filename)
        # get the root of the document
        root = tree.getroot()
        # extract each bounding box
        boxes = list()
        for box in root.findall('.//object'):
            name = box.find('name').text   #Add label name to the box list
            xmin = int(box.find('./bndbox/xmin').text)
            ymin = int(box.find('./bndbox/ymin').text)
            xmax = int(box.find('./bndbox/xmax').text)
            ymax = int(box.find('./bndbox/ymax').text)
            coors = [xmin, ymin, xmax, ymax, name]
            boxes.append(coors)

        # extract image dimensions
        width = int(root.find('.//size/width').text)
        height = int(root.find('.//size/height').text)
#         stop = time.perf_counter()
#         print("time for extract_boxes",(stop-start))
        return boxes, width, height

    # load the masks for an image
    def load_mask(self, image_id):
#         start = time.perf_counter()
        # get details of image
        info = self.image_info[image_id]
        # define box file location
        path = info['annotation']
        #return info, path

        # load XML
        boxes, w, h = self.extract_boxes(path)
        # create one array for all masks, each on a different channel
        masks = zeros([h, w, len(boxes)], dtype='uint8')
        # create masks
        class_ids = list()
        for i in range(len(boxes)):
            box = boxes[i]
            row_s, row_e = box[1], box[3]
            col_s, col_e = box[0], box[2]

            # box[4] will have the name of the class
            if box[4]=='fall-armyworm-larva':
                masks[row_s:row_e, col_s:col_e, i] = 1
                class_ids.append(self.class_names.index('fall-armyworm-larva'))
            elif box[4]=='fall-armyworm-larval-damage':
                masks[row_s:row_e, col_s:col_e, i] = 2
                class_ids.append(self.class_names.index('fall-armyworm-larval-damage'))
            elif box[4]=='fall-armyworm-frass':
                masks[row_s:row_e, col_s:col_e, i] = 3
                class_ids.append(self.class_names.index('fall-armyworm-frass'))
            elif box[4]=='fall-armyworm-egg':
                masks[row_s:row_e, col_s:col_e, i] = 4
                class_ids.append(self.class_names.index('fall-armyworm-egg'))
            elif box[4]=='healthy-maize' or box[4]=='healthy-maize' or box[4]=='healthy-images' or box[4]=='none-healthy':
                masks[row_s:row_e, col_s:col_e, i] = 5
                class_ids.append(self.class_names.index('healthy-maize'))
            elif box[4]=='maize-streak-disease':
                masks[row_s:row_e, col_s:col_e, i] = 6
                class_ids.append(self.class_names.index('maize-streak-disease'))

    #         stop = time.perf_counter()
#         print("time for load_mask",(stop-start))
        return masks, asarray(class_ids, dtype='int32')

    # load an image reference
    def image_reference(self, image_id):
        info = self.image_info[image_id]
        return info['path']

dataset_dir='final_dataset/'
validset_dir = 'validation/'

train_set = CornDataset()
train_set.load_dataset(dataset_dir, is_train=True)
train_set.prepare()
print('Train: %d' % len(train_set.image_ids))

# test/val set
test_set = CornDataset()
test_set.load_dataset(dataset_dir, is_train=False)
test_set.prepare()
print('Test: %d' % len(test_set.image_ids))

import random
num=random.randint(0, len(train_set.image_ids))
# define image id
image_id = num
# load the image
image = train_set.load_image(image_id)
# load the masks and the class ids
mask, class_ids = train_set.load_mask(image_id)
# extract bounding boxes from the masks
bbox = extract_bboxes(mask)
# display image with masks and bounding boxes
display_instances(image, bbox, mask, class_ids, train_set.class_names)

class CornConfig(Config):
    # define the name of the configuration
    NAME = "corn_cfg"
    # number of classes (background + 5 Diseases + 1 Healthy)
    NUM_CLASSES = 1 + 6
    IMAGES_PER_GPU = 1
    # number of training steps per epoch
    STEPS_PER_EPOCH = 100
    VALIDATION_STEPS = 50

     # Skip detections with < 90% confidence
#     DETECTION_MIN_CONFIDENCE = 0.8
    LEARNING_RATE = 1e-4
#     BATCH_SIZE = 28

    # prepare config
config = CornConfig()
config.display()

import os
ROOT_DIR = "/home/mehathab/Desktop/maskrcnn_drY-run"
# Directory to save logs and trained model
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

# define the model
model = MaskRCNN(mode='training', model_dir=DEFAULT_LOGS_DIR, config=config)
model_inference = MaskRCNN(mode="inference", config=config, model_dir=DEFAULT_LOGS_DIR)

# load weights (mscoco) and exclude the output layers
WEIGHT_PATH = 'mask_rcnn_coco.h5'
model.load_weights(WEIGHT_PATH, by_name=True,
                   exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",  "mrcnn_bbox", "mrcnn_mask"])

# train weights (output layers or 'heads')
# history = model.train(train_set, test_set, learning_rate=config.LEARNING_RATE, epochs=100, layers='3+')

mean_average_precision_callback = mrmodel.MeanAveragePrecisionCallback(model,
                                                                        model_inference,
                                                                        test_set,
                                                                        calculate_map_at_every_X_epoch=5,
                                                                        verbose=1)
model.train(train_set,test_set,
            learning_rate=config.LEARNING_RATE,
            epochs=100,
            layers='heads',
            custom_callbacks=[mean_average_precision_callback])

</code>```

Title: Nan Loss during training - MaskRCNN

Body:
I am training a custom Dataset sample_data where each image annotation is in the Pascal VOC XML format.
When training the MaskRCNN model from the matterport repo for TensorFlow 1.15 and the maskrcnn for Tensorflow 2.2.0

config for the matterport using tensorflow-cpu :
config

When running the model (using both versions) tensorflow-cpu, data generation is pretty fast(almost instantly) and training happens as expected with proper loss values

But when using the tensorflow-gpu,
The model loading is too long, then epochs start after another 7-10 minutes and the loss generated is nan,

I've tried to

lower the Learning rate to 1e-5,

multiprocessing off,

workers = 1,

changed optimizer to Adam,

System Specs:
i5 12400f,
12gb Ram,
12Gb RTX 3060,

all cudnn and cudatoolkit version according to tensorflow documentation installed.

Training Code :

from os import listdir
import imgaug
import numpy as np
from xml.etree import ElementTree
from numpy import zeros
from numpy import asarray
from mrcnn.utils import Dataset
from matplotlib import pyplot
from mrcnn.visualize import display_instances
from mrcnn.utils import extract_bboxes

from mrcnn.config import Config
from mrcnn.model import MaskRCNN
import mrcnn.model as mrmodel
import warnings
import tensorflow as tf
import time
warnings.filterwarnings('ignore')
# gpu_available = tf.config.list_physical_devices('GPU')
gpu_available = tf.test.is_gpu_available()
gpu_available

class CornDataset(Dataset):
    # load the dataset definitions
    def load_dataset(self, dataset_dir, is_train=True):
#         start = time.perf_counter()
        # define classes
        self.add_class("dataset", 1, "fall-armyworm-larva")
        self.add_class("dataset", 2, "fall-armyworm-larval-damage")
        self.add_class("dataset", 3, "fall-armyworm-frass")
        self.add_class("dataset", 4, "fall-armyworm-egg")
        self.add_class("dataset", 5, "healthy-maize")
        self.add_class("dataset", 6, "maize-streak-disease")

        # define data locations
        images_dir = dataset_dir + '/images/'
        annotations_dir = dataset_dir + '/annots/'

    # find all images
        count = 1
        for filename in listdir(images_dir):
            print(filename)
            # extract image id
            image_id = filename[:-4]
            name1 = ''
            if filename[-4:] != 'jpeg':
                name1 = filename[:-4]
            else:
                name1 = filename[:-5]
            image_id = name1

            # skip all images after 115 if we are building the train set
            if is_train and int(image_id) >= 6770:
                continue
            # skip all images before 115 if we are building the test/val set
            if not is_train and int(image_id) < 6770:
                continue

            img_path = images_dir + filename
            ann_path = annotations_dir + image_id + '.xml'
            # add to dataset
            self.add_image('dataset', image_id=image_id, path=img_path, annotation=ann_path, class_ids = [0,1,2,3,4,5,6])
#         stop = time.perf_counter()
#         print("time for load_dataset",(stop-start))

    # extract bounding boxes from an annotation file
    def extract_boxes(self, filename):
#         start = time.perf_counter()
        # load and parse the file
        tree = ElementTree.parse(filename)
        # get the root of the document
        root = tree.getroot()
        # extract each bounding box
        boxes = list()
        for box in root.findall('.//object'):
            name = box.find('name').text   #Add label name to the box list
            xmin = int(box.find('./bndbox/xmin').text)
            ymin = int(box.find('./bndbox/ymin').text)
            xmax = int(box.find('./bndbox/xmax').text)
            ymax = int(box.find('./bndbox/ymax').text)
            coors = [xmin, ymin, xmax, ymax, name]
            boxes.append(coors)

        # extract image dimensions
        width = int(root.find('.//size/width').text)
        height = int(root.find('.//size/height').text)
#         stop = time.perf_counter()
#         print("time for extract_boxes",(stop-start))
        return boxes, width, height

    # load the masks for an image
    def load_mask(self, image_id):
#         start = time.perf_counter()
        # get details of image
        info = self.image_info[image_id]
        # define box file location
        path = info['annotation']
        #return info, path

        # load XML
        boxes, w, h = self.extract_boxes(path)
        # create one array for all masks, each on a different channel
        masks = zeros([h, w, len(boxes)], dtype='uint8')
        # create masks
        class_ids = list()
        for i in range(len(boxes)):
            box = boxes[i]
            row_s, row_e = box[1], box[3]
            col_s, col_e = box[0], box[2]

            # box[4] will have the name of the class
            if box[4]=='fall-armyworm-larva':
                masks[row_s:row_e, col_s:col_e, i] = 1
                class_ids.append(self.class_names.index('fall-armyworm-larva'))
            elif box[4]=='fall-armyworm-larval-damage':
                masks[row_s:row_e, col_s:col_e, i] = 2
                class_ids.append(self.class_names.index('fall-armyworm-larval-damage'))
            elif box[4]=='fall-armyworm-frass':
                masks[row_s:row_e, col_s:col_e, i] = 3
                class_ids.append(self.class_names.index('fall-armyworm-frass'))
            elif box[4]=='fall-armyworm-egg':
                masks[row_s:row_e, col_s:col_e, i] = 4
                class_ids.append(self.class_names.index('fall-armyworm-egg'))
            elif box[4]=='healthy-maize' or box[4]=='healthy-maize' or box[4]=='healthy-images' or box[4]=='none-healthy':
                masks[row_s:row_e, col_s:col_e, i] = 5
                class_ids.append(self.class_names.index('healthy-maize'))
            elif box[4]=='maize-streak-disease':
                masks[row_s:row_e, col_s:col_e, i] = 6
                class_ids.append(self.class_names.index('maize-streak-disease'))

    #         stop = time.perf_counter()
#         print("time for load_mask",(stop-start))
        return masks, asarray(class_ids, dtype='int32')

    # load an image reference
    def image_reference(self, image_id):
        info = self.image_info[image_id]
        return info['path']

dataset_dir='final_dataset/'
validset_dir = 'validation/'

train_set = CornDataset()
train_set.load_dataset(dataset_dir, is_train=True)
train_set.prepare()
print('Train: %d' % len(train_set.image_ids))

# test/val set
test_set = CornDataset()
test_set.load_dataset(dataset_dir, is_train=False)
test_set.prepare()
print('Test: %d' % len(test_set.image_ids))

import random
num=random.randint(0, len(train_set.image_ids))
# define image id
image_id = num
# load the image
image = train_set.load_image(image_id)
# load the masks and the class ids
mask, class_ids = train_set.load_mask(image_id)
# extract bounding boxes from the masks
bbox = extract_bboxes(mask)
# display image with masks and bounding boxes
display_instances(image, bbox, mask, class_ids, train_set.class_names)

class CornConfig(Config):
    # define the name of the configuration
    NAME = "corn_cfg"
    # number of classes (background + 5 Diseases + 1 Healthy)
    NUM_CLASSES = 1 + 6
    IMAGES_PER_GPU = 1
    # number of training steps per epoch
    STEPS_PER_EPOCH = 100
    VALIDATION_STEPS = 50

     # Skip detections with < 90% confidence
#     DETECTION_MIN_CONFIDENCE = 0.8
    LEARNING_RATE = 1e-4
#     BATCH_SIZE = 28

    # prepare config
config = CornConfig()
config.display()

import os
ROOT_DIR = "/home/mehathab/Desktop/maskrcnn_drY-run"
# Directory to save logs and trained model
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

# define the model
model = MaskRCNN(mode='training', model_dir=DEFAULT_LOGS_DIR, config=config)
model_inference = MaskRCNN(mode="inference", config=config, model_dir=DEFAULT_LOGS_DIR)

# load weights (mscoco) and exclude the output layers
WEIGHT_PATH = 'mask_rcnn_coco.h5'
model.load_weights(WEIGHT_PATH, by_name=True,
                   exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",  "mrcnn_bbox", "mrcnn_mask"])

# train weights (output layers or 'heads')
# history = model.train(train_set, test_set, learning_rate=config.LEARNING_RATE, epochs=100, layers='3+')

mean_average_precision_callback = mrmodel.MeanAveragePrecisionCallback(model,
                                                                        model_inference,
                                                                        test_set,
                                                                        calculate_map_at_every_X_epoch=5,
                                                                        verbose=1)
model.train(train_set,test_set,
            learning_rate=config.LEARNING_RATE,
            epochs=100,
            layers='heads',
            custom_callbacks=[mean_average_precision_callback])


问:
How to find unused menu items with Application Insights
I am suspecting some menu items of my desktop software are not used, and would use Application Insights for that.

Bad idea: Creating event with Key:"menu" and property "copy" or other item is easy to create and plot in Azure portal and but creates too much noise but also duplicates.

Better idea is to build a list of items that are used throughout the session and at the program closing submit everything once as a list of items that are used.

```<code>//for each menu use
Telem.IncrementKey(menuItemText);

internal static void IncrementKey(string key)
{
    menuDict.TryGetValue(key, out count);
    count++;
    menuDict.AddOrUpdate(key, count, (k, v) => count);
}

//on closing program
foreach (var entry in menuDict)
{
    menuDictToSend.TryAdd(entry.Key, entry.value);
}
Telemetry.TrackEvent("MenuInteractionsUsed", menuDictToSend);
</code>```

Another way would be to create key "menu" and comma separate all used menu interactions, but how do I plot those in Azure Portal to figure out the usage?

Is there a better way to submit the data that would be possible to analyze? It is not important how many times single user clicked the item, just which have been used.

Body:
I am suspecting some menu items of my desktop software are not used, and would use Application Insights for that.

Bad idea: Creating event with Key:"menu" and property "copy" or other item is easy to create and plot in Azure portal and but creates too much noise but also duplicates.

Better idea is to build a list of items that are used throughout the session and at the program closing submit everything once as a list of items that are used.

//for each menu use
Telem.IncrementKey(menuItemText);

internal static void IncrementKey(string key)
{
    menuDict.TryGetValue(key, out count);
    count++;
    menuDict.AddOrUpdate(key, count, (k, v) => count);
}

//on closing program
foreach (var entry in menuDict)
{
    menuDictToSend.TryAdd(entry.Key, entry.value);
}
Telemetry.TrackEvent("MenuInteractionsUsed", menuDictToSend);

Another way would be to create key "menu" and comma separate all used menu interactions, but how do I plot those in Azure Portal to figure out the usage?

Is there a better way to submit the data that would be possible to analyze? It is not important how many times single user clicked the item, just which have been used.


问:
What is the format for 'datetime' in phpmyadmin?
enter image description here

The length/values

I want to know the datetime format, or maybe the sql query


问:
How can i write TCC (Taleo Connect Client) scripts ? I am from non programming domain, any help will be appreciated
I am new to Taleo Connect Client (TCC) and my current job required me to write TCC scripts, and I don't know what is TCC scripts and how does it look like. I am not a strong programmer, just know a little bit of coding. Any advice will be appreciated.

I am not sure where to start, I looked up online but found no documents on this.


问:
Yii Uncaught CHttpException
I've got yii app and some admin pages redirect me to error page. Error log:

```<code>2023/01/10 04:41:49 [error] 1423#1423: *4071 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught CHttpException in /home/fornex/tmp_7offers/app/lib/Controller/BaseController.php:229
Stack trace:
#0 /home/fornex/tmp_7offers/app/main/modules/admin/controllers/UsersController.php(732): App\Controller\BaseController->set404()
#1 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/actions/CInlineAction.php(49): UsersController->actionStatus()
#2 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#3 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CFilterChain.php(133): CController->runAction(Object(CInlineAction))
#4 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CFilter.php(40): CFilterChain->run()
#5 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/CController.php(1145): CFilter->filter(Object(CFilterChain))
#6 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CInlineFilter.php(58): CController->filterAccessControl(Object(CFil" while reading response header from upstream, client: 31.43.251.185, server: test.com, request: "GET /admin/users/status?id=32267&status=3&csrf=60c05c37717c54a8671b165d7b509456 HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.3-fpm.sock:", host: "5.187.1.28", referrer: "http://5.187.1.28/admin/users"
</code>```

Maybe I need to give some more info so you can help me with this error? I've been struggling with it for hours.

Title: Yii Uncaught CHttpException

Body:
I've got yii app and some admin pages redirect me to error page. Error log:

2023/01/10 04:41:49 [error] 1423#1423: *4071 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught CHttpException in /home/fornex/tmp_7offers/app/lib/Controller/BaseController.php:229
Stack trace:
#0 /home/fornex/tmp_7offers/app/main/modules/admin/controllers/UsersController.php(732): App\Controller\BaseController->set404()
#1 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/actions/CInlineAction.php(49): UsersController->actionStatus()
#2 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#3 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CFilterChain.php(133): CController->runAction(Object(CInlineAction))
#4 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CFilter.php(40): CFilterChain->run()
#5 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/CController.php(1145): CFilter->filter(Object(CFilterChain))
#6 /home/fornex/tmp_7offers/vendor/yiisoft/yii/framework/web/filters/CInlineFilter.php(58): CController->filterAccessControl(Object(CFil" while reading response header from upstream, client: 31.43.251.185, server: test.com, request: "GET /admin/users/status?id=32267&status=3&csrf=60c05c37717c54a8671b165d7b509456 HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.3-fpm.sock:", host: "5.187.1.28", referrer: "http://5.187.1.28/admin/users"

Maybe I need to give some more info so you can help me with this error? I've been struggling with it for hours.


问:
How to add a text button inside ProfileListItem in flutter
How to add a TextButton here?

I Tried inside ProfileListItem creating a TextButton but can't


问:
Print complete stack trace to debug Connection reset issue
I am new to reactive programming and I am using Webclient to make a call to another web service where I am trying to debug one issue which is coming randomly on testing environment where I can see just below in log files with no Stack Trace:

```<code>ERROR 2023-01-05 12:15:07,306 [reactor-http-epoll-7] [] [] [Loggers.java:319]  io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
        |_ checkpoint <E2><87><A2> Request to GET http://test-env.in/client/api/v1?getAllData=true [DefaultWebClient]
Stack trace:

</code>```

I tried to add log() method, also tried to add doOnError and printed the exception using logger.error but still stack trace is just empty, not able to get to the root cause of the issue.

Whereas when it is some other issue like 404 error then the complete stack trace is visible, I want to know why it is printing trace in this case and not in above case?

Body:
I am new to reactive programming and I am using Webclient to make a call to another web service where I am trying to debug one issue which is coming randomly on testing environment where I can see just below in log files with no Stack Trace:

ERROR 2023-01-05 12:15:07,306 [reactor-http-epoll-7] [] [] [Loggers.java:319]  io.netty.channel.unix.Errors$NativeIoException: readAddress(..) failed: Connection reset by peer
        Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
        |_ checkpoint <E2><87><A2> Request to GET http://test-env.in/client/api/v1?getAllData=true [DefaultWebClient]
Stack trace:

I tried to add log() method, also tried to add doOnError and printed the exception using logger.error but still stack trace is just empty, not able to get to the root cause of the issue.

Whereas when it is some other issue like 404 error then the complete stack trace is visible, I want to know why it is printing trace in this case and not in above case?


问:
Android Spinner with filter
There are plenty of resources on how to customize an Android Spinner for text search. One of them concentrate on replacing Spinner with TextView + AutoCompleteTextView, others explain how to change a design of a single spinner list item. I need the different one.

Currently I have a Spinner that selects from a fixed list an item that has two fields: ID and Text, and a result of this selection is the ID, not the Text.

I need a Spinner to remain a Spinner, to behave like a spinner - so that the main box is non-editable and I can select an item from a drop-down list.

Only a small thing should be added to it: When the Spinner is dropped down, this drop down list should contain either at the top or at the bottom an additional text field so that when I enter some text into it, the drop down list will be narrowed, and then I can click on the item, drop-down list collapses, and Spinner remembers what ID it was (not Text).

This additional editable filter text field should not be visible when the list is collapsed.

Is this possible without third party libraries?

Update

This one does what I want: https://www.youtube.com/watch?v=Wuu6RnN9Zws
but it is a third party library.

Title: Android Spinner with filter


问:
Take screenshot with specified coordinates
I'm using persp3d in R to plot 3D graphs. The graph has a large margin so I would like to take a screenshot in a certain smaller area. In Mac I can use Command+Shift+4, but I need to manually choose the coordinates (e.g. Mac shows coordinates 1212,482 by the pointer).

Is there a way to take screenshot with user-specified coordinates in R or using some Mac function?


问:
Set selected value in opetion if it's match in url
I've written the following code that generates a select list. However, the part where it's supposed to check if option name equals the same as part of url. I was able only select all or none.

```<code><?php
    function CheckIfSelected($val) {
    $current_url = strpos($_SERVER['REQUEST_URI'], $val);
    if ($current_url !== false){
    echo 'selected="selected"';
    }
}
?>
<select>
<?php
foreach ($service_id[$i] as $key => $val) {
?>
<option value="<?php echo $key ?>" <?php CheckIfSelected($val) ?>><?php echo $val ?></option>
<?php } ?>
</code>```

any ideas what is wrong?

Body:
I've written the following code that generates a select list. However, the part where it's supposed to check if option name equals the same as part of url. I was able only select all or none.

<?php
    function CheckIfSelected($val) {
    $current_url = strpos($_SERVER['REQUEST_URI'], $val);
    if ($current_url !== false){
    echo 'selected="selected"';
    }
}
?>
<select>
<?php
foreach ($service_id[$i] as $key => $val) {
?>
<option value="<?php echo $key ?>" <?php CheckIfSelected($val) ?>><?php echo $val ?></option>
<?php } ?>

any ideas what is wrong?


问:
Trying to numerically match python Log-Mel Spectrogram in Accelerate / Swift
I am working on a native port of OpenAI's Whisper for macOS and iOS via CoreML and Accelerate / AVFoundation, and in doing so noticed numerical differences in my Log Mel Spectrogram and code Whispers.

This python Notebook extracts the Log Mel Spectrogram exactly how Whisper does. I've decomposed the steps clearly.

My Swift code matches:

Raw Audio Samples

Conversion to Float

Conversion to Normalized Float

Hamming Windows calculated

Loading the precomputed Mel Filters

What begins to differ:

Complex Numbers from the STFT process

Results of Matrix ops.

However when I do my windowed FFTs, I notice similar values ranges, but inconsistent values that dont seem to match remotely. As in, not a rounding error.

My Full Mel class can be found here:

The Python code I am trying to match:

```<code>    window = torch.hann_window(N_FFT).to(audio.device)
    stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True)
    magnitudes = stft[:, :-1].abs() ** 2
    filters = mel_filters(audio.device, n_mels)
    mel_spec = filters @ magnitudes
    log_spec = torch.clamp(mel_spec, min=1e-10).log10()
    log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
    log_spec = (log_spec + 4.0) / 4.0
</code>```

And the core section of my swift code:

Points of interest:

Python appears to be outputting STFT of size 201 and 3001, whereas im not sure why they get 201, or 3001 from. My math seems to work out to generating 200 x 3000 exactly with the params from Whisper?

Am I calculating the overlapping hops correctly? I am not merging them into a single FFT. Im also padding by 200 samples before and after my audio frame of samples.

I am assuming that the 3000 sets 200 length complex numbers generated are STFT output output from PyTorch

Im assuming that vDSP's FFT implementation more or less matches whatever is happening in PyTorch

The STFT from Pytorch 0ths element and last element both have zero'd imaginary components. Mine do not. How!?

I know this is a large, complex question, but maybe someone brave will help me out?

Thank you in advance!

```<code>
 func processData(audio: [Int16]) -> [Float]
    {
        assert(self.sampleCount == audio.count)

        var audioFloat:[Float] = [Float](repeating: 0, count: audio.count)
        vDSP.convertElements(of: audio, to: &audioFloat)

        vDSP.divide(audioFloat, 32768.0, result: &audioFloat)

        // insert numFFT/2 samples before and numFFT/2 after so we have a extra numFFT amount to process
        audioFloat.insert(contentsOf: [Float](repeating: 0, count: self.numFFT/2), at: 0)
        audioFloat.append(contentsOf: [Float](repeating: 0, count: self.numFFT/2))

        // Split Complex arrays holding the mel spectrogram
        var allSampleReal = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)
        var allSampleImaginary = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)

        // we need to create 200 x 3000 matrix of STFTs - note we appear to want to output complex numbers (?)
        for (i) in 0 ..< self.melSampleCount
        {
            // Slice numFFTs every hop count (barf) and make a mel spectrum out of it
            var audioFrame = Array<Float>( audioFloat[ (i * self.hopCount) ..< ( (i * self.hopCount) + self.numFFT) ] )

            assert(audioFrame.count == self.numFFT)

            // Split Complex arrays holding a single FFT result, which gets appended to the
            var sampleReal:[Float] = [Float](repeating: 0, count: self.numFFT/2)
            var sampleImaginary:[Float] = [Float](repeating: 0, count: self.numFFT/2)

            sampleReal.withUnsafeMutableBufferPointer { realPtr in
                sampleImaginary.withUnsafeMutableBufferPointer { imagPtr in

                    vDSP.multiply(audioFrame,
                                  hanningWindow,
                                  result: &audioFrame)

                    var complexSignal = DSPSplitComplex(realp: realPtr.baseAddress!,
                                                        imagp: imagPtr.baseAddress!)

                    audioFrame.withUnsafeBytes { unsafeAudioBytes in
                        vDSP.convert(interleavedComplexVector: [DSPComplex](unsafeAudioBytes.bindMemory(to: DSPComplex.self)),
                                     toSplitComplexVector: &complexSignal)
                    }

                    self.fft.forward(input: complexSignal,
                                 output: &complexSignal)
                }
            }

            allSampleReal[i] = sampleReal
            allSampleImaginary[i] = sampleImaginary
        }

        // We create flattened  3000 x 200 array of DSPSplitComplex values
        var flattnedReal:[Float] = allSampleReal.flatMap { $0 }
        var flattnedImaginary:[Float] = allSampleImaginary.flatMap { $0 }

        // Take the magnitude squared of the matrix, which results in a Result flat array of 3000 x 200 of real floats
        // Then multiply it with our mel filter bank
        let count = flattnedReal.count
        var magnitudes = [Float](repeating: 0, count: count)
        var melSpectroGram = [Float](repeating: 0, count: 80 * 3000)

        flattnedReal.withUnsafeMutableBytes { unsafeReal in
            flattnedImaginary.withUnsafeMutableBytes { unsafeImaginary in

                let matrix = [DSPSplitComplex](repeating: DSPSplitComplex(realp: unsafeReal.bindMemory(to: Float.self).baseAddress!,
                                                                          imagp: unsafeImaginary.bindMemory(to: Float.self).baseAddress!),
                                               count: count)

                // populate magnitude matrix with magnitudes squared
                vDSP_zvmags(matrix, 1, &magnitudes, 1, vDSP_Length(count))

                // transpose magnitudes to get our 200 x 3000 matrix
                vDSP_mtrans(magnitudes, 1, &magnitudes, 1, 3000, 200)

                // Matrix A, a MxK sized matrix
                // Matrix B, a KxN sized matrix

                // MATRIX A mel filters is 80 rows x 200 columns
                // MATRIX B magnitudes is 3000 x 200
                // MATRIX B is TRANSPOSED to be 200 rows x 3000 columns
                // MATRIX C melSpectroGram is 80 rows x 3000 columns

                let M: Int32 = 80 // number of rows in matrix A
                let N: Int32 = 3000 // number of columns in matrix B
                let K: Int32 = 200 // number of columns in matrix A and number of rows in

                // matrix multiply magitude squared matrix with our filter bank
                // see https://www.advancedswift.com/matrix-math/
                cblas_sgemm(CblasRowMajor,
                            CblasNoTrans,           // Transpose A
                            CblasNoTrans,           //
                            M,                      // M Number of rows in matrices A and C.
                            N,                      // N Number of columns in matrices B and C.
                            K,                      // K Number of columns in matrix A; number of rows in matrix B.
                            1.0,                    // Alpha Scaling factor for the product of matrices A and B.
                            self.melFilterMatrix,   // Matrix A
                            K,                      // LDA The size of the first dimension of matrix A; if you are passing a matrix A[m][n], the value should be m.
                            magnitudes,             // Matrix B
                            N,                      // LDB The size of the first dimension of matrix B; if you are passing a matrix B[m][n], the value should be m.
                            0,                      // Beta Scaling factor for matrix C.
                            &melSpectroGram,        // Matrix C
                            N)                      // LDC The size of the first dimension of matrix C; if you are passing a matrix C[m][n], the value should be m.
                //        }

                var minValue: Float = 1e-10
                var maxValue: Float = 0.0
                var maxIndex: vDSP_Length = 0
                var minIndex: vDSP_Length = 0

                let melCount = melSpectroGram.count

                // get the current max value
                vDSP_maxvi(melSpectroGram, 1, &maxValue, &maxIndex, vDSP_Length(melCount))

                // Clip to a set min value, keeping the current max value
                vDSP_vclip(melSpectroGram, 1, &minValue, &maxValue, &melSpectroGram, 1, vDSP_Length(melCount))

                // Take the log base 10
                var melCountInt32:UInt32 = UInt32(melCount)
                vvlog10f(&melSpectroGram, melSpectroGram, &melCountInt32)

                // get the new max value
                vDSP_maxvi(melSpectroGram, 1, &maxValue, &maxIndex, vDSP_Length(melCount))

                // get the new min value
                vDSP_minvi(melSpectroGram, 1, &minValue, &minIndex, vDSP_Length(melCount))

                // emulate
                // log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
                // we effectively clamp to max - 8.0
                var newMin = maxValue - 8.0

                // Clip to new max and updated min
                vDSP_vclip(melSpectroGram, 1, &newMin, &maxValue, &melSpectroGram, 1, vDSP_Length(melCount))

                // Add 4 and Divide by 4
                var four:Float = 4.0
                vDSP_vsadd(melSpectroGram, 1, &four, &melSpectroGram, 1, vDSP_Length(melCount))
                vDSP_vsdiv(melSpectroGram, 1, &four, &melSpectroGram, 1, vDSP_Length(melCount))

            }
        }

        return melSpectroGram
    }

</code>```

Body:
I am working on a native port of OpenAI's Whisper for macOS and iOS via CoreML and Accelerate / AVFoundation, and in doing so noticed numerical differences in my Log Mel Spectrogram and code Whispers.

This python Notebook extracts the Log Mel Spectrogram exactly how Whisper does. I've decomposed the steps clearly.

My Swift code matches:

Raw Audio Samples

Conversion to Float

Conversion to Normalized Float

Hamming Windows calculated

Loading the precomputed Mel Filters

What begins to differ:

Complex Numbers from the STFT process

Results of Matrix ops.

However when I do my windowed FFTs, I notice similar values ranges, but inconsistent values that dont seem to match remotely. As in, not a rounding error.

My Full Mel class can be found here:

The Python code I am trying to match:

    window = torch.hann_window(N_FFT).to(audio.device)
    stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True)
    magnitudes = stft[:, :-1].abs() ** 2
    filters = mel_filters(audio.device, n_mels)
    mel_spec = filters @ magnitudes
    log_spec = torch.clamp(mel_spec, min=1e-10).log10()
    log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
    log_spec = (log_spec + 4.0) / 4.0

And the core section of my swift code:

Points of interest:

Python appears to be outputting STFT of size 201 and 3001, whereas im not sure why they get 201, or 3001 from. My math seems to work out to generating 200 x 3000 exactly with the params from Whisper?

Am I calculating the overlapping hops correctly? I am not merging them into a single FFT. Im also padding by 200 samples before and after my audio frame of samples.

I am assuming that the 3000 sets 200 length complex numbers generated are STFT output output from PyTorch

Im assuming that vDSP's FFT implementation more or less matches whatever is happening in PyTorch

The STFT from Pytorch 0ths element and last element both have zero'd imaginary components. Mine do not. How!?

I know this is a large, complex question, but maybe someone brave will help me out?

Thank you in advance!

 func processData(audio: [Int16]) -> [Float]
    {
        assert(self.sampleCount == audio.count)

        var audioFloat:[Float] = [Float](repeating: 0, count: audio.count)
        vDSP.convertElements(of: audio, to: &audioFloat)

        vDSP.divide(audioFloat, 32768.0, result: &audioFloat)

        // insert numFFT/2 samples before and numFFT/2 after so we have a extra numFFT amount to process
        audioFloat.insert(contentsOf: [Float](repeating: 0, count: self.numFFT/2), at: 0)
        audioFloat.append(contentsOf: [Float](repeating: 0, count: self.numFFT/2))

        // Split Complex arrays holding the mel spectrogram
        var allSampleReal = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)
        var allSampleImaginary = [[Float]](repeating: [Float](repeating: 0, count: self.numFFT/2), count: self.melSampleCount)

        // we need to create 200 x 3000 matrix of STFTs - note we appear to want to output complex numbers (?)
        for (i) in 0 ..< self.melSampleCount
        {
            // Slice numFFTs every hop count (barf) and make a mel spectrum out of it
            var audioFrame = Array<Float>( audioFloat[ (i * self.hopCount) ..< ( (i * self.hopCount) + self.numFFT) ] )

            assert(audioFrame.count == self.numFFT)

            // Split Complex arrays holding a single FFT result, which gets appended to the
            var sampleReal:[Float] = [Float](repeating: 0, count: self.numFFT/2)
            var sampleImaginary:[Float] = [Float](repeating: 0, count: self.numFFT/2)

            sampleReal.withUnsafeMutableBufferPointer { realPtr in
                sampleImaginary.withUnsafeMutableBufferPointer { imagPtr in

                    vDSP.multiply(audioFrame,
                                  hanningWindow,
                                  result: &audioFrame)

                    var complexSignal = DSPSplitComplex(realp: realPtr.baseAddress!,
                                                        imagp: imagPtr.baseAddress!)

                    audioFrame.withUnsafeBytes { unsafeAudioBytes in
                        vDSP.convert(interleavedComplexVector: [DSPComplex](unsafeAudioBytes.bindMemory(to: DSPComplex.self)),
                                     toSplitComplexVector: &complexSignal)
                    }

                    self.fft.forward(input: complexSignal,
                                 output: &complexSignal)
                }
            }

            allSampleReal[i] = sampleReal
            allSampleImaginary[i] = sampleImaginary
        }

        // We create flattened  3000 x 200 array of DSPSplitComplex values
        var flattnedReal:[Float] = allSampleReal.flatMap { $0 }
        var flattnedImaginary:[Float] = allSampleImaginary.flatMap { $0 }

        // Take the magnitude squared of the matrix, which results in a Result flat array of 3000 x 200 of real floats
        // Then multiply it with our mel filter bank
        let count = flattnedReal.count
        var magnitudes = [Float](repeating: 0, count: count)
        var melSpectroGram = [Float](repeating: 0, count: 80 * 3000)

        flattnedReal.withUnsafeMutableBytes { unsafeReal in
            flattnedImaginary.withUnsafeMutableBytes { unsafeImaginary in

                let matrix = [DSPSplitComplex](repeating: DSPSplitComplex(realp: unsafeReal.bindMemory(to: Float.self).baseAddress!,
                                                                          imagp: unsafeImaginary.bindMemory(to: Float.self).baseAddress!),
                                               count: count)

                // populate magnitude matrix with magnitudes squared
                vDSP_zvmags(matrix, 1, &magnitudes, 1, vDSP_Length(count))

                // transpose magnitudes to get our 200 x 3000 matrix
                vDSP_mtrans(magnitudes, 1, &magnitudes, 1, 3000, 200)

                // Matrix A, a MxK sized matrix
                // Matrix B, a KxN sized matrix

                // MATRIX A mel filters is 80 rows x 200 columns
                // MATRIX B magnitudes is 3000 x 200
                // MATRIX B is TRANSPOSED to be 200 rows x 3000 columns
                // MATRIX C melSpectroGram is 80 rows x 3000 columns

                let M: Int32 = 80 // number of rows in matrix A
                let N: Int32 = 3000 // number of columns in matrix B
                let K: Int32 = 200 // number of columns in matrix A and number of rows in

                // matrix multiply magitude squared matrix with our filter bank
                // see https://www.advancedswift.com/matrix-math/
                cblas_sgemm(CblasRowMajor,
                            CblasNoTrans,           // Transpose A
                            CblasNoTrans,           //
                            M,                      // M Number of rows in matrices A and C.
                            N,                      // N Number of columns in matrices B and C.
                            K,                      // K Number of columns in matrix A; number of rows in matrix B.
                            1.0,                    // Alpha Scaling factor for the product of matrices A and B.
                            self.melFilterMatrix,   // Matrix A
                            K,                      // LDA The size of the first dimension of matrix A; if you are passing a matrix A[m][n], the value should be m.
                            magnitudes,             // Matrix B
                            N,                      // LDB The size of the first dimension of matrix B; if you are passing a matrix B[m][n], the value should be m.
                            0,                      // Beta Scaling factor for matrix C.
                            &melSpectroGram,        // Matrix C
                            N)                      // LDC The size of the first dimension of matrix C; if you are passing a matrix C[m][n], the value should be m.
                //        }

                var minValue: Float = 1e-10
                var maxValue: Float = 0.0
                var maxIndex: vDSP_Length = 0
                var minIndex: vDSP_Length = 0

                let melCount = melSpectroGram.count

                // get the current max value
                vDSP_maxvi(melSpectroGram, 1, &maxValue, &maxIndex, vDSP_Length(melCount))

                // Clip to a set min value, keeping the current max value
                vDSP_vclip(melSpectroGram, 1, &minValue, &maxValue, &melSpectroGram, 1, vDSP_Length(melCount))

                // Take the log base 10
                var melCountInt32:UInt32 = UInt32(melCount)
                vvlog10f(&melSpectroGram, melSpectroGram, &melCountInt32)

                // get the new max value
                vDSP_maxvi(melSpectroGram, 1, &maxValue, &maxIndex, vDSP_Length(melCount))

                // get the new min value
                vDSP_minvi(melSpectroGram, 1, &minValue, &minIndex, vDSP_Length(melCount))

                // emulate
                // log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
                // we effectively clamp to max - 8.0
                var newMin = maxValue - 8.0

                // Clip to new max and updated min
                vDSP_vclip(melSpectroGram, 1, &newMin, &maxValue, &melSpectroGram, 1, vDSP_Length(melCount))

                // Add 4 and Divide by 4
                var four:Float = 4.0
                vDSP_vsadd(melSpectroGram, 1, &four, &melSpectroGram, 1, vDSP_Length(melCount))
                vDSP_vsdiv(melSpectroGram, 1, &four, &melSpectroGram, 1, vDSP_Length(melCount))

            }
        }

        return melSpectroGram
    }


问:
Random switching between scenePhase active and inactive when using LocalAuthentication
My app randomly switches scenePhase when I use LocalAuthentication. I've created a small sample to reproduce the bug below (NSFaceIDUsageDescription needs to be added for the app to run and to use Face ID in the simulator Features > Face ID > Enrolled must be ticked.

When you set a breakpoint on the first line of onChange you will see that the phase switches from active to inactive when unlocking the app with Face ID (unlock with Features > Face ID > Matching Face). How can that be?

import SwiftUI
import LocalAuthentication

@main
struct MyApp: App {

    @State private var isUnlocked = false
    @Environment(\.scenePhase) private var scenePhase

    var body: some Scene {
        WindowGroup {
            if isUnlocked {
                Text("Unlocked")
            } else {
                Text("Locked")
            }
        }
        .onChange(of: scenePhase) { phase in
            if phase == .active {
                let context = LAContext()
                var error: NSError?
                if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
                    let reason = "Authenticate yourself."
                    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
                        if success {
                            Task { @MainActor in
                                self.isUnlocked = true
                            }
                        }
                    }
                }
            } else if phase == .background || phase == .inactive {
                isUnlocked = false
            }
        }
    }
}
```


问:
PHP echo table with DataTable JS function
I wanted to echo a table from my DB. I have successfully created a function that will echo all the data from my DB. Unfortunately, the table does not implement the dataTables JS & CSS.

Below is the draft that I did, this is the expected outcome.

The plan output:

Unfortunately, when I echo the table with the function that I have created, the table is missing the "Show 10 rows" and "column, visibility", and page pagination function.

below are my php function:

function echoTable($conn, $tablename) {
  // Select table
  $sql = "SELECT * FROM $tablename";
  $result = mysqli_query($conn, $sql);
  if (!$result) {
    die("Error selecting table: " . mysqli_error($conn));
  }

  // Echo table as HTML
  echo "
";
  // Print table headers
  $row = mysqli_fetch_assoc($result);
  echo "
";
  foreach ($row as $key => $value) {
    echo "$key	";
  }
  echo "
";
  // Print table rows
  mysqli_data_seek($result, 0);
  while ($row = mysqli_fetch_assoc($result)) {
    echo "
";
    foreach ($row as $value) {
      echo "$value	";
    }
    echo "
";
  }
  echo "
";
}```

and I have inserted into the html as per below:

the outcome:

Can someone advise me on what is the problem.

Thanks in advance

Body:
I wanted to echo a table from my DB. I have successfully created a function that will echo all the data from my DB. Unfortunately, the table does not implement the dataTables JS & CSS.

Below is the draft that I did, this is the expected outcome.

The plan output:

Unfortunately, when I echo the table with the function that I have created, the table is missing the "Show 10 rows" and "column, visibility", and page pagination function.

below are my php function:

function echoTable($conn, $tablename) {
  // Select table
  $sql = "SELECT * FROM $tablename";
  $result = mysqli_query($conn, $sql);
  if (!$result) {
    die("Error selecting table: " . mysqli_error($conn));
  }

  // Echo table as HTML
  echo "
";
  // Print table headers
  $row = mysqli_fetch_assoc($result);
  echo "
";
  foreach ($row as $key => $value) {
    echo "$key	";
  }
  echo "
";
  // Print table rows
  mysqli_data_seek($result, 0);
  while ($row = mysqli_fetch_assoc($result)) {
    echo "
";
    foreach ($row as $value) {
      echo "$value	";
    }
    echo "
";
  }
  echo "
";
}

and I have inserted into the html as per below:

the outcome:

Can someone advise me on what is the problem.

Thanks in advance