问:
HTML parser in Python without using external libraries
I've been assigned a problem at university.

The problem is as follows:

I have to make a program, in a language of my choice(I decide on Python since I'm most comfortable in it), that takes an HTML file name as input, parses it(if such exists), and allows CRUD operations on it. The catch is that I can't use external libraries or packages, only ones that I've written.

How should I approach the parser?

I'd have to have a structure in which I can save the parsed data. I was thinking about a list of tuples, each tuple consisting of the opening tag, the content, and the closing tag(if there is one), or discarding the closing tags altogether and focusing on the opening ones and the content. About the parser, I was thinking to read the file's content into a string variable and try to separate the different tags and their content. I don't know, if either of those is a good idea, or if there is a better way that I haven't considered.

I'd appreciate any help. Thank you in advance!


来源: stackexchange

问:
Using JWT with socket.io
When i try to use JWT with socket.io it wont respsonse when i get connection. I dont get any errors, but i dont get any respsonse when doing things on localhost. The localstorage is empty also. Please help, i've tried everything:)

client.js

```<code>var socket = io('http://localhost:4000', {query: 'auth_token=THE_JWT_TOKEN'});
socket.on('error', function(err) {
  console.log("test")

  throw new Error(err);
});
// Connection succeeded
socket.on('success', function(data) {
  console.log(data.message);
  console.log('user info: ' + data.user);
  console.log('logged in: ' + data.user.logged_in)
})

</code>```

server.js

```<code>var io            = require("socket.io")(server);
var socketioJwt   = require("socketio-jwt");

// set authorization for socket.io
var io = require('socket.io')();
var jwtAuth = require('socketio-jwt-auth');
var jwt = require('jsonwebtoken')

// using middleware
io.use(jwtAuth.authenticate({

  secret: 'Your Secret',    // required, used to verify the token's signature
  algorithm: 'HS256'        // optional, default to be HS256
}, function(payload, done) {
  // done is a callback, you can use it as follows
  User.findOne({id: payload.sub}, function(err, user) {
    if (err) {

      // return error
      return done(err);
    }
    if (!user) {

      // return fail with an error message
      return done(null, false, 'user does not exist');
    }

    // return success with a user info
    return done(null, user);
  });
}));

io.on('connection', function(socket) {
  console.log('Authentication passed!');
  // now you can access user info through socket.request.user
  // socket.request.user.logged_in will be set to true if the user was authenticated
  socket.emit('success', {
    message: 'success logged in!',
    user: socket.request.user
  });

</code>```

ContentLicense: CC BY-SA 4.0

Title: Using JWT with socket.io

Body:
When i try to use JWT with socket.io it wont respsonse when i get connection. I dont get any errors, but i dont get any respsonse when doing things on localhost. The localstorage is empty also. Please help, i've tried everything:)

client.js

var socket = io('http://localhost:4000', {query: 'auth_token=THE_JWT_TOKEN'});
socket.on('error', function(err) {
  console.log("test")

  throw new Error(err);
});
// Connection succeeded
socket.on('success', function(data) {
  console.log(data.message);
  console.log('user info: ' + data.user);
  console.log('logged in: ' + data.user.logged_in)
})

server.js

var io            = require("socket.io")(server);
var socketioJwt   = require("socketio-jwt");

// set authorization for socket.io
var io = require('socket.io')();
var jwtAuth = require('socketio-jwt-auth');
var jwt = require('jsonwebtoken')

// using middleware
io.use(jwtAuth.authenticate({

  secret: 'Your Secret',    // required, used to verify the token's signature
  algorithm: 'HS256'        // optional, default to be HS256
}, function(payload, done) {
  // done is a callback, you can use it as follows
  User.findOne({id: payload.sub}, function(err, user) {
    if (err) {

      // return error
      return done(err);
    }
    if (!user) {

      // return fail with an error message
      return done(null, false, 'user does not exist');
    }

    // return success with a user info
    return done(null, user);
  });
}));

io.on('connection', function(socket) {
  console.log('Authentication passed!');
  // now you can access user info through socket.request.user
  // socket.request.user.logged_in will be set to true if the user was authenticated
  socket.emit('success', {
    message: 'success logged in!',
    user: socket.request.user
  });


问:
Access to XMLHttpRequest at 'URL' from origin 'chrome-extension' has been blocked by CORS policy
I'm building a Chrome extension that calls a JSON through AJAX. I don't know why CORS is blocking me. I'm always receiving errors like this:

Access to XMLHttpRequest at 'https://app.zanelo.io/chrome_extension/par12134/par12341243143' from origin 'chrome-extension://fkghhhffemehchbofpdjhnbfclnonemh' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my code:

manifest.json

```<code>{
  "manifest_version": 3,
  "name": "Zanelo Extension",
  "author": "Kim Ramirez",
  "description": "",
  "version": "1.0.0",
  "permissions": [
    "storage",
    "contextMenus"
  ],
  "minimum_chrome_version": "92",
  "action": {
    "default_title": "Zanelo Extension",
    "default_popup": "popup.html"
  },
  "web_accessible_resources": [{
      "resources": [ "zanelo_icon.png","cog.png" ],
      "matches": [ "<all_urls>" ]
  }]
}
</code>```

popup.html

```<code><!DOCTYPE html>
<html>
<head>
    <title>Zanelo Extension</title>
    <link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
    <img src='cog.png' width='30px' id='settingclickable'><br><br>
    <div id='homepagecontent'></div>
    <div id='settingscontent'>
        <input type='text' id='parameter1' placeholder='Parameter 1'><br><br>
        <input type='text' id='parameter2' placeholder='Parameter 2'><br><br>
        <button type='button' id='savebutton'>Save
    </div>
</body>
</html>
<script src="jquery-3.4.1.min.js"></script>
<script type="text/javascript"  src="popup.js"></script>
</code>```

popup.js

```<code>$.ajax({
          type: "GET",
          url: "https://app.zanelo.io/chrome_extension/par12134/par12341243143",
          success: function(data) {
              var obj = JSON.parse(data);
              alert(obj.html);
          },
          error: function(error) {
            console.log(error);
          }
});
</code>```

I'm trying to alert to test if AJAX call is working and data is coming through the Chrome extension. I really don't know why CORS is blocking me. Hoping to get help from anyone of you there. Thank you so much!

Body:
I'm building a Chrome extension that calls a JSON through AJAX. I don't know why CORS is blocking me. I'm always receiving errors like this:

Access to XMLHttpRequest at 'https://app.zanelo.io/chrome_extension/par12134/par12341243143' from origin 'chrome-extension://fkghhhffemehchbofpdjhnbfclnonemh' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my code:

manifest.json

{
  "manifest_version": 3,
  "name": "Zanelo Extension",
  "author": "Kim Ramirez",
  "description": "",
  "version": "1.0.0",
  "permissions": [
    "storage",
    "contextMenus"
  ],
  "minimum_chrome_version": "92",
  "action": {
    "default_title": "Zanelo Extension",
    "default_popup": "popup.html"
  },
  "web_accessible_resources": [{
      "resources": [ "zanelo_icon.png","cog.png" ],
      "matches": [ "<all_urls>" ]
  }]
}

popup.html

<!DOCTYPE html>

    <title>Zanelo Extension</title>
    <link rel="stylesheet" type="text/css" href="popup.css">

        <input type='text' id='parameter1' placeholder='Parameter 1'>

        <input type='text' id='parameter2' placeholder='Parameter 2'>

        <button type='button' id='savebutton'>Save

popup.js

$.ajax({
          type: "GET",
          url: "https://app.zanelo.io/chrome_extension/par12134/par12341243143",
          success: function(data) {
              var obj = JSON.parse(data);
              alert(obj.html);
          },
          error: function(error) {
            console.log(error);
          }
});

I'm trying to alert to test if AJAX call is working and data is coming through the Chrome extension. I really don't know why CORS is blocking me. Hoping to get help from anyone of you there. Thank you so much!


问:
GitHub Desktop client - Difference between Update from naster and Rebase Current Branch
I'm trying to understand what is difference between these two items in Branch menu Update from master and Rebase Current Branch

I tried both commands and it seems to me that they do the same thing - Rebase from master to current branch.


问:
Making Python script an Executable
I am trying to make a Python Script into a .exe, but whenever i try and run pyinstaller --onefile teststationtest.py i get this error

```<code>'pyinstaller' is not recognized as an internal or external command,
operable program or batch file.
</code>```

CMD says pyinstaller is not recognised. I have tried looked around my browser and tried things i have seen, but getting no where. I have uninstalled and re installed. I have added the pyinstaller.exe to PATH. Still comes up with that error though

Title: Making Python script an Executable

Body:
I am trying to make a Python Script into a .exe, but whenever i try and run pyinstaller --onefile teststationtest.py i get this error

'pyinstaller' is not recognized as an internal or external command,
operable program or batch file.

CMD says pyinstaller is not recognised. I have tried looked around my browser and tried things i have seen, but getting no where. I have uninstalled and re installed. I have added the pyinstaller.exe to PATH. Still comes up with that error though


问:
Unable to insert a List[Map[String, String]] to MongoDB via Scala
Having the following clause:

```<code>            collection.updateOne(
              Filters.and(myFilters: _*),
              Document(
                "$setOnInsert" -> Document(
                  "field" -> item.getAs[List[Map[String, String]]]("field")
                )
              ),
              UpdateOptions().upsert(true)
            )
</code>```

On the $setOnInsert clause it will complain with Cannot resolve overloaded method 'Document', and as far as I've been checking the method signature for a Document probably it isn't resolving it as a CanBeBsonElements.

Full trace of the error:

```<code>overloaded method value apply with alternatives:
  (underlying: org.mongodb.scala.bson.BsonDocument)org.mongodb.scala.bson.collection.immutable.Document <and>
  (elems: org.mongodb.scala.bson.BsonMagnets.CanBeBsonElements)org.mongodb.scala.bson.collection.immutable.Document <and>
  (elems: org.mongodb.scala.bson.BsonMagnets.CanBeBsonElement*)org.mongodb.scala.bson.collection.immutable.Document <and>
  (json: String)org.mongodb.scala.bson.collection.immutable.Document
 cannot be applied to ((String, List[Map[String,String]]))
                "$setOnInsert" -> Document(
</code>```

I've already inserted String and List[String] elements without any issue, but can't really figure out how to insert a List[Map[String, String]].

Body:
Having the following clause:

            collection.updateOne(
              Filters.and(myFilters: _*),
              Document(
                "$setOnInsert" -> Document(
                  "field" -> item.getAs[List[Map[String, String]]]("field")
                )
              ),
              UpdateOptions().upsert(true)
            )

On the $setOnInsert clause it will complain with Cannot resolve overloaded method 'Document', and as far as I've been checking the method signature for a Document probably it isn't resolving it as a CanBeBsonElements.

Full trace of the error:

overloaded method value apply with alternatives:
  (underlying: org.mongodb.scala.bson.BsonDocument)org.mongodb.scala.bson.collection.immutable.Document <and>
  (elems: org.mongodb.scala.bson.BsonMagnets.CanBeBsonElements)org.mongodb.scala.bson.collection.immutable.Document <and>
  (elems: org.mongodb.scala.bson.BsonMagnets.CanBeBsonElement*)org.mongodb.scala.bson.collection.immutable.Document <and>
  (json: String)org.mongodb.scala.bson.collection.immutable.Document
 cannot be applied to ((String, List[Map[String,String]]))
                "$setOnInsert" -> Document(

I've already inserted String and List[String] elements without any issue, but can't really figure out how to insert a List[Map[String, String]].


问:
Conver curl to http request
I have following curl:

curl --location --request PUT 'https://xxx/api/xxx' \ --header 'authorization: Token <API_TOKEN_HERE>' \ --form 'file="ZIP FILE BYTES HERE"'

Any idea how to conver to raw http request, especially "--form 'file="ZIP FILE BYTES HERE""

PUT /api/xxx HTTP/1.1 Host: xxx authorization: Token <API_TOKEN_HERE> ???

Get the answer similar to:
PUT /api/xxx HTTP/1.1 Host: xxx authorization: Token <API_TOKEN_HERE> ???

Title: Conver curl to http request


问:
NGINX Rate Limiting with high rates is not working without burst
I'm trying to set up nginx rate limiting with limit_req_zone and limit_req directives.

```<code>map $http_my_header $sample_key {
    default  "";
    "hello"  1;
}

limit_req_zone $sample_key zone=one:100m rate=30000000r/s;

server {
    listen          8020;
    server_name     localhost;

    limit_req_status 509;

    location / {
        limit_req_log_level notice;
        limit_req    zone=one;
        root   html;
    }
}
</code>```

With this configuration I expecting Nginx to be able to process lots of request per second. But after a some rate (about 1000rps) some requests are rejected.
Burst with nodelay is actually helps and all working as expected.
Problem is I do not understand why. According this article nginx rate limiting is based on time slots per millisecond. There are 30000 requests per time slot in my case. And it obviously cannot be overwhelmed.

So basically: rate 30000000r/s and no burst — ~1000rps, other are blocked. rate 3000r/s and burst=10 nodelay — ~3000rps. Why does nginx behave in that way?

Body:
I'm trying to set up nginx rate limiting with limit_req_zone and limit_req directives.

map $http_my_header $sample_key {
    default  "";
    "hello"  1;
}

limit_req_zone $sample_key zone=one:100m rate=30000000r/s;

server {
    listen          8020;
    server_name     localhost;

    limit_req_status 509;

    location / {
        limit_req_log_level notice;
        limit_req    zone=one;
        root   html;
    }
}

With this configuration I expecting Nginx to be able to process lots of request per second. But after a some rate (about 1000rps) some requests are rejected.
Burst with nodelay is actually helps and all working as expected.
Problem is I do not understand why. According this article nginx rate limiting is based on time slots per millisecond. There are 30000 requests per time slot in my case. And it obviously cannot be overwhelmed.

So basically: rate 30000000r/s and no burst — ~1000rps, other are blocked. rate 3000r/s and burst=10 nodelay — ~3000rps. Why does nginx behave in that way?


问:
SystemOutOfmemory in IIS
The server is Windows 2012R2 with IIS.

I have a website with about 100 applications (Folder Convert to application).

It was worked fine for 3 years and before the last windows updates.

After those updates even i have unistalled them, i have a strange problem with the error SystemOutOfMemory, in some apps, not the same every time, and it happens randomly through the day.
This is the error from the Event Viewer

```<code>      Event code: 3008
      Event message: A configuration error has occurred.
      Event time: 14/12/2022 1:08:36 μμ
      Event time (UTC): 14/12/2022 11:08:36 πμ
      Event ID: 2860d96182e74faa8a4a62e0e943e591
      Event sequence: 147
      Event occurrence: 1
      Event detail code: 0

      Application information:
      Application domain: /LM/W3SVC/10/ROOT/www.mysite.gr-161-133154865200911346
      Trust level: Full
      Application Virtual Path: /www.prana.gr
      Application Path: C:\inetpub\vhost\mydomain\httpdocs\www.mysite.gr\
      Machine name: VMI1110479

       Process information:
       Process ID: 3456
       Process name: w3wp.exe
       Account name: VMI1110479\IWPD_2(mycloud)

       Exception information:
       Exception type: ConfigurationErrorsException
       Exception message: Exception of type 'System.OutOfMemoryException' was thrown.
       at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String
       assemblyName, Boolean starDirective)
       at
       System.Web.Configuration.CompilationSection.
 LoadAllAssembliesFromAppDomainBinDirectory()
at System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai)
 at System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection
compConfig)
at System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir)
at
System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory
vdir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir,
VirtualPath virtualDir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext
context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp)
at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path)
at

Custom event details:
</code>```

(Sorry for the margins but i dont know how to make them right.)

When i am looking at the logs there are no any other errors before this error.

The apps are using a MySQL server database each other.

The MySQL server works fine.

I tried all the info i found about this error but nothing yet.

Can you help me?

Title: SystemOutOfmemory in IIS

Body:
The server is Windows 2012R2 with IIS.

I have a website with about 100 applications (Folder Convert to application).

It was worked fine for 3 years and before the last windows updates.

After those updates even i have unistalled them, i have a strange problem with the error SystemOutOfMemory, in some apps, not the same every time, and it happens randomly through the day.
This is the error from the Event Viewer

      Event code: 3008
      Event message: A configuration error has occurred.
      Event time: 14/12/2022 1:08:36 μμ
      Event time (UTC): 14/12/2022 11:08:36 πμ
      Event ID: 2860d96182e74faa8a4a62e0e943e591
      Event sequence: 147
      Event occurrence: 1
      Event detail code: 0

      Application information:
      Application domain: /LM/W3SVC/10/ROOT/www.mysite.gr-161-133154865200911346
      Trust level: Full
      Application Virtual Path: /www.prana.gr
      Application Path: C:\inetpub\vhost\mydomain\httpdocs\www.mysite.gr\
      Machine name: VMI1110479

       Process information:
       Process ID: 3456
       Process name: w3wp.exe
       Account name: VMI1110479\IWPD_2(mycloud)

       Exception information:
       Exception type: ConfigurationErrorsException
       Exception message: Exception of type 'System.OutOfMemoryException' was thrown.
       at System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String
       assemblyName, Boolean starDirective)
       at
       System.Web.Configuration.CompilationSection.
 LoadAllAssembliesFromAppDomainBinDirectory()
at System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai)
 at System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection
compConfig)
at System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir)
at
System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory
vdir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory vdir,
VirtualPath virtualDir, Boolean ignoreErrors)
at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)
at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext
context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)
at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound)
at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp)
at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)
at System.Web.UI.PageHandlerFactory.GetHandler(HttpContext context, String requestType, String virtualPath, String path)
at

