问:
How to extend Auth0's middleware?
I'm trying to add some properties to the results of the authentication process. Auth0 sets up Express middleware like this:

```<code>  export const checkJwt = auth({
    audience: process.env.AUTH0_AUDIENCE,
    issuerBaseURL: process.env.AUTH0_ISSUERBASEURL,
  });
</code>```

This checks the authorisation header and works fine. It creates an request.auth object and adds payload into that. Works.

However, I want to add details from my own database, such as an ID or an organisation the user belongs to.

I've tried multiple ways to capture the result of auth but just can't get my head around it.

```<code>export var newAuth = function (
  req: Request,
  res: Response,
  next: NextFunction
) {

  const opts = {
    audience: process.env.AUTH0_AUDIENCE,
    issuerBaseURL: process.env.AUTH0_ISSUERBASEURL,
  };

  return (req: Request, res: Response, next: NextFunction) => {

    // is the issue here?
    var result = auth(opts)(req, res, next);

    return result;
  }
};
</code>```

I suppose I'm asking how can I intercept or extend middleware in Express?

Title: How to extend Auth0's middleware?

Body:
I'm trying to add some properties to the results of the authentication process. Auth0 sets up Express middleware like this:

  export const checkJwt = auth({
    audience: process.env.AUTH0_AUDIENCE,
    issuerBaseURL: process.env.AUTH0_ISSUERBASEURL,
  });

This checks the authorisation header and works fine. It creates an request.auth object and adds payload into that. Works.

However, I want to add details from my own database, such as an ID or an organisation the user belongs to.

I've tried multiple ways to capture the result of auth but just can't get my head around it.

export var newAuth = function (
  req: Request,
  res: Response,
  next: NextFunction
) {

  const opts = {
    audience: process.env.AUTH0_AUDIENCE,
    issuerBaseURL: process.env.AUTH0_ISSUERBASEURL,
  };

  return (req: Request, res: Response, next: NextFunction) => {

    // is the issue here?
    var result = auth(opts)(req, res, next);

    return result;
  }
};

I suppose I'm asking how can I intercept or extend middleware in Express?


来源: stackexchange

问:
How can I turn a matrix of data into a list of time series using R
I have a matrix of data where the 1st column are dates and the rest (nearly 100 columns) are binary data (0's and 1's). I was tasked to turn them into time series in R, but I'm lost in how to do it.

I'm lost in this one, especially because all info is for time series involving data different than binary data

ContentLicense: CC BY-SA 4.0


Title: SQL ADD 1HOUR INTERVAL TO A QUERY

Body:
I created a query that UNIONS two tables and makes a count of unanswered calls before an answered call.

Here is the query with the creation of the tables and some data added to it.

DROP TABLE IF EXISTS answered;
DROP TABLE IF EXISTS unanswered;

CREATE TABLE answered (
    ttime varchar(255),
    calledNumber varchar(255),
    callingNumber varchar(255),
    attendantNumber varchar(255),
    identifier varchar(255),
    company varchar(255),
    key12 varchar(255)

);

CREATE TABLE unanswered (
    ttime varchar(255),
    calledNumber varchar(255),
    callingNumber varchar(255),
    attendantNumber varchar(255),
    identifier varchar(255),
    company varchar(255),
    key12 varchar(255)

);

INSERT INTO answered (ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12) VALUES
('2022-12-19 04:13:00', '+123456',  '+2345672',  '+3234343', 'abcdefg212', '23343', 'Answered'),
('2022-12-19 04:37:00', '+123232',  '+2345671',  '+3234343', 'abcdefg213', '23343', 'Answered'),
('2022-12-19 06:47:00', '+127853',  '+2345671',  '+3231237', 'abcdefg214', '23344', 'Answered'),
('2022-12-19 18:30:00', '+566312',  '+1212212',  '+3231223', 'abcdefg222', '23345', 'Answered');

INSERT INTO unanswered (ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12) VALUES
('2022-12-19 04:23:00', '+123456',  '+2345672',  '+3234343', 'abcdefg215', '23343', 'Unanswered'),
('2022-12-19 04:24:00', '+123232',  '+2345671',  '+3234343', 'abcdefg216', '23343', 'Unanswered'),
('2022-12-19 06:27:00', '+127853',  '+2345671',  '+3231237', 'abcdefg217', '23344', 'Unanswered'),
('2022-12-19 17:47:00', '+127854',  '+2345676',  '+3231223', 'abcdefg218', '23345', 'Unanswered'),
('2022-12-19 17:07:00', '+127854',  '+1234216',  '+3231223', 'abcdefg219', '23345', 'Unanswered'),
('2022-12-19 12:47:00', '+125732',  '+9845646',  '+3231223', 'abcdefg220', '23345', 'Unanswered'),
('2022-12-19 13:47:00', '+127583',  '+1231221',  '+3231223', 'abcdefg221', '23345', 'Unanswered');

    WITH
        t1 AS (
            SELECT DISTINCT
                ttime,
                calledNumber,
                attendantNumber,
                callingNumber,
                identifier,
                company,
                key12
            FROM answered

        ),
        t2 AS (
            SELECT DISTINCT
                ttime,
                calledNumber,
                '' as attendantNumber,
                callingNumber,
                identifier,
                company,
                key12
            FROM unanswered

        ),
    t3 AS (
            SELECT ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12
            FROM t1
            UNION ALL
            SELECT ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12
            FROM t2
          ),
    t4 AS (
            SELECT row_number() OVER (PARTITION BY callingNumber, company ORDER BY ttime) as row_numb,
                ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12
            FROM t3
          ),
    t5 AS (
            SELECT row_numb, ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12,
                lag(row_numb, 1, 0) OVER (PARTITION BY callingNumber, company ORDER BY ttime) as info1
            FROM t4
            WHERE key12 = 'Answered'
          ),
    t6 AS (
            SELECT ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12,
            CASE
                WHEN (row_numb-info1) = 1 THEN '1 attempt until answered'
                WHEN (row_numb-info1) = 2 THEN '2 attempt until answered'
                ELSE '3 attempt or more until answered'
            END AS key122
            FROM t5
          )
    SELECT * FROM t6
    ORDER BY ttime

Right now the ouput is the following:

ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12, key122

'2022-12-19 04:13:00', '+123456', '+2345672', '+3234343', 'abcdefg212', '23343', 'Answered', '1 attempt until answered'

'2022-12-19 04:37:00', '+123232', '+2345671', '+3234343', 'abcdefg213', '23343', 'Answered', '3 attempt or more until answered'

'2022-12-19 06:47:00', '+127853', '+2345671', '+3231237', 'abcdefg214', '23344', 'Answered', '2 attempt until answered'

'2022-12-19 18:30:00', '+566312', '+1212212', '+3231223', 'abcdefg222', '23345', 'Answered', '3 attempt or more until answered'

I want to count only the unanswered calls that are only at a maximum of 1hour before of an unswared call and where the company and callingNumber are equal in both calls.

So, with the given data, my desired output is the following:

ttime, calledNumber, attendantNumber, callingNumber, identifier, company, key12, key122

'2022-12-19 04:13:00', '+123456', '+2345672', '+3234343', 'abcdefg212', '23343', 'Answered', '1 attempt until answered'

'2022-12-19 04:37:00', '+123232', '+2345671', '+3234343', 'abcdefg213', '23343', 'Answered', '3 attempt or more until answered'

'2022-12-19 06:47:00', '+127853', '+2345671', '+3231237', 'abcdefg214', '23344', 'Answered', '1 attempt until answered'

'2022-12-19 18:30:00', '+566312', '+1212212', '+3231223', 'abcdefg222', '23345', 'Answered', '2 attempt or more until answered'

In the initial table Unanswered this rows should not be counted, because they are more than 1 hour away of an answered call.

('2022-12-19 17:07:00', '+127854',  '+1234216',  '+3231223', 'abcdefg219', '23345', 'Unanswered'),
('2022-12-19 12:47:00', '+125732',  '+9845646',  '+3231223', 'abcdefg220', '23345', 'Unanswered'),
('2022-12-19 13:47:00', '+127583',  '+1231221',  '+3231223', 'abcdefg221', '23345', 'Unanswered'),
('2022-12-19 05:27:00', '+127853',  '+2345671',  '+3231237', 'abcdefg217', '23344', 'Unanswered'),

I've tried some things but I did not reach any positive output.

To sum all up, I need to change the query to be able to only count the calls that are at a maximum of 1hour before an answered call and that all the calls (answered and unanswered) have the same callingNumber and company columns.


问:
is using clear-site-data header removing client sides storages other than browser?
i was coming to http headers and that was it :
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

my question is that by using this header are we able to clear storages in other client platforms other than browsers such as android or ios native application?


问:
How to use same kotlin class to make 2 connections using configurationProperties
Currently, My project consists of a config class having lateinit var and a connection class which uses this config to make connection to the DB. Here is dummy code of what it looks like for a single connection and it works fine-

Config.kt-

```<code>@Configuration
@ConfigurationProperties(prefix="db")
@Scope("singleton")
open class Config {
    lateinit var schema: String
    lateinit var account: String
}
</code>```

Connection.kt-

```<code>@Configuration
open class Connection(private val config: Config) {
    fun makeConn()
    fun fetch()
}
</code>```

application.properties-

```<code>db.schema=ABC
db.account=myAcc
</code>```

main.kt-

```<code>open class dataFetch(
        private val config: Config,
        private val connection: Connection
) {
// Do something with config.schema
// Do something with connection.fetch()
}
</code>```

Now I want to make 2 connection with the same config class values and connection class. Only the connection properties need to be changed. What is a good way of doing this? I have made 2 copies of both classes and made it work but it's ugly and repetitive.

Body:
Currently, My project consists of a config class having lateinit var and a connection class which uses this config to make connection to the DB. Here is dummy code of what it looks like for a single connection and it works fine-

Config.kt-

@Configuration
@ConfigurationProperties(prefix="db")
@Scope("singleton")
open class Config {
    lateinit var schema: String
    lateinit var account: String
}

Connection.kt-

@Configuration
open class Connection(private val config: Config) {
    fun makeConn()
    fun fetch()
}

application.properties-

db.schema=ABC
db.account=myAcc

main.kt-

open class dataFetch(
        private val config: Config,
        private val connection: Connection
) {
// Do something with config.schema
// Do something with connection.fetch()
}

Now I want to make 2 connection with the same config class values and connection class. Only the connection properties need to be changed. What is a good way of doing this? I have made 2 copies of both classes and made it work but it's ugly and repetitive.


问:
Making request from browser empty tab
When I make request from browser's empty tab (using devtools console and fetch method ) it fails.

I receive these request headers:

```<code>Provisional headers are shown
Learn more
Referer
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
</code>```

I know that browser has CORS. But I don't understand how it works with empty tabs.

What browser set as origin and so on.

Also I think that in this case browser doesn't show all request headers.

So maybe you can tell to me how to get them and how it works or you can share a good resource to read.

Title: Making request from browser empty tab

Body:
When I make request from browser's empty tab (using devtools console and fetch method ) it fails.

I receive these request headers:

Provisional headers are shown
Learn more
Referer
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

I know that browser has CORS. But I don't understand how it works with empty tabs.

What browser set as origin and so on.

Also I think that in this case browser doesn't show all request headers.

So maybe you can tell to me how to get them and how it works or you can share a good resource to read.


问:
reading a 2048-bit Diffie-Hellman prime number from a buffer
I am trying to use the telegram API to support telegram calls directly from out system. In order to perform the call, the library requires e2e encryption. so I am calling a method to get a 2048-bit Diffie-Hellman prime number from the api. However, the number is coming as a buffer and I want to convert it to be a 2048bit prime number. here is the code

```<code>async requestCall(userId: string) {
    try {
      const dhConfig = await this.invoke(
        new Api.messages.GetDhConfig({
          randomLength: 32
        })
      );

      // convert p to number
      // @ts-expect-error ignore
      const p = dhConfig.p as Buffer;
      // convert p to integer

      const pInt = p.readInt32BE(0);

      // @ts-expect-error ignore
      const g = dhConfig.g;

      // chose random value between 1 and p-1
      const a = Math.floor(Math.random() * (pInt - 1)) + 1;

      // calculate g^a mod p
      const ga = Math.pow(g, a) % pInt;
      this.ga = ga;

      // get the ga hash SHA256 of g^a mod p as 32 bytes
      const gaHash = crypto.createHash('sha256').update(ga.toString()).digest();

      // save in the session
      this.a = a;
      this.p = pInt;

      // request the call
      await this.invoke(
        new Api.phone.RequestCall({
          userId,
          randomId: Math.floor(Math.random() * 100000000),
          gAHash: gaHash,
          protocol: new Api.PhoneCallProtocol({
            udpP2p: true,
            udpReflector: true,
            minLayer: 65,
            maxLayer: 65,
            libraryVersions: ['1.0.0', '2.0.0', '3.0.0', '4.0.0']
          })
        })
      );
    } catch (err) {
      console.log('[Telegram Client] [call] error: ', err);
    }
  }
</code>```

the number that I am getting is a negative number and it is most probably wrong. I also tried to convert it to string and then number but it did not work. so, the question is, how to get the prime number from that buffer?

Body:
I am trying to use the telegram API to support telegram calls directly from out system. In order to perform the call, the library requires e2e encryption. so I am calling a method to get a 2048-bit Diffie-Hellman prime number from the api. However, the number is coming as a buffer and I want to convert it to be a 2048bit prime number. here is the code

async requestCall(userId: string) {
    try {
      const dhConfig = await this.invoke(
        new Api.messages.GetDhConfig({
          randomLength: 32
        })
      );

      // convert p to number
      // @ts-expect-error ignore
      const p = dhConfig.p as Buffer;
      // convert p to integer

      const pInt = p.readInt32BE(0);

      // @ts-expect-error ignore
      const g = dhConfig.g;

      // chose random value between 1 and p-1
      const a = Math.floor(Math.random() * (pInt - 1)) + 1;

      // calculate g^a mod p
      const ga = Math.pow(g, a) % pInt;
      this.ga = ga;

      // get the ga hash SHA256 of g^a mod p as 32 bytes
      const gaHash = crypto.createHash('sha256').update(ga.toString()).digest();

      // save in the session
      this.a = a;
      this.p = pInt;

      // request the call
      await this.invoke(
        new Api.phone.RequestCall({
          userId,
          randomId: Math.floor(Math.random() * 100000000),
          gAHash: gaHash,
          protocol: new Api.PhoneCallProtocol({
            udpP2p: true,
            udpReflector: true,
            minLayer: 65,
            maxLayer: 65,
            libraryVersions: ['1.0.0', '2.0.0', '3.0.0', '4.0.0']
          })
        })
      );
    } catch (err) {
      console.log('[Telegram Client] [call] error: ', err);
    }
  }

the number that I am getting is a negative number and it is most probably wrong. I also tried to convert it to string and then number but it did not work. so, the question is, how to get the prime number from that buffer?


问:
flutter search in search
This is the onsearch function that searches for all custnum addresses.

```<code>onSearch(String text) async {
print(text);
List<Item> itemII = items;
if (text.isNotEmpty) {
  List<Item> itemList = [];
  for (var item in itemII) {
    if (item.custnum == text.toLowerCase().toUpperCase()) {
      itemList.add(item);
    }
  }
  setState(() {
    searchText = text;
    searchitems.clear();
    searchitems.addAll(itemList);
    MainPage.searchItemMainPage.addAll(itemList);

    if (searchitems.isNotEmpty) {
      print({MainPage.searchItemMainPage[0].address});
      searchitems[0].address!.sort((a, b) {
        if (a.for_bill == 'Y' && b.for_bill == 'N') {
          return -1;
        } else if (a.for_bill == 'N' && b.for_bill == 'Y') {
          return 1;
        } else if (a.for_ship == 'Y' && b.for_ship == 'N') {
          return -1;
        } else if (a.for_ship == 'N' && b.for_ship == 'Y') {
          return 1;
        } else if (a.for_contact == 'Y' && b.for_contact == 'N') {
          return -1;
        } else if (a.for_contact == 'N' && b.for_contact == 'Y') {
          return 1;
        } else {
          return 0;
        }
      });
    }
  });
} else {
  setState(() {
    searchCus.clear();
    searchitems.clear();
    MainPage.searchItemMainPage.clear();
    // searchitems.addAll(items);
    print('searchitems : $searchitems');
  });
}
}
</code>```

This is the onsearchaddr function, it finds the address in searchitems after the search. By typing the name of the field addr, then the address will be displayed.

```<code> onSearchAddr(String text) {
List<Item> result = searchitems;
if (text.isNotEmpty) {
  List<Item> itemList = [];
  for (var item in result) {
    item.address = item.address!
        .where((element) =>
            element.addr1!.toUpperCase().toLowerCase().contains(text))
        .toList();
    itemList.add(item);
  }

  setState(() {
    searchitems.clear();
    searchitems.addAll(itemList);
    print('itemList : ${itemList}');
  });
} else {
  setState(() {
    searchitems.clear();
    searchitems.addAll(MainPage.searchItemMainPage);
    print(
        'SearchitemsMainPage : ${MainPage.searchItemMainPage[0].address}');
  });
 }
 }
</code>```

Could you please write some code to modify onsearchaddr, it can search as typed but when it clears text it doesn't show information of searchitems as before but it shows information of last typed message.
It's like the previous backup wasn't provided.

Title: flutter search in search

Body:
This is the onsearch function that searches for all custnum addresses.

onSearch(String text) async {
print(text);
List<Item> itemII = items;
if (text.isNotEmpty) {
  List<Item> itemList = [];
  for (var item in itemII) {
    if (item.custnum == text.toLowerCase().toUpperCase()) {
      itemList.add(item);
    }
  }
  setState(() {
    searchText = text;
    searchitems.clear();
    searchitems.addAll(itemList);
    MainPage.searchItemMainPage.addAll(itemList);

    if (searchitems.isNotEmpty) {
      print({MainPage.searchItemMainPage[0].address});
      searchitems[0].address!.sort((a, b) {
        if (a.for_bill == 'Y' && b.for_bill == 'N') {
          return -1;
        } else if (a.for_bill == 'N' && b.for_bill == 'Y') {
          return 1;
        } else if (a.for_ship == 'Y' && b.for_ship == 'N') {
          return -1;
        } else if (a.for_ship == 'N' && b.for_ship == 'Y') {
          return 1;
        } else if (a.for_contact == 'Y' && b.for_contact == 'N') {
          return -1;
        } else if (a.for_contact == 'N' && b.for_contact == 'Y') {
          return 1;
        } else {
          return 0;
        }
      });
    }
  });
} else {
  setState(() {
    searchCus.clear();
    searchitems.clear();
    MainPage.searchItemMainPage.clear();
    // searchitems.addAll(items);
    print('searchitems : $searchitems');
  });
}
}

This is the onsearchaddr function, it finds the address in searchitems after the search. By typing the name of the field addr, then the address will be displayed.

 onSearchAddr(String text) {
List<Item> result = searchitems;
if (text.isNotEmpty) {
  List<Item> itemList = [];
  for (var item in result) {
    item.address = item.address!
        .where((element) =>
            element.addr1!.toUpperCase().toLowerCase().contains(text))
        .toList();
    itemList.add(item);
  }

  setState(() {
    searchitems.clear();
    searchitems.addAll(itemList);
    print('itemList : ${itemList}');
  });
} else {
  setState(() {
    searchitems.clear();
    searchitems.addAll(MainPage.searchItemMainPage);
    print(
        'SearchitemsMainPage : ${MainPage.searchItemMainPage[0].address}');
  });
 }
 }

Could you please write some code to modify onsearchaddr, it can search as typed but when it clears text it doesn't show information of searchitems as before but it shows information of last typed message.
It's like the previous backup wasn't provided.