Custom event details:

(Sorry for the margins but i dont know how to make them right.)

When i am looking at the logs there are no any other errors before this error.

The apps are using a MySQL server database each other.

The MySQL server works fine.

I tried all the info i found about this error but nothing yet.

Can you help me?


问:
How to add "Create table" option in editor using React.js
I am working with React.js and Next.js and I am integrating an editor. What I want is to add a "Create table" option in my editor.

How can i do this? I've researched and found following link, that shows that there is option to add "Table" (Create but I don't know how to use "Create Table" in my editor. How can I add this feature to my editor?

https://ej2.syncfusion.com/react/documentation/rich-text-editor/toolbar/#custom-tool

Here is my current code

const modules = {
  toolbar: [
    [{ header: '1' }, { header: '2' }, { header: '3' }, { font: [] }],
    [{ size: [] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [
      { list: 'ordered' },
      { list: 'bullet' },
      { indent: '-1' },
      { indent: '+1' },
    ],
    ['link', 'image', 'video'],
    ['clean'],

  ],
  clipboard: {
    // toggle to add extra line breaks when pasting HTML:
    matchVisual: false,
  },
}
```


问:
static_cast to Universal Reference
I'm new to modern c++, and got messed up with value categories.
There is discusssion about 'forward＜T＞ vs static_cast<T&&>'
Which says the purpose of using forward is to write clean code.

My question is

What are the differences of static_cast＜T＞ and static_cast<T&&> if they are used in template?

Probably this is extended question. Why the direct use of static_cast＜T＞ works fine unlike static_cast＜T＞ in customized _forward function?

```<code>#include <iostream>
using namespace std;

void printInt(int& i) { cout << "lvalue reference: " << i << endl; }
void printInt(int&& i) { cout << "rvalue reference: " << i << endl; }

/* std::forward
*
* template<class _Ty>
*   _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>& _Arg) noexcept
*   {   // forward an lvalue as either an lvalue or an rvalue
*   return (static_cast<_Ty&&>(_Arg));
*   }
*
* template<class _Ty>
*   _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>&& _Arg) noexcept
*   {   // forward an rvalue as an rvalue
*   static_assert(!is_lvalue_reference_v<_Ty>, "bad forward call");
*   return (static_cast<_Ty&&>(_Arg));
*   }
*/

template<class T>
T&& _forward(typename remove_reference<T>::type& arg) {
    return static_cast<T>(arg);
}

template<typename T>
void test(T&& x) {
    printInt(x);                    // x itself is lvalue
    printInt(std::move(x));         // convert x into rvalue
    printInt(std::forward<T>(x));   // inference reference type
    printInt(static_cast<T&&>(x));

    printInt(_forward<T>(x));
    printInt(static_cast<T>(x));
}

int main() {
    int a = 5;
    cout << "pass lvalue" << endl;
    test(a);

    cout << "pass rvalue" << endl;
    test(10);
}

</code>```

[output]

pass lvalue

lvalue reference: 5

rvalue reference: 5

lvalue reference: 5

lvalue reference: 5

lvalue reference: 5

lvalue reference: 5

pass rvalue

lvalue reference: 10

rvalue reference: 10

rvalue reference: 10

rvalue reference: 10

rvalue reference: 17823636

rvalue reference: 10

```<code>    printInt(x);                    // x itself is lvalue
    printInt(std::move(x));         // convert x into rvalue
    printInt(std::forward<T>(x));   // inference reference type
    printInt(static_cast<T&&>(x));
</code>```

works as expected.

```<code>    printInt(_forward<T>(x));
    printInt(static_cast<T>(x));
</code>```

However, why does static_cast＜T＞(x) works same with static_cast<T&&>(x)?
It seems like it should print out rvalue only.
And why the case using _forward prints dummy value?

I just guess, maybe, xvalue is relevant with these results. But cannot explain clearly.

Title: static_cast to Universal Reference

Body:
I'm new to modern c++, and got messed up with value categories.
There is discusssion about 'forward＜T＞ vs static_cast<T&&>'
Which says the purpose of using forward is to write clean code.

My question is

What are the differences of static_cast＜T＞ and static_cast<T&&> if they are used in template?

Probably this is extended question. Why the direct use of static_cast＜T＞ works fine unlike static_cast＜T＞ in customized _forward function?

#include <iostream>
using namespace std;

void printInt(int& i) { cout << "lvalue reference: " << i << endl; }
void printInt(int&& i) { cout << "rvalue reference: " << i << endl; }

/* std::forward
*
* template<class _Ty>
*   _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>& _Arg) noexcept
*   {   // forward an lvalue as either an lvalue or an rvalue
*   return (static_cast<_Ty&&>(_Arg));
*   }
*
* template<class _Ty>
*   _NODISCARD constexpr _Ty&& forward(remove_reference_t<_Ty>&& _Arg) noexcept
*   {   // forward an rvalue as an rvalue
*   static_assert(!is_lvalue_reference_v<_Ty>, "bad forward call");
*   return (static_cast<_Ty&&>(_Arg));
*   }
*/

template<class T>
T&& _forward(typename remove_reference<T>::type& arg) {
    return static_cast<T>(arg);
}

template<typename T>
void test(T&& x) {
    printInt(x);                    // x itself is lvalue
    printInt(std::move(x));         // convert x into rvalue
    printInt(std::forward<T>(x));   // inference reference type
    printInt(static_cast<T&&>(x));

    printInt(_forward<T>(x));
    printInt(static_cast<T>(x));
}

int main() {
    int a = 5;
    cout << "pass lvalue" << endl;
    test(a);

    cout << "pass rvalue" << endl;
    test(10);
}

[output]

pass lvalue

lvalue reference: 5

rvalue reference: 5

lvalue reference: 5

lvalue reference: 5

lvalue reference: 5

lvalue reference: 5

pass rvalue

lvalue reference: 10

rvalue reference: 10

rvalue reference: 10

rvalue reference: 10

rvalue reference: 17823636

rvalue reference: 10

    printInt(x);                    // x itself is lvalue
    printInt(std::move(x));         // convert x into rvalue
    printInt(std::forward<T>(x));   // inference reference type
    printInt(static_cast<T&&>(x));

works as expected.

    printInt(_forward<T>(x));
    printInt(static_cast<T>(x));

However, why does static_cast＜T＞(x) works same with static_cast<T&&>(x)?
It seems like it should print out rvalue only.
And why the case using _forward prints dummy value?

I just guess, maybe, xvalue is relevant with these results. But cannot explain clearly.


问:
Pandas csv export decimal values not correct
Using python with pandas.
When exporting a dataframe to CSV all my decimal values become integers. For Example:

12.5487 become 125487

Which is no big deal for further calculations.

I tried :

```<code>df.to_csv(r'C:\export.csv',index=False, header=True,sep=',',decimal='.')
</code>```

Won't work. I also tried to use the

.astype(float)

Also no results.

This is the output of my df which shows the decimals as they should.

GEG_BIO_EFFL
GEG_BUF1_LT_01
BIO1_P01_OFF

7003
5.895833
90

7004
5.789521
90

6894
5.654896
90

Can someone please tell me how to do this properly

Body:
Using python with pandas.
When exporting a dataframe to CSV all my decimal values become integers. For Example:

12.5487 become 125487

Which is no big deal for further calculations.

I tried :

df.to_csv(r'C:\export.csv',index=False, header=True,sep=',',decimal='.')

Won't work. I also tried to use the

.astype(float)

Also no results.

This is the output of my df which shows the decimals as they should.

GEG_BIO_EFFL
GEG_BUF1_LT_01
BIO1_P01_OFF

7003
5.895833
90

7004
5.789521
90

6894
5.654896
90

Can someone please tell me how to do this properly


问:
dll for VBA looks empty
I created a class library in vb.net, but the classes in the object browser seem to be empty (no attributes, functions).

I made the Assembly Com-Visible and registered it for COM-Interop.

I signed assembly.

In VBA referenced the tlb-File

Title: dll for VBA looks empty


问:
Testing iron-session `withIronSessionSsr` that uses `context` in NextJs, React, and Jest
So I have this NextJs utility file function below that returns an imported function. Then that imported function accepts a handler, that uses context, as an argument.

```<code>import { ironSessionUtil } from './anotherUtil'

const checker = () =>
  ironSessionUtil(({ req }) => {
    const { user } = req.session
    if (!user) {
      return {
        redirect: { destination: '/welcome', permanent: false }
      }
    }

    return { props: { details: user.details } }
  })

export default checker
</code>```

So far I've tried just calling the method but it returns an Async Function.

```<code>it('should return props', () => {
  const result = checker()
  console.log('result >> ', result)
})
</code>```

This returns:

[AsyncFunction: nextGetServerSidePropsHandlerWrappedWithIronSession]

I've been scouring the web on how to test this. Would you suggest refactors to make this more testable? Or do you know how this can be done in Jest?

Body:
So I have this NextJs utility file function below that returns an imported function. Then that imported function accepts a handler, that uses context, as an argument.

import { ironSessionUtil } from './anotherUtil'

const checker = () =>
  ironSessionUtil(({ req }) => {
    const { user } = req.session
    if (!user) {
      return {
        redirect: { destination: '/welcome', permanent: false }
      }
    }

    return { props: { details: user.details } }
  })

export default checker

So far I've tried just calling the method but it returns an Async Function.

it('should return props', () => {
  const result = checker()
  console.log('result >> ', result)
})

This returns:

[AsyncFunction: nextGetServerSidePropsHandlerWrappedWithIronSession]

I've been scouring the web on how to test this. Would you suggest refactors to make this more testable? Or do you know how this can be done in Jest?


问:
ffmpeg header how to allow certain domain
so im new to ffmpeg , i want to restrict my streams be allowed only to my website

stream server is nginx and mywebsite is written in php , the stream server is different from mywebsite host , so i want to restrict stream requests only to my website domain.

i have applied this command is not working , i have searched in google didnt found much information on ffmpeg headers command.

ffmpeg  -headers "Accept-Encoding:gzip, deflate, br" -headers "Accept-Language:zh-CN,zh;q=0.9,en;q=0.8" -headers "Origin:https://mywebsite.com"  -headers "Referer:https://mywebsite.com"

appreciate your support


问:
Not getting value for the selected items using EJS multi select dropdown Syncfusion
I am using multi select dropdown using ejs Syncfusion. I am not able to retrieve value for selected items. I need the items to do further filtering. Code for same is below

<ejs-multiselect id='multiselectelement' (ngModelChange)="OnChangeair($event)" [(ngModel)]="value" [dataSource]='assetData' [fields]='fields' ></ejs-multiselect>```

Using the item i need to cascade another dropdown. Any help would be appreciated.

Body:
I am using multi select dropdown using ejs Syncfusion. I am not able to retrieve value for selected items. I need the items to do further filtering. Code for same is below

<ejs-multiselect id='multiselectelement' (ngModelChange)="OnChangeair($event)" [(ngModel)]="value" [dataSource]='assetData' [fields]='fields' ></ejs-multiselect>

Using the item i need to cascade another dropdown. Any help would be appreciated.


问:
How to access Instagram Graph API and use Instagram webhooks?
I'm trying to create an app in which I would like to display user feeds from social media apps like Instagram. I want the data to be as live as possible so I tried to integrate Instagram Webhooks. I have created a server side application with Instagram's authentication and a callback url for webhooks through which I want to fetch data from Instagram and then store it in a database.

I have been going through the Official documentation. I was able to get User id, name, comments through Instagram API and I have also subscribed Instagram's webhooks in my meta developer's application. It didn't throw any error but when I like or comment on my post I couldn't get any object in the callback URL. I'm completely new to this so It would be great if someone could explain me how to do this?


问:
Redirect Private Wordpress Posts to the url held in a specific custom field on the taxonomy for that post

We would like to keep the ideas we have previously presented to (non logged in) clients, but which are no longer "current". We set them to being private WP posts, so that they are no longer available to non logged in users. However, we would like to redirect anyone who clicks on that original link to a page which shows all of the currently active ideas instead.

Research led me to the solution below, but in our case we need to redirect to a specific url in each case. Our theme (the amazing Total theme from WP Explorer/AJ) does have a field for the redirect url to be entered at post level, but actually the value of the url is determined by the value of a custom taxonomy on a post ie all posts with that Taxonomy should redirect to the same url in all cases.

```<code>add_action('template_redirect', 'your_theme_private_posts_redirect', 99);

function your_theme_private_posts_redirect()
{
    if (is_single() && 'private' == get_post_status(get_the_ID())) {
        wp_safe_redirect(home_url());
        exit();
    }
}

Credit https://stackoverflow.com/questions/68954429/wordpress-how-to-redirect-private-custom-post-types
</code>```

I understand that the above code would redirect all private posts to the home url, but how can I adapt it to do the following:

a) Only to apply to non logged in users and b)to set the url to be the value held in the redirect field on the post OR (better still) a custom field on the agency_artist custom taxonomy for that post. Hoping someone can help!

Body:
We would like to keep the ideas we have previously presented to (non logged in) clients, but which are no longer "current". We set them to being private WP posts, so that they are no longer available to non logged in users. However, we would like to redirect anyone who clicks on that original link to a page which shows all of the currently active ideas instead.

Research led me to the solution below, but in our case we need to redirect to a specific url in each case. Our theme (the amazing Total theme from WP Explorer/AJ) does have a field for the redirect url to be entered at post level, but actually the value of the url is determined by the value of a custom taxonomy on a post ie all posts with that Taxonomy should redirect to the same url in all cases.

add_action('template_redirect', 'your_theme_private_posts_redirect', 99);

function your_theme_private_posts_redirect()
{
    if (is_single() && 'private' == get_post_status(get_the_ID())) {
        wp_safe_redirect(home_url());
        exit();
    }
}

Credit https://stackoverflow.com/questions/68954429/wordpress-how-to-redirect-private-custom-post-types

I understand that the above code would redirect all private posts to the home url, but how can I adapt it to do the following:

a) Only to apply to non logged in users and b)to set the url to be the value held in the redirect field on the post OR (better still) a custom field on the agency_artist custom taxonomy for that post. Hoping someone can help!


问:
How to change date format in DateRangePicker?
I am using DateRangePicker in my application. Everything is working fine only facing issue in date format. My server date format is "mm-dd-yyyy" and I want to show date in "DD-MMM-YYYY" format after selecting date from date picker. Below is my code and I have tried to change date format but still it is showing date in same as my system date format.</p>
```<code><script >
  $(function() {
    $("#newmaindate0").singleDatePicker();
    $(".ui-singleDatePicker").addClass("notranslate");
});
$.fn.singleDatePicker = function() {
    $("#newmaindate0").on("apply.daterangepicker", function(e, picker) {
        picker.element.val(picker.startDate.format("MM-DD-YYYY"));
        date_calc("#newmaindate0", "#newduedate0", "#newfreq0", "#newperiod0");
    });
    var date = new Date();
    return $(this).daterangepicker({
        showDropdowns: true,
        minDate: new Date(new Date().setDate(new Date().getDate() - 2)),
        todayHighlight: true,
        autoclose: true,
        singleDatePicker: true,
        autoUpdateInput: false,
        locale: {
            format: "DD-MMM-YYYY",
        },
    });
};
< /script>
</code>```