问:
openssl ruby, add an additional ssl certificate (i.e. don't replace old ones)
I'm facing troubles with an API call I do with HTTP gem, the https server I need to call has a certificate created by a CA that is valid but the root certificate is not present in the CA bundle of the server (which I have no rights to change).

I have certificate and intermediaries for the server, and can make it work with configuring SSL_CERT_FILE as env file, though this replaces in openssl the other certificates, so with this file only this specific API works, and nothing else.

I'm looking for a way to include the certificate globally so that all my calls work.

I managed to have successful ssl connections on a per call level, but it's really not ideal, and I'd like a global solution.

here's how I managed to do it:

```<code>store = OpenSSL::X509::Store.new
store.set_default_paths
store.add_file('ssl_certificates/ca_certificate.pem')
ssl_ctx = OpenSSL::SSL::SSLContext.new.tap do |ctx|
  ctx.set_params(
    cert_store: store
  )
end

HTTP.post("https://<the api server with the non recognised ssl certificate>.com", ssl_context: ssl_ctx)
HTTP.post("https://google.com", ssl_context: ssl_ctx)
</code>```

The problem with this is that it's per call. I'd like to have it globally, I can set it globally via SSL_CERT_FILE environment variable, but in that case all other certificates are removed, and nothing else works.

any ideas?

Thanks,

Body:
I'm facing troubles with an API call I do with HTTP gem, the https server I need to call has a certificate created by a CA that is valid but the root certificate is not present in the CA bundle of the server (which I have no rights to change).

I have certificate and intermediaries for the server, and can make it work with configuring SSL_CERT_FILE as env file, though this replaces in openssl the other certificates, so with this file only this specific API works, and nothing else.

I'm looking for a way to include the certificate globally so that all my calls work.

I managed to have successful ssl connections on a per call level, but it's really not ideal, and I'd like a global solution.

here's how I managed to do it:

store = OpenSSL::X509::Store.new
store.set_default_paths
store.add_file('ssl_certificates/ca_certificate.pem')
ssl_ctx = OpenSSL::SSL::SSLContext.new.tap do |ctx|
  ctx.set_params(
    cert_store: store
  )
end

HTTP.post("https://<the api server with the non recognised ssl certificate>.com", ssl_context: ssl_ctx)
HTTP.post("https://google.com", ssl_context: ssl_ctx)

The problem with this is that it's per call. I'd like to have it globally, I can set it globally via SSL_CERT_FILE environment variable, but in that case all other certificates are removed, and nothing else works.

any ideas?

Thanks,


问:
Get the names of the parameters of the wrapped function
I want to use the methods of the Minio class without specifying all their parameters, but substituting some of the parameters automatically. How do I do it...

I get all the class methods from the prototype of the Minio class and dynamically create wrappers for them in my class.

For each wrapper method, I get the parameter names from the original method of the Test class.

If there is one in the list of parameters that I want to omit when calling my wrapper method, then I add it to the list of arguments and call originalMethod.apply(this.minioClient, args).

Everything was fine until there were methods that were already wrapped.
I need to get the parameter list of the bucketExists method from outside the Minio class. Any idea how to get parameter names from such a wrapped method?

// minio/dist/main/helpers.js
exports function promisify(fn){
  return function(){
    const args = [...arguments];
    fn.apply(this, args);
  }
}

// minio/dist/main/minio.js
class Minio{
  bucketExists(bucketName){
    return bucketName;
  }
  methodThatNotWrappedByPromisifyAndWorksFine(bucketName){
    return bucketName;
  }
}

module.exports = Minio;
Minio.prototype.bucketExists = (0,helpers.promisify)(Minio.prototype.bucketExists)
```
<p>I want to give an instance of my class with methods wrapped from the original class link the ability to work with only one bucket, that was passed to the my class constructor, without the ability to specify some other one after initialize.</p>
<p>My wrapper</p>
<pre class="lang-js prettyprint-override"><code>    const proxyHandler = () => {
      return {
        apply: (target, thisArg, argumentsList) => {
          const funcParams = getMethodParamNames(target.source ? target.source.functionForWrap : target);
          const bucketNameIndex = funcParams.indexOf("bucketName");
          const regionNameIndex = funcParams.indexOf("region");

          if (bucketNameIndex >= 0) {
            argumentsList.splice(bucketNameIndex, 0, this.bucket.name);
          }
          if (regionNameIndex >= 0) {
            argumentsList.splice(regionNameIndex, 0, this.bucket.region);
          }
          try {
            return target.apply(this.minioClient, argumentsList);
          } catch (error) {
            logger.engine.error(`S3 '${this.bucket.name}' ${target} error: ${error.message}`, error.stack);
          }
        },
      }
    }

    getMethods(this.minioClient).forEach(func => {
      this[func] = new Proxy(this.minioClient[func], proxyHandler());
    })
</code>```

Solved the problem by overriding the method wrapper like this.

const MinioHelpers = require('minio/dist/main/helpers');

const origMinioPromisify = MinioHelpers.promisify;

MinioHelpers.promisify = (functionForWrap) => {
    console.log("PATCHED!", functionForWrap);
    var fn = origMinioPromisify(functionForWrap);
    //from this i'll get all need information about wrapped function
    fn.source = {
        functionForWrap,
        promisify: origMinioPromisify,
    }
    return fn
}

var Minio = require('minio');

```

Body:
I want to use the methods of the Minio class without specifying all their parameters, but substituting some of the parameters automatically. How do I do it...

I get all the class methods from the prototype of the Minio class and dynamically create wrappers for them in my class.

For each wrapper method, I get the parameter names from the original method of the Test class.

If there is one in the list of parameters that I want to omit when calling my wrapper method, then I add it to the list of arguments and call originalMethod.apply(this.minioClient, args).

Everything was fine until there were methods that were already wrapped.
I need to get the parameter list of the bucketExists method from outside the Minio class. Any idea how to get parameter names from such a wrapped method?

// minio/dist/main/helpers.js
exports function promisify(fn){
  return function(){
    const args = [...arguments];
    fn.apply(this, args);
  }
}

// minio/dist/main/minio.js
class Minio{
  bucketExists(bucketName){
    return bucketName;
  }
  methodThatNotWrappedByPromisifyAndWorksFine(bucketName){
    return bucketName;
  }
}

module.exports = Minio;
Minio.prototype.bucketExists = (0,helpers.promisify)(Minio.prototype.bucketExists)

I want to give an instance of my class with methods wrapped from the original class link the ability to work with only one bucket, that was passed to the my class constructor, without the ability to specify some other one after initialize.

My wrapper

    const proxyHandler = () => {
      return {
        apply: (target, thisArg, argumentsList) => {
          const funcParams = getMethodParamNames(target.source ? target.source.functionForWrap : target);
          const bucketNameIndex = funcParams.indexOf("bucketName");
          const regionNameIndex = funcParams.indexOf("region");

          if (bucketNameIndex >= 0) {
            argumentsList.splice(bucketNameIndex, 0, this.bucket.name);
          }
          if (regionNameIndex >= 0) {
            argumentsList.splice(regionNameIndex, 0, this.bucket.region);
          }
          try {
            return target.apply(this.minioClient, argumentsList);
          } catch (error) {
            logger.engine.error(`S3 '${this.bucket.name}' ${target} error: ${error.message}`, error.stack);
          }
        },
      }
    }

    getMethods(this.minioClient).forEach(func => {
      this[func] = new Proxy(this.minioClient[func], proxyHandler());
    })

Solved the problem by overriding the method wrapper like this.

const MinioHelpers = require('minio/dist/main/helpers');

const origMinioPromisify = MinioHelpers.promisify;

MinioHelpers.promisify = (functionForWrap) => {
    console.log("PATCHED!", functionForWrap);
    var fn = origMinioPromisify(functionForWrap);
    //from this i'll get all need information about wrapped function
    fn.source = {
        functionForWrap,
        promisify: origMinioPromisify,
    }
    return fn
}

var Minio = require('minio');


问:
Access to row values from vue table
I'm trying to create a table with buttons in every row that trigger a modal form.

This is my current b-table

<template>

    <template v-slot:cell(Actions)="{ gw }">

          Promote

        Delete

    </template>

</template>
```

The button does trigger the method populateGWForm, but the passed "gw" shows up undefined.

Is the v-slot "{ gw }" the mechanism that enumerates the "gws" per row ?

Is the syntax of @click correct?

Title: Access to row values from vue table

Body:
I'm trying to create a table with buttons in every row that trigger a modal form.

This is my current b-table

<template>

    <template v-slot:cell(Actions)="{ gw }">

          Promote

        Delete

    </template>

</template>

The button does trigger the method populateGWForm, but the passed "gw" shows up undefined.

Is the v-slot "{ gw }" the mechanism that enumerates the "gws" per row ?

Is the syntax of @click correct?


问:
How to eliminate a shift/ reduce issue in Bison/Flex?
I have a school project where I have to make a minipy compiler (kind of similar to python), and I have a shift/reduce conflict in my .synt file.  The problem is within this grammar:

```<code>INS:INS_AFF
   |INS INS_AFF
   |INS_IF
   |INS_FOR1
   |INS_FOR2
   |INS_WHILE
</code>```

The problem only appeared after adding INS in the second line, but I need to add that in each line — otherwise, it won't work. So what other options do I have?

I tried every solution I ever found, but nothing worked. Either it won't work as it's supposed to, or it gives me more problems.

Body:
I have a school project where I have to make a minipy compiler (kind of similar to python), and I have a shift/reduce conflict in my .synt file.  The problem is within this grammar:

INS:INS_AFF
   |INS INS_AFF
   |INS_IF
   |INS_FOR1
   |INS_FOR2
   |INS_WHILE

The problem only appeared after adding INS in the second line, but I need to add that in each line — otherwise, it won't work. So what other options do I have?

I tried every solution I ever found, but nothing worked. Either it won't work as it's supposed to, or it gives me more problems.


问:
Escaping the ${APACHE_LOG_DIR} variable in the cat command of a bash script
I'm coding a BASH script to automatically configure virtual hosts of an apache server.
To create the virtual host configuration file I use the cat command. The problem is that I don't know how to escape the ${APACHE_LOG_DIR} variables. I tried with \$ like this :

```<code>#!/bin/bash
cat >/etc/apache2/sites-available/site1.com.conf <<EOF
<VirtualHost *:80>
     ServerAdmin webmaster@localhost
     ServerName site1.com
     ServerAlias site1.com
     DocumentRoot /var/www/ site1.com /public_html
     ErrorLog \${APACHE_LOG_DIR}/error.log
     CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<Directory "/var/www/site1.com">
     AllowOverride All
</Directory>
EOF
</code>```

but it doesn't work and the variable ${APACHE_LOG_DIR}  is not displayed in the .conf file :

```<code><VirtualHost *:80>
     ServerAdmin webmaster@localhost
     ServerName site1.com
     ServerAlias site1.com
     DocumentRoot /var/www/ site1.com /public_html
     ErrorLog /error.log
     CustomLog /access.log combined
</VirtualHost>
<Directory "/var/www/site1.com">
     AllowOverride All
</Directory>
</code>```

when I escape $ with \ without something after, $ appears in the .conf file, but if I escape the entire variable \${APACHE_LOG_DIR} in the code, the variable ${APACHE_LOG_DIR} no longer appears in the .conf file

Thanks for your help

Body:
I'm coding a BASH script to automatically configure virtual hosts of an apache server.
To create the virtual host configuration file I use the cat command. The problem is that I don't know how to escape the ${APACHE_LOG_DIR} variables. I tried with \$ like this :

#!/bin/bash
cat >/etc/apache2/sites-available/site1.com.conf <<EOF
<VirtualHost *:80>
     ServerAdmin webmaster@localhost
     ServerName site1.com
     ServerAlias site1.com
     DocumentRoot /var/www/ site1.com /public_html
     ErrorLog \${APACHE_LOG_DIR}/error.log
     CustomLog \${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<Directory "/var/www/site1.com">
     AllowOverride All
</Directory>
EOF

but it doesn't work and the variable ${APACHE_LOG_DIR}  is not displayed in the .conf file :

<VirtualHost *:80>
     ServerAdmin webmaster@localhost
     ServerName site1.com
     ServerAlias site1.com
     DocumentRoot /var/www/ site1.com /public_html
     ErrorLog /error.log
     CustomLog /access.log combined
</VirtualHost>
<Directory "/var/www/site1.com">
     AllowOverride All
</Directory>

when I escape $ with \ without something after, $ appears in the .conf file, but if I escape the entire variable \${APACHE_LOG_DIR} in the code, the variable ${APACHE_LOG_DIR} no longer appears in the .conf file

Thanks for your help


问:
Get closure size in Nix
How does one get the derivation closure size in Nix itself. You can already do this using nix path-info (for https://github.com/srid/emanote - see example below),  but I'd like to get this value from a Nix expression. Is this doable? If so, how?

```<code>❯ nix path-info --json -S .#default | jq 'map(select(.closureSize > 0.4e9)) | sort_by(.closureSize) | map([.path, .closureSize])'
[
  [
    "/nix/store/l3fl1fzxw6nfkbdmcf9ghjnnkl4l7vml-emanote-1.0.1.6",
    546010216
  ]
]
</code>```

Title: Get closure size in Nix

Body:
How does one get the derivation closure size in Nix itself. You can already do this using nix path-info (for https://github.com/srid/emanote - see example below),  but I'd like to get this value from a Nix expression. Is this doable? If so, how?

❯ nix path-info --json -S .#default | jq 'map(select(.closureSize > 0.4e9)) | sort_by(.closureSize) | map([.path, .closureSize])'
[
  [
    "/nix/store/l3fl1fzxw6nfkbdmcf9ghjnnkl4l7vml-emanote-1.0.1.6",
    546010216
  ]
]


问:
jest Could not locate module error in React typescript
I'm trying to learning unit testing in react applications. My app created with webpack instead of create-react-app. I looked at the topics with similar errors, then I applied the config file as follows. The problem is I'm using alias in tsconfig and  also edited moduleNameMapper accordingly in jest.config file. But in console this error appears.

Configuration error:

```<code>Could not locate module @layouts/main mapped as:
views/commons/layouts/$1.

Please check your configuration for these entries:
{
  "moduleNameMapper": {
    "/^@layouts\/(.*)$/": "views/commons/layouts/$1"
  },
  "resolver": undefined
}

> 1 | import MainLayout from '@layouts/main'
    | ^
  2 |
  3 | const NotFoundPage = () => (
  4 |   <MainLayout>
</code>```

I created a config file as below.
// jest.config.js

```<code>const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig')

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: 'ts-jest',
  roots: ['<rootDir>/src'],
  moduleDirectories: ['node_modules', __dirname],
  setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
  moduleNameMapper: {
    ...pathsToModuleNameMapper(compilerOptions.paths),
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '^.+\\.js?$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  moduleFileExtensions: ['js', 'ts', 'd.ts', 'jsx', 'tsx', 'json']
}
</code>```

// setupTests.js

```<code>import '@testing-library/jest-dom'
</code>```

// tsconfig.js

```<code>{
  "compilerOptions": {
    "baseUrl": "./src/",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "paths": {
      "@api/*": ["api/*"],
      "@assets/*": ["assets/*"],
      "@icons/*": ["assets/icons/*"],
      "@images/*": ["assets/images/*"],
      "@styles/*": ["assets/styles/*"],
      "@hooks/*": ["hooks/*"],
      "@i18n": ["i18n/index"],
      "@i18n/*": ["i18n/*"],
      "@store": ["store/index"],
      "@store/*": ["store/*"],
      "@reducers/*": ["store/reducers/*"],
      "@storage": ["store/storage/index"],
      "@storage/*": ["store/storage/*"],
      "@storeUtils/*": ["store/utils/*"],
      "@staticStore/*": ["store/static/*"],
      "@types": ["types/index"],
      "@types/*": ["types/*"],
      "@views/*": ["views/*"],
      "@commonViews/*": ["views/commons/*"],
      "@footers/*": ["views/commons/footers/*"],
      "@headers/*": ["views/commons/headers/*"],
      "@layouts/*": ["views/commons/layouts/*"],
      "@providers/*": ["views/commons/providers/*"],
      "@seo/*": ["views/commons/seo/*"],
      "@components/*": ["views/components/*"],
      "@viewsConfigs/*": ["views/configs/*"],
      "@pages/*": ["views/pages/*"]
    }
  },
  "include": ["src/**/*", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}
</code>```

//babelrc

```<code>{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": []
}
</code>```

By the way, if I changes moduleDirectories: ['node_modules', __dirname], like moduleDirectories: ['node_modules', "."], error does not appears anymore. But I'm getting new error like that:

```<code>Test suite failed to run

TypeError: Cannot read properties of undefined (reading 'extend')

  at createJestExpect (node_modules/@jest/expect/build/index.js:29:19)
  at Object.<anonymous> (node_modules/@jest/expect/build/index.js:39:20)
</code>```

Body:
I'm trying to learning unit testing in react applications. My app created with webpack instead of create-react-app. I looked at the topics with similar errors, then I applied the config file as follows. The problem is I'm using alias in tsconfig and  also edited moduleNameMapper accordingly in jest.config file. But in console this error appears.

Configuration error:

Could not locate module @layouts/main mapped as:
views/commons/layouts/$1.

Please check your configuration for these entries:
{
  "moduleNameMapper": {
    "/^@layouts\/(.*)$/": "views/commons/layouts/$1"
  },
  "resolver": undefined
}

> 1 | import MainLayout from '@layouts/main'
    | ^
  2 |
  3 | const NotFoundPage = () => (
  4 |   <MainLayout>

I created a config file as below.
// jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig')

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: 'ts-jest',
  roots: ['<rootDir>/src'],
  moduleDirectories: ['node_modules', __dirname],
  setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
  moduleNameMapper: {
    ...pathsToModuleNameMapper(compilerOptions.paths),
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '^.+\\.js?$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  moduleFileExtensions: ['js', 'ts', 'd.ts', 'jsx', 'tsx', 'json']
}

// setupTests.js

import '@testing-library/jest-dom'

// tsconfig.js

{
  "compilerOptions": {
    "baseUrl": "./src/",
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "paths": {
      "@api/*": ["api/*"],
      "@assets/*": ["assets/*"],
      "@icons/*": ["assets/icons/*"],
      "@images/*": ["assets/images/*"],
      "@styles/*": ["assets/styles/*"],
      "@hooks/*": ["hooks/*"],
      "@i18n": ["i18n/index"],
      "@i18n/*": ["i18n/*"],
      "@store": ["store/index"],
      "@store/*": ["store/*"],
      "@reducers/*": ["store/reducers/*"],
      "@storage": ["store/storage/index"],
      "@storage/*": ["store/storage/*"],
      "@storeUtils/*": ["store/utils/*"],
      "@staticStore/*": ["store/static/*"],
      "@types": ["types/index"],
      "@types/*": ["types/*"],
      "@views/*": ["views/*"],
      "@commonViews/*": ["views/commons/*"],
      "@footers/*": ["views/commons/footers/*"],
      "@headers/*": ["views/commons/headers/*"],
      "@layouts/*": ["views/commons/layouts/*"],
      "@providers/*": ["views/commons/providers/*"],
      "@seo/*": ["views/commons/seo/*"],
      "@components/*": ["views/components/*"],
      "@viewsConfigs/*": ["views/configs/*"],
      "@pages/*": ["views/pages/*"]
    }
  },
  "include": ["src/**/*", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

//babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": []
}

By the way, if I changes moduleDirectories: ['node_modules', __dirname], like moduleDirectories: ['node_modules', "."], error does not appears anymore. But I'm getting new error like that:

Test suite failed to run

TypeError: Cannot read properties of undefined (reading 'extend')

  at createJestExpect (node_modules/@jest/expect/build/index.js:29:19)
  at Object.<anonymous> (node_modules/@jest/expect/build/index.js:39:20)


问:
monitor pgadmin cpu/memory consumption for a database in realtime
The default dashboard for pgadmin is exactly what I want , except it doesn't have the CPU and memory consumption graph. It seems to use the admin pack extension, and the preferences section doesn't provide an option to configure it. Is there another extension or way to have the graph for CPU and memory consumption in pgadmin? (including another db client alternative to pgadmin):


问:
How to delete a specific element from a dynamic array?
I am currently trying to make it so that when the user gives a student ID to my program it will compare it with all the other ID's and if it exists in the array then it will delete it using realloc.

Here are some parts of the program:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student {
    int id;
    char name[50];
    char surname[50];
    int semester;
    float grade;
} student;

int
main()
{
    int x,
     std,
     i,
     k,
     size1,
     size2;

    x = 0;
    int car = 0;
    int flag = 1;
    struct student *ptr = NULL;

    while (x != 8) {
        printf("\n"
            "1. Initialize student list\n"
            "2. Add a student record\n"
            "3. Delete a student record\n"
            "4. Display a student record by student surname\n"
            "5. Display students passed\n"
            "6. Display students failed\n"
            "7. Display all student records\n"
            "8. Exit");
        printf("\nYour choice: ");
        scanf("%d", &x);

        if (x == 1) {
            printf("How many new students? ");
            scanf("%d", &std);
            ptr = (student *) malloc(std * sizeof(student));
            size1 = std;
            for (i = 0; i < std; i++) {
                printf("Enter detail of student #%d\n", (i + 1));
                ptr[i].id = i + 1;
                printf("Enter first name: ");
                scanf("%s", ptr[i].name);
                printf("Enter last name: ");
                scanf("%s", ptr[i].surname);
                printf("Enter semester: ");
                scanf("%d", &ptr[i].semester);
                printf("Enter grade: ");
                scanf("%f", &ptr[i].grade);
            }
        }

        else if (x == 3) {
            printf("Give the ID you wish to delete:\n");
            scanf("%d", &k);
            for (i = 0; i < std; i++) {
                if (k == ptr[i].id) {
                    std = std - 1;
                    size2 = std;
                    ptr[i] = ptr[i + 1];
                    memmove(ptr,ptr + (size1 - size2),size2 * sizeof(student));
                    ptr = realloc(ptr, std * sizeof(student));
                }
            }
        }

        else if (x == 7) {
            for (i = 0; i < std; i++) {
                printf("%d ", ptr[i].id);
                printf("%s ", ptr[i].name);
                printf("%s ", ptr[i].surname);
                printf("%d ", ptr[i].semester);
                printf("%f ", ptr[i].grade);
                printf("\n");
            }
        }
    }
}
</code>```

I have tried adding another for loop in the if(x==3) under the if (k==ptr[i].id) to move everything but when it tries to print it either gives me the next students information 2 times or it just prints some random numbers and letters which doesn't help. I have also tried to change std. Sometimes upping it by 1 other times lowering it by 1. It still didn't give me the results I expected. I'm pretty sure I'm missing something pretty obvious but it's been a few hours and I still haven't found a way to make it work.

What I want from it is to read the ID. Compare it with ptr[i].id to see if it exists and if it does exist then I simply want to delete it and everything that comes with it. Basically overwrite ptr[i](which has the id I want to delete) with the next one which would be ptr[i+1]

Body:
I am currently trying to make it so that when the user gives a student ID to my program it will compare it with all the other ID's and if it exists in the array then it will delete it using realloc.

Here are some parts of the program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct student {
    int id;
    char name[50];
    char surname[50];
    int semester;
    float grade;
} student;

int
main()
{
    int x,
     std,
     i,
     k,
     size1,
     size2;

    x = 0;
    int car = 0;
    int flag = 1;
    struct student *ptr = NULL;

    while (x != 8) {
        printf("\n"
            "1. Initialize student list\n"
            "2. Add a student record\n"
            "3. Delete a student record\n"
            "4. Display a student record by student surname\n"
            "5. Display students passed\n"
            "6. Display students failed\n"
            "7. Display all student records\n"
            "8. Exit");
        printf("\nYour choice: ");
        scanf("%d", &x);

        if (x == 1) {
            printf("How many new students? ");
            scanf("%d", &std);
            ptr = (student *) malloc(std * sizeof(student));
            size1 = std;
            for (i = 0; i < std; i++) {
                printf("Enter detail of student #%d\n", (i + 1));
                ptr[i].id = i + 1;
                printf("Enter first name: ");
                scanf("%s", ptr[i].name);
                printf("Enter last name: ");
                scanf("%s", ptr[i].surname);
                printf("Enter semester: ");
                scanf("%d", &ptr[i].semester);
                printf("Enter grade: ");
                scanf("%f", &ptr[i].grade);
            }
        }

        else if (x == 3) {
            printf("Give the ID you wish to delete:\n");
            scanf("%d", &k);
            for (i = 0; i < std; i++) {
                if (k == ptr[i].id) {
                    std = std - 1;
                    size2 = std;
                    ptr[i] = ptr[i + 1];
                    memmove(ptr,ptr + (size1 - size2),size2 * sizeof(student));
                    ptr = realloc(ptr, std * sizeof(student));
                }
            }
        }

        else if (x == 7) {
            for (i = 0; i < std; i++) {
                printf("%d ", ptr[i].id);
                printf("%s ", ptr[i].name);
                printf("%s ", ptr[i].surname);
                printf("%d ", ptr[i].semester);
                printf("%f ", ptr[i].grade);
                printf("\n");
            }
        }
    }
}

I have tried adding another for loop in the if(x==3) under the if (k==ptr[i].id) to move everything but when it tries to print it either gives me the next students information 2 times or it just prints some random numbers and letters which doesn't help. I have also tried to change std. Sometimes upping it by 1 other times lowering it by 1. It still didn't give me the results I expected. I'm pretty sure I'm missing something pretty obvious but it's been a few hours and I still haven't found a way to make it work.

What I want from it is to read the ID. Compare it with ptr[i].id to see if it exists and if it does exist then I simply want to delete it and everything that comes with it. Basically overwrite ptr[i](which has the id I want to delete) with the next one which would be ptr[i+1]


问:
Rails: Error updating puma from 3.12 to 5.6
I am trying to update Puma from 3.12 to 5.6. But see the following error when i try to run rails s. I am currently on Mac Ventura.

Below are more details

```<code>Ruby 2.7
Rails 7.0.3

</code>```
```<code>    25: from bin/rails:4:in `<main>'
    24: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    23: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    22: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands.rb:18:in `<main>'
    21: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/command.rb:48:in `invoke'
    20: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/command/base.rb:87:in `perform'
    19: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor.rb:392:in `dispatch'
    18: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
    17: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
    16: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `perform'
    15: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `tap'
    14: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:137:in `block in perform'
    13: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    12: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    11: from /Users/usermac/Desktop/RailsDevelopement/backend/config/application.rb:7:in `<main>'
    10: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler.rb:174:in `require'
     9: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:58:in `require'
     8: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:58:in `each'
     7: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:69:in `block in require'
     6: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:69:in `each'
     5: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:74:in `block (2 levels) in require'
     4: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     3: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     2: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma.rb:13:in `<main>'
     1: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
/Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': dlopen(/Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma/puma_http11.bundle, 0x0009): symbol not found in flat namespace '_ERR_load_crypto_strings' - /Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma/puma_http11.bundle (LoadError)

</code>```

I have already tried the following

bundle config build.puma --with-cflags="-Wno-error=implicit-function-declaration"

uninstall openssl 3 and install openssl 1.0.2

Any help on how to fix this would be great.

Body:
I am trying to update Puma from 3.12 to 5.6. But see the following error when i try to run rails s. I am currently on Mac Ventura.

Below are more details

Ruby 2.7
Rails 7.0.3

    25: from bin/rails:4:in `'
    24: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    23: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    22: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands.rb:18:in `'
    21: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/command.rb:48:in `invoke'
    20: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/command/base.rb:87:in `perform'
    19: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor.rb:392:in `dispatch'
    18: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor/invocation.rb:127:in `invoke_command'
    17: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/thor-1.2.1/lib/thor/command.rb:27:in `run'
    16: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `perform'
    15: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:134:in `tap'
    14: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/railties-7.0.3/lib/rails/commands/server/server_command.rb:137:in `block in perform'
    13: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    12: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
    11: from /Users/usermac/Desktop/RailsDevelopement/backend/config/application.rb:7:in `'
    10: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler.rb:174:in `require'
     9: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:58:in `require'
     8: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:58:in `each'
     7: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:69:in `block in require'
     6: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:69:in `each'
     5: from /Users/usermac/.rvm/rubies/ruby-2.7.4/lib/ruby/2.7.0/bundler/runtime.rb:74:in `block (2 levels) in require'
     4: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     3: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
     2: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma.rb:13:in `'
     1: from /Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require'
/Users/usermac/.rvm/gems/ruby-2.7.4/gems/bootsnap-1.15.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': dlopen(/Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma/puma_http11.bundle, 0x0009): symbol not found in flat namespace '_ERR_load_crypto_strings' - /Users/usermac/.rvm/gems/ruby-2.7.4/gems/puma-5.6.5/lib/puma/puma_http11.bundle (LoadError)

I have already tried the following

bundle config build.puma --with-cflags="-Wno-error=implicit-function-declaration"

uninstall openssl 3 and install openssl 1.0.2

Any help on how to fix this would be great.


问:
JS form inputs not registering after changing tabs
I am using webpack to dynamically create a to do list website. I have tabs for different content. The default load tab has a form that can be filled out that sends data to local storage. Form inputs work fine upon load, however when I switch tabs and go back to the default page, form inputs are not registering.

I am logging every input from the form (text area input, date, priority) into console to see the expected output it will send to local storage. On default page load (my 'all tab') form inputs work fine, but they do not work when I switch back from any other tab that I have.

After switching tabs, the text area input logs as empty and so does the date. However, the priority radio buttons will still register correctly.

```<code>
</code>```
```<code>function makeForm() {
        const form = document.createElement('form');
        form.setAttribute('id', 'task-form');

        const textInput = document.createElement('textarea');
        textInput.setAttribute('id', 'task-input');
        textInput.required = 'true';
        textInput.placeholder = 'Enter task here';
        form.appendChild(textInput);

        const date = document.createElement('input');
        date.type = 'date';
        date.setAttribute('id', 'task-due-date');
        const dateLabel = document.createElement('label');
        dateLabel.setAttribute('for', 'due-date');
        dateLabel.textContent = 'Complete by:';
        form.appendChild(dateLabel);
        form.appendChild(date);

        const priorityDiv = makePriorityDiv();
        form.appendChild(priorityDiv);

        const buttonDiv = document.createElement('div');
        buttonDiv.classList.add('button-div');

        const addBtn = document.createElement('input');
        addBtn.type = 'submit';
        addBtn.value = 'Add';
        buttonDiv.appendChild(addBtn);

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = 'Cancel';
        cancelBtn.classList.add('form-btn');
        cancelBtn.addEventListener('click', cancel);
        buttonDiv.appendChild(cancelBtn);
        form.appendChild(buttonDiv);

        form.addEventListener('submit', addToLocalStorage);

        return form;
    }
</code>```
```<code>    function addToLocalStorage(e) {
        e.preventDefault();
        const parentDiv = e.target.parentElement.parentElement;

        inputValue = document.getElementById('task-input').value;
        dateValue = document.getElementById('task-due-date').value;
        priorityValue = document.querySelector('input[name="priority"]:checked').value;

        console.log(`before adding to local storage:
        input: ${inputValue}
        date: ${dateValue}
        priorty: ${priorityValue}`);

        document.getElementById('task-form').reset();

        parentDiv.classList.add('hidden');
    }
</code>```
```<code>
</code>```

Body:
I am using webpack to dynamically create a to do list website. I have tabs for different content. The default load tab has a form that can be filled out that sends data to local storage. Form inputs work fine upon load, however when I switch tabs and go back to the default page, form inputs are not registering.

I am logging every input from the form (text area input, date, priority) into console to see the expected output it will send to local storage. On default page load (my 'all tab') form inputs work fine, but they do not work when I switch back from any other tab that I have.

After switching tabs, the text area input logs as empty and so does the date. However, the priority radio buttons will still register correctly.

function makeForm() {
        const form = document.createElement('form');
        form.setAttribute('id', 'task-form');

        const textInput = document.createElement('textarea');
        textInput.setAttribute('id', 'task-input');
        textInput.required = 'true';
        textInput.placeholder = 'Enter task here';
        form.appendChild(textInput);

        const date = document.createElement('input');
        date.type = 'date';
        date.setAttribute('id', 'task-due-date');
        const dateLabel = document.createElement('label');
        dateLabel.setAttribute('for', 'due-date');
        dateLabel.textContent = 'Complete by:';
        form.appendChild(dateLabel);
        form.appendChild(date);

        const priorityDiv = makePriorityDiv();
        form.appendChild(priorityDiv);

        const buttonDiv = document.createElement('div');
        buttonDiv.classList.add('button-div');

        const addBtn = document.createElement('input');
        addBtn.type = 'submit';
        addBtn.value = 'Add';
        buttonDiv.appendChild(addBtn);

        const cancelBtn = document.createElement('button');
        cancelBtn.textContent = 'Cancel';
        cancelBtn.classList.add('form-btn');
        cancelBtn.addEventListener('click', cancel);
        buttonDiv.appendChild(cancelBtn);
        form.appendChild(buttonDiv);

        form.addEventListener('submit', addToLocalStorage);

        return form;
    }

    function addToLocalStorage(e) {
        e.preventDefault();
        const parentDiv = e.target.parentElement.parentElement;

        inputValue = document.getElementById('task-input').value;
        dateValue = document.getElementById('task-due-date').value;
        priorityValue = document.querySelector('input[name="priority"]:checked').value;

        console.log(`before adding to local storage:
        input: ${inputValue}
        date: ${dateValue}
        priorty: ${priorityValue}`);

        document.getElementById('task-form').reset();

        parentDiv.classList.add('hidden');
    }


问:
Node js return old data from twilio account to angular component
I tried to run function from Angular each 10 seconds to find out my twillio account balance.

When I run backend from cmd, first result is ok, then in the background cron send SMS on some mobile phone. But when function from Node is called after 10 seconds, it always return my first balacne before sending SMS on mobile phones. Does it have something common with cache?

My angular function to call service and Node js function

```<code>  getTwilioAccountBalance() {
      this.twilioService.getTwilioAccountBalance().subscribe({
        next: data => {
          console.log(data);
          this.accountBalance = Math.round((data.balance*0.94 + Number.EPSILON) * 100) / 100;
          console.log(this.accountBalance);
        },
        error: err => {
          console.log(err)
        }
      })
    }
</code>```

Node js function in controller what send balance from Twillio account

```<code>require('dotenv').config();

exports.getTwilioAccountBalance = (req, res) => {

const client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN)

client.balance.fetch()
  .then((data) => {
    const balance = Math.round(data.balance * 100) / 100;
    const currency = data.currency;
    console.log(`Your account balance is ${balance} ${currency}.`)

    res.status(200).send({
        balance
      })
  })
  .catch(function(error) {
    console.log(error);
  });

};
</code>```

If i wanna to receive current balance of my account, I have to turn off backend in cmd and run it again

Body:
I tried to run function from Angular each 10 seconds to find out my twillio account balance.

When I run backend from cmd, first result is ok, then in the background cron send SMS on some mobile phone. But when function from Node is called after 10 seconds, it always return my first balacne before sending SMS on mobile phones. Does it have something common with cache?

My angular function to call service and Node js function

  getTwilioAccountBalance() {
      this.twilioService.getTwilioAccountBalance().subscribe({
        next: data => {
          console.log(data);
          this.accountBalance = Math.round((data.balance*0.94 + Number.EPSILON) * 100) / 100;
          console.log(this.accountBalance);
        },
        error: err => {
          console.log(err)
        }
      })
    }

Node js function in controller what send balance from Twillio account

require('dotenv').config();

exports.getTwilioAccountBalance = (req, res) => {

const client = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN)

client.balance.fetch()
  .then((data) => {
    const balance = Math.round(data.balance * 100) / 100;
    const currency = data.currency;
    console.log(`Your account balance is ${balance} ${currency}.`)

    res.status(200).send({
        balance
      })
  })
  .catch(function(error) {
    console.log(error);
  });

};

If i wanna to receive current balance of my account, I have to turn off backend in cmd and run it again


问:
Spring scheduler job don't start
I implemented a job to run every minute but it never starts.

This is the module's main class

```<code>@SpringBootApplication
@Configuration
@Import({EventsConfig.class, SchedulingConfig.class})
@EnableScheduling
@EnableConfigurationProperties({ScheduleQueryProperties.class, ScheduleThreadPoolProperties.class})
public class EventsStarter {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventsStarter.class);

    public static void main(String[] args) {
       Security.addProvider(new BouncyCastleProvider());
        try {
            SSLUtil.turnOffSslChecking();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            LOGGER.error(e.getMessage(), e);
        }
        SpringApplication.run(EventsStarter.class, args);

    }
}
</code>```

This is my Scheduling class

```<code>@Slf4j
@Component
@EnableScheduling
public class BlockedAccountsAlarmSchedule {

    @Autowired
    private BlockedAccountsAlarmScheduleService blockedAccountsAlarmScheduleService;

    @LogProfiler
    @LogInfo(logResult = true)
    @Scheduled(cron = "${schedule.account.alarm.process-time}")
    @Trace(dispatcher = true)
    public void executeToProcess() {
        log.info("m=execute, msg=Job init");
        this.blockedAccountsAlarmScheduleService.processBlockAccountAlarm();
    }

}
</code>```

bootstrap.yml

```<code>schedule:
  account:
    alarm:
      process-time: "0 0/1 * * * *"
      thread-pool:
        name-prefix: schedule-job-executor
        core-pool-size: 1
        max-pool-size: 2
        queue-capacity: 1
        use-max-available-processors: false
      query:
        limit-size: 100
        execution-count: 3
        execute-until-end: true
</code>```

Application.yml

```<code>card-utils:
  activation:
    passwordBySms: false
  occurrence-report:
    upload-limit-days: 3
  account:
    credit:
      minimum-limit: 100
  overlimit:
    fee: 10.00
    percentage: 1.10

schedule:
  account:
    alarm:
      process-time: "0 0/1 * * * *"
      thread-pool:
        name-prefix: schedule-job-executor
        core-pool-size: 1
        max-pool-size: 2
        queue-capacity: 1
        use-max-available-processors: false
      query:
        limit-size: 100
        execution-count: 3
        execute-until-end: true
  integration:
    base-uri: "https://api.conductor.com.br/pier/v2/api"
</code>```

The application starts but the BlockedAccountsAlarmSchedule class
is not called at any time

Title: Spring scheduler job don't start

Body:
I implemented a job to run every minute but it never starts.

This is the module's main class

@SpringBootApplication
@Configuration
@Import({EventsConfig.class, SchedulingConfig.class})
@EnableScheduling
@EnableConfigurationProperties({ScheduleQueryProperties.class, ScheduleThreadPoolProperties.class})
public class EventsStarter {

    private static final Logger LOGGER = LoggerFactory.getLogger(EventsStarter.class);

    public static void main(String[] args) {
       Security.addProvider(new BouncyCastleProvider());
        try {
            SSLUtil.turnOffSslChecking();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            LOGGER.error(e.getMessage(), e);
        }
        SpringApplication.run(EventsStarter.class, args);

    }
}

This is my Scheduling class

@Slf4j
@Component
@EnableScheduling
public class BlockedAccountsAlarmSchedule {

    @Autowired
    private BlockedAccountsAlarmScheduleService blockedAccountsAlarmScheduleService;

    @LogProfiler
    @LogInfo(logResult = true)
    @Scheduled(cron = "${schedule.account.alarm.process-time}")
    @Trace(dispatcher = true)
    public void executeToProcess() {
        log.info("m=execute, msg=Job init");
        this.blockedAccountsAlarmScheduleService.processBlockAccountAlarm();
    }

}

bootstrap.yml

schedule:
  account:
    alarm:
      process-time: "0 0/1 * * * *"
      thread-pool:
        name-prefix: schedule-job-executor
        core-pool-size: 1
        max-pool-size: 2
        queue-capacity: 1
        use-max-available-processors: false
      query:
        limit-size: 100
        execution-count: 3
        execute-until-end: true

Application.yml

card-utils:
  activation:
    passwordBySms: false
  occurrence-report:
    upload-limit-days: 3
  account:
    credit:
      minimum-limit: 100
  overlimit:
    fee: 10.00
    percentage: 1.10

schedule:
  account:
    alarm:
      process-time: "0 0/1 * * * *"
      thread-pool:
        name-prefix: schedule-job-executor
        core-pool-size: 1
        max-pool-size: 2
        queue-capacity: 1
        use-max-available-processors: false
      query:
        limit-size: 100
        execution-count: 3
        execute-until-end: true
  integration:
    base-uri: "https://api.conductor.com.br/pier/v2/api"

The application starts but the BlockedAccountsAlarmSchedule class
is not called at any time


问:
is it same meaning that word of memory array and word of OS?
https://www.youtube.com/watch?v=eMCU7ccBkk4

in this video,
if there is 2^n * m bit memory, m means word size.

and as far as I know, when we calculate the memory size of 32-bit OS,
we calculate like this => 2^32 * 1 byte(8bit) = 4GB.
in 32-bit OS, 32 means word size. But according to the formula above, m = 8, so word size should be 8. it seems contradictory. what is wrong? what am i missing?


问:
How to programmaticaly unpin weifenluo.winformsUI form
I have an application that uses Weifenluo.WinformsUI.Docking. One panel, with the navigation menu in it, is initially displayed and is pinned. Pinned seems to be the default state.

My client would like the menu to be unpinned to give them more usable working area on-screen.

How can it be programmatically unpinned?


问:
How to call window object method in Cypress?
I'm trying to call this method "window._e2e_cookie_popup_actions.acceptAll()" which basically sets the cookie policy in local storage.
When I call this method on browser console, it works perfectly.
However, when I try this on Cypress, it says "TypeError: Cannot read properties of undefined (reading 'acceptAll')"

This is how I tried on Cypress

```<code> cy.window().then((window)=>{
    window._e2e_cookie_popup_actions.acceptAll()
 })
</code>```

Expection: If this method is called, the cookie should be set.

Thank you in advance!

Body:
I'm trying to call this method "window._e2e_cookie_popup_actions.acceptAll()" which basically sets the cookie policy in local storage.
When I call this method on browser console, it works perfectly.
However, when I try this on Cypress, it says "TypeError: Cannot read properties of undefined (reading 'acceptAll')"

This is how I tried on Cypress

 cy.window().then((window)=>{
    window._e2e_cookie_popup_actions.acceptAll()
 })

Expection: If this method is called, the cookie should be set.

Thank you in advance!


问:
Why does the generator loss diverge in my WGAN-GP
I am using a WGAN-GP for medical image generation and while training, I notice that the loss for the generator diverges to a high value while the loss for the discriminator is more or less the same as the training continues - Loss plot. I am not sure why that would happen.

I am using this code for the WGAN-GP. The only thing I changed in this implementation was to change the number of filters in the discriminator to 32 (or ngf/4).


问:
Pinescript cpde to validate the current buy/sell signal
I can't seem to make this work in pine script - to check if the current buy signal is at least 10 bars away from the previous buy signal. Anyone?

```<code>i_buy = (ST1_buy and ST2_buy and ema_buy and mfi_buy) or (ST3_buy and ST4_buy and ema_buy and mfi2_buy)
i_sell = (ST1_sell and ST2_sell and ema_sell and mfi_sell) or (ST3_sell and ST4_sell and ema_sell and mfi2_sell)

buy = i_buy and not i_buy[1]
sell = i_sell and not i_sell[1]
</code>```

tried so many combinations but did not work

Body:
I can't seem to make this work in pine script - to check if the current buy signal is at least 10 bars away from the previous buy signal. Anyone?

i_buy = (ST1_buy and ST2_buy and ema_buy and mfi_buy) or (ST3_buy and ST4_buy and ema_buy and mfi2_buy)
i_sell = (ST1_sell and ST2_sell and ema_sell and mfi_sell) or (ST3_sell and ST4_sell and ema_sell and mfi2_sell)

buy = i_buy and not i_buy[1]
sell = i_sell and not i_sell[1]

tried so many combinations but did not work


问:
Use Wild Char in JSON Formatting
I am new to JSON and working on formatting a calendar within Microsoft Lists. I hope what I'm asking is an easy fix!

Essentially, the goal is to highlight on the calendar when a meeting contains the word "Nick" even though the meetings have different names. (ex. Nick: Review, Nick: Email, Nick: FYI)

My code (generated by Microsoft) is below.

```<code>{
  "$schema": "//link removed",
  "additionalEventClass": {
    "operator": ":",
    "operands": [
      {
        "operator": "==",
        "operands": [
          "[$Title]",
          "Nick: Review"
        ]
      },
      "=if(@isSelected == true, 'sp-css-color-WhiteFont sp-css-backgroundColor-BgBlue' , 'sp-css-backgroundColor-BgCornflowerBlue sp-css-color-CornflowerBlueFont')",
      "=if(@isSelected == true, 'sp-css-color-WhiteFont sp-css-backgroundColor-BgGray' , 'sp-css-backgroundColor-BgLightGray sp-css-color-LightGrayFont')"
    ]
  }
}
</code>```

I have been googling for contains functions or something using an asterisk similar to what I've used in other languages, but I'm unclear on how to integrate.

Title: Use Wild Char in JSON Formatting

Body:
I am new to JSON and working on formatting a calendar within Microsoft Lists. I hope what I'm asking is an easy fix!

Essentially, the goal is to highlight on the calendar when a meeting contains the word "Nick" even though the meetings have different names. (ex. Nick: Review, Nick: Email, Nick: FYI)

My code (generated by Microsoft) is below.

{
  "$schema": "//link removed",
  "additionalEventClass": {
    "operator": ":",
    "operands": [
      {
        "operator": "==",
        "operands": [
          "[$Title]",
          "Nick: Review"
        ]
      },
      "=if(@isSelected == true, 'sp-css-color-WhiteFont sp-css-backgroundColor-BgBlue' , 'sp-css-backgroundColor-BgCornflowerBlue sp-css-color-CornflowerBlueFont')",
      "=if(@isSelected == true, 'sp-css-color-WhiteFont sp-css-backgroundColor-BgGray' , 'sp-css-backgroundColor-BgLightGray sp-css-color-LightGrayFont')"
    ]
  }
}

I have been googling for contains functions or something using an asterisk similar to what I've used in other languages, but I'm unclear on how to integrate.


问:
Keycloak password reset link still works after generating a second one
I am using Keycloak as an identity provider. I was testing the forget password flow and I noticed that if I try the forget password twice before setting the new password, two emails are sent. Everything ok. But then, I can use both links I get in the email inbox to reset the password.

The first link shouldn't work anymore after the second one is generated.
I tried to go over the keycloak options but I cannot find anything regarding invalidating the links after new ones are generated.


问:
How can i establish a connection to a db no using credentials every time
I'm working with several R files that need connect to database but server has timeout so timeout=inf is not functional

What i was looking for is something like this:
RMySQL Database connection

(I'm the only user in R, and in total users just a few)

Inserting in my .RProfile all what is needed (credentials) and only in the .r programs that connect and disconnect when were necessary

In .RProfile:

```<code>con <- dbConnect(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
         Server = "{host}", database = "db", UID = "userid",
         PWD = "pwd",
         Port = 1234)
</code>```

and in .R programs use something like this:

```<code>conn <- dbConnect(odbc::odbc(), group = "what i should use here?")

#using database
tbl(conn,"table")
#more code

dbDisconnect(conn)
</code>```

I was too looking for other option, pool

In .RProfile

```<code>library(pool)
pool<- dbPool(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
         Server = "{host}", database = "db", UID = "userid",
         PWD = "pwd",
         Port = 1234)

.Last <- function(){
poolClose(pool)
}
</code>```

But i'm not sure if it works or the previous option is better.

Body:
I'm working with several R files that need connect to database but server has timeout so timeout=inf is not functional

What i was looking for is something like this:
RMySQL Database connection

(I'm the only user in R, and in total users just a few)

Inserting in my .RProfile all what is needed (credentials) and only in the .r programs that connect and disconnect when were necessary

In .RProfile:

con <- dbConnect(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
         Server = "{host}", database = "db", UID = "userid",
         PWD = "pwd",
         Port = 1234)

and in .R programs use something like this:

conn <- dbConnect(odbc::odbc(), group = "what i should use here?")

#using database
tbl(conn,"table")
#more code

dbDisconnect(conn)

I was too looking for other option, pool

In .RProfile

library(pool)
pool<- dbPool(odbc::odbc(), Driver = "{MariaDB ODBC 3.1 Driver}",
         Server = "{host}", database = "db", UID = "userid",
         PWD = "pwd",
         Port = 1234)

.Last <- function(){
poolClose(pool)
}

But i'm not sure if it works or the previous option is better.


问:
Is that possible to download zoom recording from shared link programmatically? (javascript)
everyone.
I have a shared link for zoom cloud recording.

I want to download the recording and play it on my react app.

I have only the shared link. No others like meeting_id, access_token, download_url, download_token.

Is that possible?

Thanks.


问:
Google Calendar API authentication in Python working on localhost but not working in Production
I have checked my redirect URI's, they are working perfectly in localhost but in production on button click instead of going to the authentication page it redirects to the same page without displaying any error.

I tried to create a try except block to log any errors but even the log file was empty.

```<code>def create_workshop(request):
    try:
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        'static//client_secret_xxxx.json',
        scopes=['https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/calendar'])
        flow.redirect_uri = CALENDAR_REDIRECT_URI
        authorization_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true')
        return redirect(authorization_url)
    except Exception as e:
        logging.basicConfig(filename="testing.log",
                    format='%(asctime)s %(message)s',
                    filemode='w')
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        logger.error(e)
</code>```

I have looked at all the solutions, and it displayed the same code as solution but I'm not sure why isn't it redirecting.

Body:
I have checked my redirect URI's, they are working perfectly in localhost but in production on button click instead of going to the authentication page it redirects to the same page without displaying any error.

I tried to create a try except block to log any errors but even the log file was empty.

def create_workshop(request):
    try:
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        'static//client_secret_xxxx.json',
        scopes=['https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/calendar'])
        flow.redirect_uri = CALENDAR_REDIRECT_URI
        authorization_url, state = flow.authorization_url(
            access_type='offline',
            include_granted_scopes='true')
        return redirect(authorization_url)
    except Exception as e:
        logging.basicConfig(filename="testing.log",
                    format='%(asctime)s %(message)s',
                    filemode='w')
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        logger.error(e)

I have looked at all the solutions, and it displayed the same code as solution but I'm not sure why isn't it redirecting.


问:
Can I use multiple controllers when using resource controllers?
I have created a resource controller(devices, DeviceController).
Now I want to add in the devices.edit a dropdown menu from another table with which the model device has a relationship.

I tried to create a DropdownController which returns the status of the devices but the controller does not reach the view although I created a route.

But when I send the statusse via DeviceController then it works.

My question is do I have to send everything via the DeviceController or can I split it up?

The error is Undefined variable $status

```<code>//DropController
public function show(){

    $status = Status::all();
    return view('devices.edit',compact('status'));
}

// web.php
Route::get('devices.edit',[\App\Http\Controllers\DropController::class,'show']);
Route::resource('devices', DeviceController::class);

//devices.edit
<select name="ddStatus">
    @foreach($status as $state)
        <option value="{{ $state->id }}">{{ $state->Status_Name }}</option>
    @endforeach
</select></p>

</code>```

If I send the statuses in the DeviceController then it works, but I would like to manage the dropdown with a separate controller. Or is it ok to send such things also in the DeviceController? Because I thought you should separate that

Body:
I have created a resource controller(devices, DeviceController).
Now I want to add in the devices.edit a dropdown menu from another table with which the model device has a relationship.

I tried to create a DropdownController which returns the status of the devices but the controller does not reach the view although I created a route.

But when I send the statusse via DeviceController then it works.

My question is do I have to send everything via the DeviceController or can I split it up?

The error is Undefined variable $status

//DropController
public function show(){

    $status = Status::all();
    return view('devices.edit',compact('status'));
}

// web.php
Route::get('devices.edit',[\App\Http\Controllers\DropController::class,'show']);
Route::resource('devices', DeviceController::class);

//devices.edit
<select name="ddStatus">
    @foreach($status as $state)
        <option value="{{ $state->id }}">{{ $state->Status_Name }}</option>
    @endforeach
</select>

If I send the statuses in the DeviceController then it works, but I would like to manage the dropdown with a separate controller. Or is it ok to send such things also in the DeviceController? Because I thought you should separate that


问:
Hyper-V Disk Creation on a Different Host
I'm beginning to think this is not possible but I have to ask.  I have a Windows Server 2012R2 Datacenter server acting as a PDC and I have the Hyper-V role installed.  This server has 15T of disk space but not a lot of CPU or RAM.  I want to use it as a disk drive storage server for my VM Guest drives.

I also have a Server 2019 Core server that has more CPU power and 32G of RAM, but very little storage space.  I want to use this server as my VM host machine, but I want to build all the storage on the 2012R2 server, but everything I have tried has failed.  As expected, I can create VM guests if both the machine and disk is on this server, but if I try to create the disk on the other server it fails with an error similar to "Failed to create the virtual hard disk".

Is it just not possible to create the guest machine and disk on separate servers?  Is this because of the 2012R2 and 2019 server differences?  Is it possible and I just don't have the disk share setup properly?

Hyper-V is all new to me, it is a learning lab and I have a lot to learn.  I've spent hours reading and going through articles but I just haven't found what I'm looking for yet.  I think it's time I reach out to the experts and see it it is even possible first.

Thanks,
Tom

I can successfully create a guest if both the guest machine and disk are on the Host.  When I try to create the disk on a a different host, I get the "Failed to create the virtual hard disk" error.  I'm trying to maximize the use of the resources I have by splitting CPU/RAM on one host and Disk on another, but I am beginning to think it is not possible.


问:
"NameError: name 'torch' is not defined" but torch is installed and imported
I tried to install and import m3inference:

```<code>pip install m3inference
import m3inference
</code>```

But I get the following error, how could I fix it?

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-9-50ee37ff85fa> in <module>
----> 1 import m3inference

3 frames
/usr/local/lib/python3.8/dist-packages/m3inference/full_model.py in M3InferenceModel()
     10
     11 class M3InferenceModel(nn.Module):
---> 12     def __init__(self, device='cuda' if torch.cuda.is_available() else 'cpu'):
     13         super(M3InferenceModel, self).__init__()
     14

NameError: name 'torch' is not defined
</code>```

I tried to install and import torch before doing the same with m3inference.

Body:
I tried to install and import m3inference:

pip install m3inference
import m3inference

But I get the following error, how could I fix it?

NameError                                 Traceback (most recent call last)
<ipython-input-9-50ee37ff85fa> in <module>
----> 1 import m3inference

3 frames
/usr/local/lib/python3.8/dist-packages/m3inference/full_model.py in M3InferenceModel()
     10
     11 class M3InferenceModel(nn.Module):
---> 12     def __init__(self, device='cuda' if torch.cuda.is_available() else 'cpu'):
     13         super(M3InferenceModel, self).__init__()
     14

NameError: name 'torch' is not defined

I tried to install and import torch before doing the same with m3inference.


问:
Created an API but getting 511 network authentication error at client end
I am trying to create a simple web app, where I am using Go to create the backend and svelte to create the frontend. Backend is hosted on port 8080 and frontend on 5173. I used a node package 'localtunnel' to forward both the ports.
When I am sending a GET request on the forwarded backend port it is working fine but when I am using fetch(window.fetch) on the same from the svelte app it is giving 511 network authentication error. Please see the below codes:

Go Backend:

```<code>func enableCors(w *http.ResponseWriter) {

    (*w).Header().Set("Access-Control-Allow-Origin", "https://chilly-rabbits-film-146-196-44-202.loca.lt")
                                                     //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I am providing the forwarded address of svelte app (PORT: 5173)
}

// Wrapper handler function
func handleRequest() {
    handler := mux.NewRouter()
    handler.HandleFunc("/sant", argHandler).Methods("GET")
    log.Fatal(http.ListenAndServe(":8080", handler))
}

func argHandler(w http.ResponseWriter, r *http.Request) {
    enableCors(&w)
    w.Header().Set("content-type", "application/json")
        .
        .
        .
        var data Data
    _ = json.Unmarshal(file, &data)
        var sant string
        sant = <some data is assigned>
        json.NewEncoder(w).Encode(santa)

</code>```

Svelte frontend:

```<code><script>
  let name;
  async function fetchData() {

    const endpoint = "https://giant-words-help-146-196-44-202.loca.lt/sant";
                    //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ forwarded port of Backend API(PORT: 8080)
    const response = await fetch(endpoint, {
        "Content-Type": "application/json",
        Accept: "application/json",
    });
    name = await response.json();
  }
</script>
</code>```

Getting the following error:

GEThttps://giant-words-help-146-196-44-202.loca.lt/sant [HTTP/2 511 Network Authentication Required 1560ms]
If I open https://giant-words-help-146-196-44-202.loca.lt/sant once on a new browser tab then the whole thing some how starts to work. But for Each network who is accessing the app need to open the link once to access the app.

Could you please help me figuring this out.
Thanks in advance! :)

Body:
I am trying to create a simple web app, where I am using Go to create the backend and svelte to create the frontend. Backend is hosted on port 8080 and frontend on 5173. I used a node package 'localtunnel' to forward both the ports.
When I am sending a GET request on the forwarded backend port it is working fine but when I am using fetch(window.fetch) on the same from the svelte app it is giving 511 network authentication error. Please see the below codes:

Go Backend:

func enableCors(w *http.ResponseWriter) {

    (*w).Header().Set("Access-Control-Allow-Origin", "https://chilly-rabbits-film-146-196-44-202.loca.lt")
                                                     //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I am providing the forwarded address of svelte app (PORT: 5173)
}

// Wrapper handler function
func handleRequest() {
    handler := mux.NewRouter()
    handler.HandleFunc("/sant", argHandler).Methods("GET")
    log.Fatal(http.ListenAndServe(":8080", handler))
}

func argHandler(w http.ResponseWriter, r *http.Request) {
    enableCors(&w)
    w.Header().Set("content-type", "application/json")
        .
        .
        .
        var data Data
    _ = json.Unmarshal(file, &data)
        var sant string
        sant = <some data is assigned>
        json.NewEncoder(w).Encode(santa)

Svelte frontend:

Getting the following error:

GEThttps://giant-words-help-146-196-44-202.loca.lt/sant [HTTP/2 511 Network Authentication Required 1560ms]
If I open https://giant-words-help-146-196-44-202.loca.lt/sant once on a new browser tab then the whole thing some how starts to work. But for Each network who is accessing the app need to open the link once to access the app.

Could you please help me figuring this out.
Thanks in advance! :)


问:
Roblox script, doesn't work but doesn't show any errors
I'm making a baldi basics fan game in Roblox, and once you pick up the notebook, it checks when if the player has 7 coins (notebooks, placeholder name) and it doesn't work, it doesn't seem to show any errors in the script editor.

I tried this script:

```<code>script.Parent.ClickDetector.MouseClick:Connect(function(plr)
    plr.leaderstats.Coins.Value = plr.leaderstats.Coins.Value + 1
    script.Parent.Sound:Play()
        script.Parent:Remove()
        game.ServerStorage.artem.Parent = workspace
        game.Workspace.lobby:Stop()
        game.Workspace.artem_passive.Parent = game.ReplicatedStorage
        if plr.leaderstats.Coins.Value >= 7 then -- this is the part that doesn't work
                game.Workspace["ready up"]:Play()
                game.Workspace["invisible wall"].CanCollide = false
        end
end)

</code>```

There's also a leaderboard script i added in with, that is working.

```<code>game.Players.PlayerAdded:connect(function(plr)
    local f = Instance.new("Folder", plr)
    f.Name = "leaderstats"
    local coins = Instance.new("IntValue", f)
    coins.Name = "Coins"
    coins.Value = 0
end)
</code>```

Body:
I'm making a baldi basics fan game in Roblox, and once you pick up the notebook, it checks when if the player has 7 coins (notebooks, placeholder name) and it doesn't work, it doesn't seem to show any errors in the script editor.

I tried this script:

script.Parent.ClickDetector.MouseClick:Connect(function(plr)
    plr.leaderstats.Coins.Value = plr.leaderstats.Coins.Value + 1
    script.Parent.Sound:Play()
        script.Parent:Remove()
        game.ServerStorage.artem.Parent = workspace
        game.Workspace.lobby:Stop()
        game.Workspace.artem_passive.Parent = game.ReplicatedStorage
        if plr.leaderstats.Coins.Value >= 7 then -- this is the part that doesn't work
                game.Workspace["ready up"]:Play()
                game.Workspace["invisible wall"].CanCollide = false
        end
end)

There's also a leaderboard script i added in with, that is working.

game.Players.PlayerAdded:connect(function(plr)
    local f = Instance.new("Folder", plr)
    f.Name = "leaderstats"
    local coins = Instance.new("IntValue", f)
    coins.Name = "Coins"
    coins.Value = 0
end)


问:
Custom permalinks structure for custom posts
I have a SEO problem as the structure of the site on WordPress is squad.

The site has ordinary cutters and are custom. They are structurally interested in information, but not in the URL. The task of tie them. The solution has never been found on the Internet.

Example:

Page
https://website.com/page1
https://website.com/page2

Custom Post Type
https://website.com/custom/page1/post1
https://website.com/custom/page2/post2

I need cut /custom/ and put this post1 under page1 of that page and another posts under another pages.

In register_post_type I was made rewrite
`

```<code>'rewrite'             => [
                    'slug' => '/',
                    'with_front' => false
                    ],
</code>```

`
so this remove my /custom/. Can any say me where I can find guide how to transfer this custom_post_type under /page*/?

I tried change permalinks via permalinks plugin, but it doesn't solve my issue.

Body:
I have a SEO problem as the structure of the site on WordPress is squad.

The site has ordinary cutters and are custom. They are structurally interested in information, but not in the URL. The task of tie them. The solution has never been found on the Internet.

Example:

Page
https://website.com/page1
https://website.com/page2

Custom Post Type
https://website.com/custom/page1/post1
https://website.com/custom/page2/post2

I need cut /custom/ and put this post1 under page1 of that page and another posts under another pages.

In register_post_type I was made rewrite
`

'rewrite'             => [
                    'slug' => '/',
                    'with_front' => false
                    ],

`
so this remove my /custom/. Can any say me where I can find guide how to transfer this custom_post_type under /page*/?

I tried change permalinks via permalinks plugin, but it doesn't solve my issue.