问:
MariaDB/mysqld is blocked by `docker-default` AppArmor profile
I had a working MySQL install and I tried to migrate it to MariaDB. I also have Docker, which seems to block /usr/sbin/mysqld via AppArmor.

To be clear, I’m not using Docker currently (but I’d like to not have to remove it since I will be using it soon).

The problem I’m having is when I’m trying to load my project, served by good old Apache, in the browser. I’m getting a SQLSTATE[HY000] [2002] No such file or directory error message.

The workaround right now is to force AppArmor to unblock mysqld:

```<code>sudo apparmor_parser -v -R /etc/apparmor.d/usr.sbin.mysqld && sudo systemctl restart mariadb
</code>```

This works, but I have to redo it after every system boot.

aa-status clearly shows who the culprit is:

```<code>4 processes are in enforce mode.
   ...
   /usr/sbin/mysqld (2960) docker-default
</code>```

After running the workaround above, this line disappears from aa-status and everything works perfectly.

How can I permanently disable this "protection" from the docker-default profile?

Body:
I had a working MySQL install and I tried to migrate it to MariaDB. I also have Docker, which seems to block /usr/sbin/mysqld via AppArmor.

To be clear, I’m not using Docker currently (but I’d like to not have to remove it since I will be using it soon).

The problem I’m having is when I’m trying to load my project, served by good old Apache, in the browser. I’m getting a SQLSTATE[HY000] [2002] No such file or directory error message.

The workaround right now is to force AppArmor to unblock mysqld:

sudo apparmor_parser -v -R /etc/apparmor.d/usr.sbin.mysqld && sudo systemctl restart mariadb

This works, but I have to redo it after every system boot.

aa-status clearly shows who the culprit is:

4 processes are in enforce mode.
   ...
   /usr/sbin/mysqld (2960) docker-default

After running the workaround above, this line disappears from aa-status and everything works perfectly.

How can I permanently disable this "protection" from the docker-default profile?


问:
How can we add request header in safari browser automation using selenium webdriver in javascript?
We dont have add Extension method support in safari options of webdriver. How can we add the request header in safari browser?

How can we add request header in safari browser automation using selenium webdriver


问:
Problem with a array overwriting another in a structure in C
Ok guys, I have a problem.
I'm quite a beginner in C and I have to code a Sokoban game in C (in terminal).
I use some structures to store my variables and scene, here they are (there are another one but it's just a vector2)  :

```<code>struct carte //couldn't use map cause of c++
{
    char ** carte;
    int line;
    int column;
};
typedef struct carte carte;

struct gameObject
{
    char sprite;
    vect2 * pos;
};
typedef struct gameObject gameObject;

struct interupteur
{
    gameObject gO;
    int active; //bool
};
typedef struct interupteur interupteur;

struct scene
{
    carte * carte;
    gameObject * chara;
    //array containing all the boxes
    gameObject * box;
    //array containing the switches
    interupteur * inter;
    int nbInter;
    int nbBox;
};
typedef struct scene scene;
</code>```

I use a function to serialize my scene from a txt file. It works except for one thing : the inter (switch) array and the box array have the same content meaning the switch from my map (see below) override the box. So from the following txt I get to this :

```<code>in the txt     results
######         ######
#    #         #    #
#P  C#         #P   #
#    #         #    #
#   I#         #   I#
######         ######

</code>```

So here is how I allocated my scene and my two arrays (let's forget the error case of NULL pointers) :

```<code>scene * scene1 = malloc(sizeof(scene));
scene1->box = malloc(scene1->nbBox*sizeof(gameObject));
scene1->inter = malloc(scene1->nbInter*sizeof(interupteur));
</code>```

So I store the content of the txt in a 2d array of char and replace the P (player), C (box) and I (switch) with a space and store them elsewhere in my scene struct.

```<code>    for(int i = 0 ; i < scene1->carte->ligne ; i++)
    {
        for(int j = 0 ; j < scene1->carte->colonne ; j++)
        {
            fscanf(f,"%c",&(scene1->carte->carte[i][j]));
            if(scene1->carte->carte[i][j] == 'P')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->chara->pos->x = i;
                scene1->chara->pos->y = j;
                scene1->chara->sprite = 'P';
            }
            else if(scene1->carte->carte[i][j] == 'I')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->inter[k2].gO.pos->x = i;
                scene1->inter[k2].gO.pos->y = j;
                scene1->inter[k2].gO.sprite = 'I';
                k1++;
            }
            else if(scene1->carte->carte[i][j] == 'C')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->box[k1].pos->x = i;
                scene1->box[k1].pos->y = j;
                scene1->box[k1].sprite = 'C';
                k1++;
            }
</code>```

I checked and it doesn't come from my output function. It come from my serialization function, the box is here until the function read the switch and override it. I also checked the address of the two arrays and they're different.
At first I was thinking it was a padding issue but I don't use union so I really don't know. I searched on internet and didn't find anything. Can somebody explain me why I have this problem ?
I code on Windows 10 using code blocks.

PS : Excuse me if my post isn't clear it is my first one and please excuse my English it isn't my native language.

I tried to change the order of the if/else if but it didn't change the overwriting (but create quite a mess). Expect that I didn't tried much more because I really don't see where the issue come from.

Edit : Here is my full code, you can use it as a minimal exemple (I don't know if it is minimal enough) :

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

struct vect2
{
    int x;
    int y ;
};
typedef struct vect2 vect2;

struct carte //couldn't use map cause of c++
{
    char ** carte;
    int line;
    int column;
};
typedef struct carte carte;

struct gameObject
{
    char sprite;
    vect2 * pos;
};
typedef struct gameObject gameObject;

struct interupteur
{
    gameObject gO;
    int active; //bool
};
typedef struct interupteur interupteur;

struct scene
{
    carte * carte;
    gameObject * chara;
    //array containing all the boxes
    gameObject * box;
    //array containing the switches
    interupteur * inter;
    int nbInter;
    int nbBox;
};
typedef struct scene scene;

scene * Update(scene * scene1)
{
    int k1 = 0, k2 = 0;
    for(int i = 0 ; i< scene1->carte->line;i++)
    {
        for(int j = 0 ; j < scene1->carte->column ; j++)
        {
            if(scene1->inter[k2].gO.pos->x == i && scene1->inter[k2].gO.pos->y == j)
            {
                printf("%c",scene1->inter[k1].gO.sprite);
                k2++;
            }
            else if(scene1->chara->pos->x == i && scene1->chara->pos->y == j)
            {
                printf("%c",scene1->chara->sprite);
            }
            else if(scene1->box[k1].pos->x == i && scene1->box[k1].pos->y == j)
            {
                printf("%c",scene1->box[k1].sprite);
                k1++;
            }
            else
                printf("%c",scene1->carte->carte[i][j]);
        }
    }
    return scene1;
}

scene * SerialMap(const char * path)
{
    scene * scene1 = malloc(sizeof(scene));
    scene1->carte = malloc(sizeof(carte));
    FILE * f =  fopen(path,"r+");

    //Look for dimension of the map, assuming the lines have the same lentgh, count box and switch
    scene1->carte->column = 0;
    scene1->carte->line = 0;
    char c;
    int k = 0;
    scene1->nbInter = 0;
    scene1->nbBox = 0;
    for(c = fgetc(f); c != EOF ; c = fgetc(f))
    {
        if(c == '\n')
        {
            scene1->carte->column = k;
            scene1->carte->line++;
            k = 0;
        }
        if(c == 'C')
            scene1->nbBox++;
        if(c == 'I')
            scene1->nbInter++;
        k++;
    }
    rewind(f);

    //Alloc map array
    scene1->carte->carte = malloc(scene1->carte->line * sizeof(char *));
    for(int i = 0 ; i < scene1->carte->line ; i++)
        scene1->carte->carte[i] = malloc(scene1->carte->column * sizeof(char));

    //Alloc switch and box array
    scene1->box = malloc(scene1->nbBox*sizeof(gameObject));
    scene1->inter = malloc(scene1->nbInter*sizeof(interupteur));
    scene1->chara = malloc(sizeof(gameObject));
    scene1->chara->pos = malloc(sizeof(vect2));

    //Serial map in 2d array and store box, switch and player
    int k1 = 0, k2 = 0; //k1 is used for the box tab and k2 for the swith tab
    for(int i = 0 ; i < scene1->carte->line ; i++)
    {
        for(int j = 0 ; j < scene1->carte->column ; j++)
        {
            fscanf(f,"%c",&(scene1->carte->carte[i][j]));
            if(scene1->carte->carte[i][j] == 'P')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->chara->pos->x = i;
                scene1->chara->pos->y = j;
                scene1->chara->sprite = 'P';
            }
            else if(scene1->carte->carte[i][j] == 'I')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->inter[k2].gO.pos->x = i;
                scene1->inter[k2].gO.pos->y = j;
                scene1->inter[k2].gO.sprite = 'I';
                k2++;
            }
            else if(scene1->carte->carte[i][j] == 'C')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->box[k1].pos->x = i;
                scene1->box[k1].pos->y = j;
                scene1->box[k1].sprite = 'C';
                k1++;
            }
        }
    }

    fclose(f);
    return scene1;
}

int main(int argc, char ** argv)
{
    scene * gamescene = SerialMap(argv[1]);
    gamescene  = Update(gamescene);
    return 0;
}

</code>```

You can use the example I gave in the second code block.

Body:
Ok guys, I have a problem.
I'm quite a beginner in C and I have to code a Sokoban game in C (in terminal).
I use some structures to store my variables and scene, here they are (there are another one but it's just a vector2)  :

struct carte //couldn't use map cause of c++
{
    char ** carte;
    int line;
    int column;
};
typedef struct carte carte;

struct gameObject
{
    char sprite;
    vect2 * pos;
};
typedef struct gameObject gameObject;

struct interupteur
{
    gameObject gO;
    int active; //bool
};
typedef struct interupteur interupteur;

struct scene
{
    carte * carte;
    gameObject * chara;
    //array containing all the boxes
    gameObject * box;
    //array containing the switches
    interupteur * inter;
    int nbInter;
    int nbBox;
};
typedef struct scene scene;

I use a function to serialize my scene from a txt file. It works except for one thing : the inter (switch) array and the box array have the same content meaning the switch from my map (see below) override the box. So from the following txt I get to this :

in the txt     results
######         ######
#    #         #    #
#P  C#         #P   #
#    #         #    #
#   I#         #   I#
######         ######

So here is how I allocated my scene and my two arrays (let's forget the error case of NULL pointers) :

scene * scene1 = malloc(sizeof(scene));
scene1->box = malloc(scene1->nbBox*sizeof(gameObject));
scene1->inter = malloc(scene1->nbInter*sizeof(interupteur));

So I store the content of the txt in a 2d array of char and replace the P (player), C (box) and I (switch) with a space and store them elsewhere in my scene struct.

    for(int i = 0 ; i < scene1->carte->ligne ; i++)
    {
        for(int j = 0 ; j < scene1->carte->colonne ; j++)
        {
            fscanf(f,"%c",&(scene1->carte->carte[i][j]));
            if(scene1->carte->carte[i][j] == 'P')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->chara->pos->x = i;
                scene1->chara->pos->y = j;
                scene1->chara->sprite = 'P';
            }
            else if(scene1->carte->carte[i][j] == 'I')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->inter[k2].gO.pos->x = i;
                scene1->inter[k2].gO.pos->y = j;
                scene1->inter[k2].gO.sprite = 'I';
                k1++;
            }
            else if(scene1->carte->carte[i][j] == 'C')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->box[k1].pos->x = i;
                scene1->box[k1].pos->y = j;
                scene1->box[k1].sprite = 'C';
                k1++;
            }

I checked and it doesn't come from my output function. It come from my serialization function, the box is here until the function read the switch and override it. I also checked the address of the two arrays and they're different.
At first I was thinking it was a padding issue but I don't use union so I really don't know. I searched on internet and didn't find anything. Can somebody explain me why I have this problem ?
I code on Windows 10 using code blocks.

PS : Excuse me if my post isn't clear it is my first one and please excuse my English it isn't my native language.

I tried to change the order of the if/else if but it didn't change the overwriting (but create quite a mess). Expect that I didn't tried much more because I really don't see where the issue come from.

Edit : Here is my full code, you can use it as a minimal exemple (I don't know if it is minimal enough) :

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

struct vect2
{
    int x;
    int y ;
};
typedef struct vect2 vect2;

struct carte //couldn't use map cause of c++
{
    char ** carte;
    int line;
    int column;
};
typedef struct carte carte;

struct gameObject
{
    char sprite;
    vect2 * pos;
};
typedef struct gameObject gameObject;

struct interupteur
{
    gameObject gO;
    int active; //bool
};
typedef struct interupteur interupteur;

struct scene
{
    carte * carte;
    gameObject * chara;
    //array containing all the boxes
    gameObject * box;
    //array containing the switches
    interupteur * inter;
    int nbInter;
    int nbBox;
};
typedef struct scene scene;

scene * Update(scene * scene1)
{
    int k1 = 0, k2 = 0;
    for(int i = 0 ; i< scene1->carte->line;i++)
    {
        for(int j = 0 ; j < scene1->carte->column ; j++)
        {
            if(scene1->inter[k2].gO.pos->x == i && scene1->inter[k2].gO.pos->y == j)
            {
                printf("%c",scene1->inter[k1].gO.sprite);
                k2++;
            }
            else if(scene1->chara->pos->x == i && scene1->chara->pos->y == j)
            {
                printf("%c",scene1->chara->sprite);
            }
            else if(scene1->box[k1].pos->x == i && scene1->box[k1].pos->y == j)
            {
                printf("%c",scene1->box[k1].sprite);
                k1++;
            }
            else
                printf("%c",scene1->carte->carte[i][j]);
        }
    }
    return scene1;
}

scene * SerialMap(const char * path)
{
    scene * scene1 = malloc(sizeof(scene));
    scene1->carte = malloc(sizeof(carte));
    FILE * f =  fopen(path,"r+");

    //Look for dimension of the map, assuming the lines have the same lentgh, count box and switch
    scene1->carte->column = 0;
    scene1->carte->line = 0;
    char c;
    int k = 0;
    scene1->nbInter = 0;
    scene1->nbBox = 0;
    for(c = fgetc(f); c != EOF ; c = fgetc(f))
    {
        if(c == '\n')
        {
            scene1->carte->column = k;
            scene1->carte->line++;
            k = 0;
        }
        if(c == 'C')
            scene1->nbBox++;
        if(c == 'I')
            scene1->nbInter++;
        k++;
    }
    rewind(f);

    //Alloc map array
    scene1->carte->carte = malloc(scene1->carte->line * sizeof(char *));
    for(int i = 0 ; i < scene1->carte->line ; i++)
        scene1->carte->carte[i] = malloc(scene1->carte->column * sizeof(char));

    //Alloc switch and box array
    scene1->box = malloc(scene1->nbBox*sizeof(gameObject));
    scene1->inter = malloc(scene1->nbInter*sizeof(interupteur));
    scene1->chara = malloc(sizeof(gameObject));
    scene1->chara->pos = malloc(sizeof(vect2));

    //Serial map in 2d array and store box, switch and player
    int k1 = 0, k2 = 0; //k1 is used for the box tab and k2 for the swith tab
    for(int i = 0 ; i < scene1->carte->line ; i++)
    {
        for(int j = 0 ; j < scene1->carte->column ; j++)
        {
            fscanf(f,"%c",&(scene1->carte->carte[i][j]));
            if(scene1->carte->carte[i][j] == 'P')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->chara->pos->x = i;
                scene1->chara->pos->y = j;
                scene1->chara->sprite = 'P';
            }
            else if(scene1->carte->carte[i][j] == 'I')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->inter[k2].gO.pos->x = i;
                scene1->inter[k2].gO.pos->y = j;
                scene1->inter[k2].gO.sprite = 'I';
                k2++;
            }
            else if(scene1->carte->carte[i][j] == 'C')
            {
                scene1->carte->carte[i][j] = ' ';
                scene1->box[k1].pos->x = i;
                scene1->box[k1].pos->y = j;
                scene1->box[k1].sprite = 'C';
                k1++;
            }
        }
    }

    fclose(f);
    return scene1;
}

int main(int argc, char ** argv)
{
    scene * gamescene = SerialMap(argv[1]);
    gamescene  = Update(gamescene);
    return 0;
}

You can use the example I gave in the second code block.


问:
How can I combine a WHERE and ORDERBY request in Firestore (Firebase 9)? ReactJs
I have following function. If I only use orderBy or where, it works and I receive the documents.
If I try to combine both, I receive null. Is it not possible to combine it like I did?

```<code> const {documents} = useCollection('users', ['name', '==', 'Tom'] ,['age', 'asc'])
</code>```
```<code>export const useCollection = (collections, _q, _ordBy) => {
    const [documents, setDocuments] = useState(null)
    const [error, setError] = useState(null)
    const q = useRef(_q).current
    const ordBy = useRef(_ordBy).current

    useEffect(()=>{
        let ref = collection(db, collections)

        ref = query(ref, where(...q), orderBy(...ordBy))

        const unsubscribe = onSnapshot(ref, (snapshot)=>{
            let results = []
            snapshot.docs.forEach(doc => {
                results.push({...doc.data(), id: doc.id})
            })
            setDocuments(results)
            setError(null)
        }, (error) => {
            setError('could not fetch')
        })
        return () => unsubscribe()
    }, [collections, q, ordBy])
    return {documents, error}
}
</code>```

I tried only orderBy and only where and it works. After combining it, I receive null.

Body:
I have following function. If I only use orderBy or where, it works and I receive the documents.
If I try to combine both, I receive null. Is it not possible to combine it like I did?

 const {documents} = useCollection('users', ['name', '==', 'Tom'] ,['age', 'asc'])

export const useCollection = (collections, _q, _ordBy) => {
    const [documents, setDocuments] = useState(null)
    const [error, setError] = useState(null)
    const q = useRef(_q).current
    const ordBy = useRef(_ordBy).current

    useEffect(()=>{
        let ref = collection(db, collections)

        ref = query(ref, where(...q), orderBy(...ordBy))

        const unsubscribe = onSnapshot(ref, (snapshot)=>{
            let results = []
            snapshot.docs.forEach(doc => {
                results.push({...doc.data(), id: doc.id})
            })
            setDocuments(results)
            setError(null)
        }, (error) => {
            setError('could not fetch')
        })
        return () => unsubscribe()
    }, [collections, q, ordBy])
    return {documents, error}
}

I tried only orderBy and only where and it works. After combining it, I receive null.


问:
Problems when pasting a monetary value in a TDBEdit
I created a DBEditValida component that descends from a DBEdit that receives monetary values, the formatting of the component itself (#,##0.00) is working fine. But when I copy and paste a number with a dot (example: 1,000.00) the component gives the error "IS NOT A BCD VALUE". The dot must remain in the formatting of the component values.

I'm trying to treat it in two different ways:

I tried to handle formatting when exiting the component.

```<code>procedure TDBEditValida.DoExit;
var text_formata : string;
var num_conv : real;
begin
 inherited;
 if text <> '' then
  begin

    num_conv := StrToFloat(StringReplace(text,'.','', [rfreplaceall]));
    text_formata := Formatfloat('#,##0.00',num_conv);
    text := text_formata;

  end
end;

{but when I try to save the form it gives the same error "IS NOT A BCD VALUE".}
</code>```

handle the copied value on the clipboard.

```<code>procedure TDBEditValida.DoEnter;
begin
  inherited;
  Clipboard.AsText := StringReplace(Clipboard.AsText,'.','', [rfreplaceall]);
end;

...

procedure TDBEditValida.Change;

begin
  inherited;
  Clipboard.AsText := StringReplace(Clipboard.AsText,'.','', [rfreplaceall]);
end;

{when I copy the value and select the component, the formatting is correct, but if I select the component and then copy the value, it still shows an error}
</code>```

Body:
I created a DBEditValida component that descends from a DBEdit that receives monetary values, the formatting of the component itself (#,##0.00) is working fine. But when I copy and paste a number with a dot (example: 1,000.00) the component gives the error "IS NOT A BCD VALUE". The dot must remain in the formatting of the component values.

I'm trying to treat it in two different ways:

I tried to handle formatting when exiting the component.

procedure TDBEditValida.DoExit;
var text_formata : string;
var num_conv : real;
begin
 inherited;
 if text <> '' then
  begin

    num_conv := StrToFloat(StringReplace(text,'.','', [rfreplaceall]));
    text_formata := Formatfloat('#,##0.00',num_conv);
    text := text_formata;

  end
end;

{but when I try to save the form it gives the same error "IS NOT A BCD VALUE".}

handle the copied value on the clipboard.

procedure TDBEditValida.DoEnter;
begin
  inherited;
  Clipboard.AsText := StringReplace(Clipboard.AsText,'.','', [rfreplaceall]);
end;

...

procedure TDBEditValida.Change;

begin
  inherited;
  Clipboard.AsText := StringReplace(Clipboard.AsText,'.','', [rfreplaceall]);
end;

{when I copy the value and select the component, the formatting is correct, but if I select the component and then copy the value, it still shows an error}


问:
How to install hpilo-exporter?
so I'm trying to setup the hpilo-exporter for Prometheus to monitor the Power-Supply of one of our servers, but I'm struggling with the installation.

I tried following the steps mentioned in Github:

As mentioned there, I tried to run "pip install -e $HPILO_EXPORTER_DIR", which doesn't work for me (it's missing an argument for -e which would either be a vcs project url or a local project path, both of which I don't have?)

So I tried "pip install hpilo-exporter" which is also mentioned as a way to install the hpilo-exporter, which apparently is supposed to have worked ( I get following output after running the pip command "Installing collected packages: prometheus-client, python-hpilo, hpilo-exporter
Successfully installed hpilo-exporter-0.4.5 prometheus-client-0.15.0 python-hpilo-4.4.3") so I figured that it worked and tried to run the command to start the hpilo-exporter (as mentioned on GitHub aswell) which is "hpilo-exporter [--address=0.0.0.0 --port=9416 --endpoint="/metrics"]" but this isn't being recognised as a
command (output "hpilo-exporter: Command not found.")

So my question is, how do I solve this and get the hpilo-exporter to install and work properly?

Any help is much appreciated!

Title: How to install hpilo-exporter?


问:
Insert Category data in mvc using jquery
my java code is not working when pulling data in database.
Where am I going wrong? I tried many times but it didn't work.
I'm looking at debug mode mastercontroller. data is not coming.
I have jquery.min.js attached on my layout page.
I tried another js code as a trial, it works. I'm waiting for your help

My java code is not working when adding category array to mvc using jquery

//categoryaddt.js

$(document).ready(function () {
    $("#categoryform").validate({
        rules: {
            Name: { required: true },
        },
        messages: {
            Nanem: "Please Enter a Valid Name."
        },

        submitHandler: function (e) {

            var chk = 0;
            if ($("#closeButton").prop('checked') == true) {
                chk = 1;
            }

            var RequestCls = {
                Name: $("#txtName").val(),
                Active: chk
            }

            var UrlApi = '@Url.Content("~")' + "Master/AddCategory";
            $.ajax({
                url: UrlApi,
                type: 'POST',
                data: JSON.stringify(RequestCls),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {

                    alert(data.message);
                },
                error: function (data) {
                    alert(data.message);
                }

            });
        }
    })
});

```
```//Category.cshtml

@{
    ViewBag.Title = "Category";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

                <form id="categoryform" method="post">

                                Name
                                <input id="txtName" name="Name" type="text" class="form-control" autocomplete="off" />

                                <input type="checkbox" class="custom-control-input input-mini" id="closeButton" value="checked" />
                                Is Active

                    <button type="submit" id="btnSave" class="btn btn-primary mr-1 waves-effect waves-light"></button>
                </form>

@section scripts{

}
```
```//MasterCls.cs

using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls
{
    public class MasterCls : IMaster
    {
        QrperidEntities dbEntity;
        public MasterCls()
        {
            dbEntity = new QrperidEntities();
        }

        public ResponseCls AddCategory(RequestCls obj)
        {
            ResponseCls result = new ResponseCls();
            result.message = "Kayıt Başarı ile Yapıldı...!";
            result.status = "succes";
            result.flag = 1;

            try
            {
                using (var db = dbEntity)
                {
                    Category _category = new Category();
                    _category.Name = obj.Name;
                    _category.Active = obj.Active;

                    db.Category.Add(_category);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message.ToString();
                result.status = "error";
                result.flag = 0;
            }

            return result;
        }
    }
}

```
```//IMaster.cs

using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nero_Medya_Inventory_Management_System.BusinessLogic.IService
{
    public interface IMaster
    {
        ResponseCls AddCategory( RequestCls obj );
    }
}

```
```//Category.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Nero_Medya_Inventory_Management_System
{
    using System;
    using System.Collections.Generic;

    public partial class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Active { get; set; }
    }
}

```
```//MasterController.cs

using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Nero_Medya_Inventory_Management_System.Controllers
{
    public class MasterController : Controller
    {
        // GET: Master
        IMaster _master;
        public MasterController()
        {
            _master = new MasterCls();
        }

        public ActionResult Category()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AddCategory(RequestCls obj)
        {
            var result = _master.AddCategory(obj);
            return Json(result,JsonRequestBehavior.AllowGet);
        }
    }
}

```

Body:
my java code is not working when pulling data in database.
Where am I going wrong? I tried many times but it didn't work.
I'm looking at debug mode mastercontroller. data is not coming.
I have jquery.min.js attached on my layout page.
I tried another js code as a trial, it works. I'm waiting for your help

My java code is not working when adding category array to mvc using jquery

//categoryaddt.js

$(document).ready(function () {
    $("#categoryform").validate({
        rules: {
            Name: { required: true },
        },
        messages: {
            Nanem: "Please Enter a Valid Name."
        },

        submitHandler: function (e) {

            var chk = 0;
            if ($("#closeButton").prop('checked') == true) {
                chk = 1;
            }

            var RequestCls = {
                Name: $("#txtName").val(),
                Active: chk
            }

            var UrlApi = '@Url.Content("~")' + "Master/AddCategory";
            $.ajax({
                url: UrlApi,
                type: 'POST',
                data: JSON.stringify(RequestCls),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {

                    alert(data.message);
                },
                error: function (data) {
                    alert(data.message);
                }

            });
        }
    })
});

//Category.cshtml

@{
    ViewBag.Title = "Category";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

                <form id="categoryform" method="post">

                                Name
                                <input id="txtName" name="Name" type="text" class="form-control" autocomplete="off" />

                                <input type="checkbox" class="custom-control-input input-mini" id="closeButton" value="checked" />
                                Is Active

                    <button type="submit" id="btnSave" class="btn btn-primary mr-1 waves-effect waves-light"></button>
                </form>

@section scripts{

}

//MasterCls.cs

using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls
{
    public class MasterCls : IMaster
    {
        QrperidEntities dbEntity;
        public MasterCls()
        {
            dbEntity = new QrperidEntities();
        }

        public ResponseCls AddCategory(RequestCls obj)
        {
            ResponseCls result = new ResponseCls();
            result.message = "Kayıt Başarı ile Yapıldı...!";
            result.status = "succes";
            result.flag = 1;

            try
            {
                using (var db = dbEntity)
                {
                    Category _category = new Category();
                    _category.Name = obj.Name;
                    _category.Active = obj.Active;

                    db.Category.Add(_category);
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                result.message = ex.Message.ToString();
                result.status = "error";
                result.flag = 0;
            }

            return result;
        }
    }
}

//IMaster.cs

using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nero_Medya_Inventory_Management_System.BusinessLogic.IService
{
    public interface IMaster
    {
        ResponseCls AddCategory( RequestCls obj );
    }
}

//Category.cs

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Nero_Medya_Inventory_Management_System
{
    using System;
    using System.Collections.Generic;

    public partial class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Active { get; set; }
    }
}

//MasterController.cs

using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Nero_Medya_Inventory_Management_System.Controllers
{
    public class MasterController : Controller
    {
        // GET: Master
        IMaster _master;
        public MasterController()
        {
            _master = new MasterCls();
        }

        public ActionResult Category()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AddCategory(RequestCls obj)
        {
            var result = _master.AddCategory(obj);
            return Json(result,JsonRequestBehavior.AllowGet);
        }
    }
}


问:
Caching on Azure Synapse
I'm trying to create a report on PowerBI using azure synapse, I have a few live tables which should only include today's data, I've used Bulk Insert to create the azure pipeline. I'm noticing that historical data is also saved on my tables, but I've made sure to include in my script that I only want the current days data saved on here. Here's an example for context, I do not see prior days on the preview on synapse but when I import the tables on pbi days prior to the 14th show - This issue is slowing down the timeliness of my data, as I work with large data that can reach the 1000000 rows limit at any moment :</p>
```<code>SELECT
  CAST(Date as DATE) as 'Date' , count(distinct id) as 'IDs', Step as 'Steps', DATEPART(HOUR, Date) as 'hour'
FROM
  dbo.XExample
  where [enter image description here]
  CAST(Date as DATE) = CAST(GetDate() as Date)
  GROUP BY
  DATEPART(HOUR, Date), CAST(Date as DATE),  Step
```(https://i.stack.imgur.com/FwVCg.png) [enter image description here](https://i.stack.imgur.com/qgOfN.png)

I've tried clearing the cache on PBI and that didn't help, Also tried setting data cache to 0 that didn't solve the issue as I couldn't import any tables afterwards.
</code>```

Title: Caching on Azure Synapse

Body:
I'm trying to create a report on PowerBI using azure synapse, I have a few live tables which should only include today's data, I've used Bulk Insert to create the azure pipeline. I'm noticing that historical data is also saved on my tables, but I've made sure to include in my script that I only want the current days data saved on here. Here's an example for context, I do not see prior days on the preview on synapse but when I import the tables on pbi days prior to the 14th show - This issue is slowing down the timeliness of my data, as I work with large data that can reach the 1000000 rows limit at any moment :

SELECT
  CAST(Date as DATE) as 'Date' , count(distinct id) as 'IDs', Step as 'Steps', DATEPART(HOUR, Date) as 'hour'
FROM
  dbo.XExample
  where [enter image description here]
  CAST(Date as DATE) = CAST(GetDate() as Date)
  GROUP BY
  DATEPART(HOUR, Date), CAST(Date as DATE),  Step
```(https://i.stack.imgur.com/FwVCg.png) [enter image description here](https://i.stack.imgur.com/qgOfN.png)

I've tried clearing the cache on PBI and that didn't help, Also tried setting data cache to 0 that didn't solve the issue as I couldn't import any tables afterwards.


问:
How to set greater than - less than condition in Protege OWL/XML format
I want to add a restriction for height (data property) of a Person (class) such that height can't be <= 0.

Is there a data range / inequality value restriction in owl like:

 height only xsd:decimal[">0"^^xsd:decimal]

As I understand, we have some xsd:minInclusive and xsd:maxExclusive conditions but unfortunately I don't know how to use it, in OWL reasoning.


问:
How to write a Python script which tests the program and start from command line this way: python unit_test.py program_to_test.py input_data.txt
I know that I could add:

```<code>if __name__ == '__main__':
    unittest.main()
</code>```

and run code via CMD like:
python unit_test.py
But I want add some arguments which will be pass to script and work with them:

python unit_test.py program_to_test.py input_or_output_data.txt

My second question is: is possible to import module from command line?
basically I want to add module
program_to_test.py
from CMD and work with that?

I try add arguments with argparse but program always give me error:

```<code>ERROR: program_to_test (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'program_to_test'

======================================================================
ERROR: input_data (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'input_data'

----------------------------------------------------------------------
Ran 2 tests in 0.001s`
</code>```

Body:
I know that I could add:

if __name__ == '__main__':
    unittest.main()

and run code via CMD like:
python unit_test.py
But I want add some arguments which will be pass to script and work with them:

python unit_test.py program_to_test.py input_or_output_data.txt

My second question is: is possible to import module from command line?
basically I want to add module
program_to_test.py
from CMD and work with that?

I try add arguments with argparse but program always give me error:

ERROR: program_to_test (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'program_to_test'

======================================================================
ERROR: input_data (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'input_data'

----------------------------------------------------------------------
Ran 2 tests in 0.001s`


问:
Python multithreading- memory leak when use an shared object(so)
I have a python programs that gets memory leaks when use an third-party SO.
I simplify my code like this:

```<code>import time
import sys
import threading
import codecs
import ctypes
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

class TestThirdPartySo(object):
    def __init__(self):
        # this so uses thread-specific data
        self.call_stat_so = ctypes.CDLL("./third_party_fun.so")
        self.handle = self.call_stat_so._handle

    def test_fun(self):
        self.call_stat_so.fun_xxx()

def thread_fun():
    TestThirdPartySo().test_fun()

def test_main(num):
    count = 0
    while True:
        # create 3 * num threads
        thread_num = 3
        thread_list = []
        for _ in range(thread_num):
            thread_list.append(threading.Thread(target=thread_fun))
        for thread in thread_list:
            thread.start()
        for thread in thread_list:
            thread.join()
        count += thread_num
        time.sleep(0.01)
        if count % 100 == 0:
            print("finied %s" % count)
        if count > num:
            break
    print("end !!!!")

if __name__ == '__main__':
    num = sys.argv[1]
    test_main(int(num))
</code>```

Now, I know this shared object uses thread-specific data.And I have tried to close the SO after called it like this:

```<code>class TestThirdPartySo(object):
    def __init__(self):
        # this so uses thread-specific data
        self.call_stat_so = ctypes.CDLL("./third_party_fun.so")
        self.handle = self.call_stat_so._handle

    def test_fun(self):
        self.call_stat_so.fun_xxx()

    def __del__(self):
        dlclose_func(self.handle)

def dlclose_func(_handle):
    dlclose_func_tmp = ctypes.cdll.LoadLibrary('libdl.so').dlclose
    dlclose_func_tmp.argtypes = [ctypes.c_void_p]
    dlclose_func_tmp(_handle)
</code>```

But I failed to close the so. And I'm also not sure if the leaked memory will be freed after closing the so.

If the program not uses multi-threads or creates a fixed number of threads(threadpool), it works ok.

For some reason,I need create threads constantly in my program. What can I do to prevent this memory leaks?

Body:
I have a python programs that gets memory leaks when use an third-party SO.
I simplify my code like this:

import time
import sys
import threading
import codecs
import ctypes
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

class TestThirdPartySo(object):
    def __init__(self):
        # this so uses thread-specific data
        self.call_stat_so = ctypes.CDLL("./third_party_fun.so")
        self.handle = self.call_stat_so._handle

    def test_fun(self):
        self.call_stat_so.fun_xxx()

def thread_fun():
    TestThirdPartySo().test_fun()

def test_main(num):
    count = 0
    while True:
        # create 3 * num threads
        thread_num = 3
        thread_list = []
        for _ in range(thread_num):
            thread_list.append(threading.Thread(target=thread_fun))
        for thread in thread_list:
            thread.start()
        for thread in thread_list:
            thread.join()
        count += thread_num
        time.sleep(0.01)
        if count % 100 == 0:
            print("finied %s" % count)
        if count > num:
            break
    print("end !!!!")

if __name__ == '__main__':
    num = sys.argv[1]
    test_main(int(num))

Now, I know this shared object uses thread-specific data.And I have tried to close the SO after called it like this:

class TestThirdPartySo(object):
    def __init__(self):
        # this so uses thread-specific data
        self.call_stat_so = ctypes.CDLL("./third_party_fun.so")
        self.handle = self.call_stat_so._handle

    def test_fun(self):
        self.call_stat_so.fun_xxx()

    def __del__(self):
        dlclose_func(self.handle)

def dlclose_func(_handle):
    dlclose_func_tmp = ctypes.cdll.LoadLibrary('libdl.so').dlclose
    dlclose_func_tmp.argtypes = [ctypes.c_void_p]
    dlclose_func_tmp(_handle)

But I failed to close the so. And I'm also not sure if the leaked memory will be freed after closing the so.

If the program not uses multi-threads or creates a fixed number of threads(threadpool), it works ok.

For some reason,I need create threads constantly in my program. What can I do to prevent this memory leaks?


问:
How to use `AbortController` with custom API?
I have a API call inside useEffect. I don't use fetch to do that rather I have my own custom API.

const getAENames = () => {
    return new Promise((resolve, reject) => {
        api.get(
            {
                url: '/fetchAENames',
            },
            (res) => {
                resolve(res.AENAMES);
            },
            (err) => {
                reject(new Error(`Oops! Couldn't fetch AE Names: ${err}`));
            },
        );
    });
};

useEffect(() => {
    getAENames()
         .then((res) => {
            dispatch({ type: 'appEntityNames', value: res});
         })
        .catch((err) => {
            toast.error(err.message, {
                autoClose: 10000,
            });
    });
}, []);
```

useEffect is called twice as I'm on StrictMode. So, I would like a proper cleanup code for the above call instead of disabling StrictMode.

From what I have looked up, AbortController can be used to properly cancel API calls for clean up. I'm not sure whether it can be used with any API calls or just fetch? If it can be used in my case, how do I go about?

Or should I just use useRef to handle this?

Any help would be appreciated! Thanks!

Body:
I have a API call inside useEffect. I don't use fetch to do that rather I have my own custom API.

const getAENames = () => {
    return new Promise((resolve, reject) => {
        api.get(
            {
                url: '/fetchAENames',
            },
            (res) => {
                resolve(res.AENAMES);
            },
            (err) => {
                reject(new Error(`Oops! Couldn't fetch AE Names: ${err}`));
            },
        );
    });
};

useEffect(() => {
    getAENames()
         .then((res) => {
            dispatch({ type: 'appEntityNames', value: res});
         })
        .catch((err) => {
            toast.error(err.message, {
                autoClose: 10000,
            });
    });
}, []);

useEffect is called twice as I'm on StrictMode. So, I would like a proper cleanup code for the above call instead of disabling StrictMode.

From what I have looked up, AbortController can be used to properly cancel API calls for clean up. I'm not sure whether it can be used with any API calls or just fetch? If it can be used in my case, how do I go about?

Or should I just use useRef to handle this?

Any help would be appreciated! Thanks!


问:
Docker creates a bridge network with name "env_default" when network is not specified
I have a spring boot app started using the below docker-compose. It creates a new bridge network with name "env_default" instead of using the default one available.

```<code>version: "3"

services:
  backend-config:
    image: hub/backend-config:v200
    container_name: backend-config
    expose:
      - 9091
    ports:
      - 9091:9091
    environment:
      - LOG_LOCATION=/var/lib/backend/config/logs
    volumes:
      - ./logs:/var/lib/backend/config/logs
</code>```

Below are the networks after the above container is started. My understanding was container by default will use the default bridge network. Is this the correct behavior?

```<code>NETWORK ID     NAME          DRIVER    SCOPE
b66610237847   bridge        bridge    local
736cd740d86e   env_default   bridge    local
6ad7ca425e1c   host          host      local
e01327716975   none          null      local
</code>```

Body:
I have a spring boot app started using the below docker-compose. It creates a new bridge network with name "env_default" instead of using the default one available.

version: "3"

services:
  backend-config:
    image: hub/backend-config:v200
    container_name: backend-config
    expose:
      - 9091
    ports:
      - 9091:9091
    environment:
      - LOG_LOCATION=/var/lib/backend/config/logs
    volumes:
      - ./logs:/var/lib/backend/config/logs

Below are the networks after the above container is started. My understanding was container by default will use the default bridge network. Is this the correct behavior?

NETWORK ID     NAME          DRIVER    SCOPE
b66610237847   bridge        bridge    local
736cd740d86e   env_default   bridge    local
6ad7ca425e1c   host          host      local
e01327716975   none          null      local


问:
Can't save a temporary csv file to /home/app directory on heroku using R shiny app
I need to generate a temporary csv file on heroku /home/app directory and use it directly on my shiny application but the csv file is not being created in the directory when I try to check using heroku bash command there is no csv file exist in the directory. I don't need the file to be persistent in the server. I want it to be temporary use during processing only.

here is an example of the code to write the csv file to the directory

```<code>df <- c(0,0)
write.csv(df,"/home/app/test.csv")
</code>```

Body:
I need to generate a temporary csv file on heroku /home/app directory and use it directly on my shiny application but the csv file is not being created in the directory when I try to check using heroku bash command there is no csv file exist in the directory. I don't need the file to be persistent in the server. I want it to be temporary use during processing only.

here is an example of the code to write the csv file to the directory

df <- c(0,0)
write.csv(df,"/home/app/test.csv")