问:
Camera rotate by movement joystick
I have first person shooter. It's work when I rotate the camera at first (right part of the screen) and then use joystick for movement (left part of the screen). But if I use joystick for movement and then rotate the camera - player move and camera rotate by joystick, not by camera rotation zone. How to fix it?</p>
```<code>using UnityEngine;
using UnityEngine.EventSystems;

public class FixedTouchField : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [HideInInspector]
    public Vector2 TouchDist;
    [HideInInspector]
    public Vector2 PointerOld;
    [HideInInspector]
    protected int PointerId;
    [HideInInspector]
    public bool Pressed;

    void Start()
    {
    }

    void Update()
    {
        if (Pressed)
        {
            if (PointerId >= 0 && PointerId < Input.touches.Length)
            {
                TouchDist = Input.touches[PointerId].position - PointerOld;
                PointerOld = Input.touches[PointerId].position;
            }
            else
            {
               TouchDist = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - PointerOld;
               PointerOld = Input.mousePosition;
            }
        }
        else
        {
            TouchDist = new Vector2();
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
    Pressed = true;
        //PointerId = eventData.pointerId;
    //PointerOld = eventData.position;
        PointerOld = Input.touches[PointerId].position;

    }

    public void OnPointerUp(PointerEventData eventData)
    {
       Pressed = false;
    }

}
</code>```

Title: Camera rotate by movement joystick

Body:
I have first person shooter. It's work when I rotate the camera at first (right part of the screen) and then use joystick for movement (left part of the screen). But if I use joystick for movement and then rotate the camera - player move and camera rotate by joystick, not by camera rotation zone. How to fix it?

using UnityEngine;
using UnityEngine.EventSystems;

public class FixedTouchField : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [HideInInspector]
    public Vector2 TouchDist;
    [HideInInspector]
    public Vector2 PointerOld;
    [HideInInspector]
    protected int PointerId;
    [HideInInspector]
    public bool Pressed;

    void Start()
    {
    }

    void Update()
    {
        if (Pressed)
        {
            if (PointerId >= 0 && PointerId < Input.touches.Length)
            {
                TouchDist = Input.touches[PointerId].position - PointerOld;
                PointerOld = Input.touches[PointerId].position;
            }
            else
            {
               TouchDist = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - PointerOld;
               PointerOld = Input.mousePosition;
            }
        }
        else
        {
            TouchDist = new Vector2();
        }
    }

    public void OnPointerDown(PointerEventData eventData)
    {
    Pressed = true;
        //PointerId = eventData.pointerId;
    //PointerOld = eventData.position;
        PointerOld = Input.touches[PointerId].position;

    }

    public void OnPointerUp(PointerEventData eventData)
    {
       Pressed = false;
    }

}


来源: stackexchange

问:
Unit testing methods whose impact can only be confirmed using another method
Assume there are two methods in a module, insert and print. The module's inner properties are private and can only be accessed by calling print().

In testing, print has its own set of tests, and now I'm trying to test insert. The issue is, the only way to confirm if insert did in fact insert any data into the model is to call print() and check its output. Which also means that if something were to break print in the future, then insert's tests would also fail.

The most straightforward solution is to expose the inner variables that insert affects and assert the changes directly, but that would clutter the module's API and potentially confuse end users.

Is there another practice/solution to situations like this or is exposing the inner variable the way to go?

ContentLicense: CC BY-SA 4.0


问:
Android Studio Virtual android device blinking
I want to set up android studio's android emulator for React Native and I have a problem with the emulator. I read that it is a problem with resizing. That emulator wants to resize an android window. But I can not find a solution to that.


问:
How to make a nextjs component embeddable
I'm working on a project in nextjs in which I have created a dashboard in which users can manage their websites in groups, after this i have extracted data from the websites and the data is indexed in meilisearch for adding the search functionality, now I have done all the thing.

now i want that the script of my search component that i have made in nextjs which is getting data from meilisearch and show that script in text area of my websites so users can copy and paste in their websites to have the search functionality and have the same result like i am getting in my websites, how can i do that.

enter image description here

as you can see i have input box where i am searching and git the results now i want to generate a script of the search component to be show in the above text boxes so users can copy and paste it in their own websites and they should get the same results as i am getting here.


问:
windll.gdi32.GetPixel failed with pyautogui and Variables from configparser
i   was trying to do a config.ini with configpaser i got it working with this

```<code>from configparser import ConfigParser

#-------Message Config Start ------------#
config =  ConfigParser()
config.read('config.ini')

#Devicename for Message Curls
Geraet = str = config['DEFAULT']['Geraet_Name']
YellowBellX = str = config['DEFAULT']['YellowBellXCoord']
YellowBellY = str = config['DEFAULT']['YellowBellYCoord']
</code>```

it works for urls of telegram curl and Geraet  Name works alsow

but when i use this for x y for pixelmatch i get error
Exeption windll.gdi32.GetPixel failed : return -1

if i change YellowBellX to Coords it works
YellowBellX = 355
YellowBellY = 219

this works and pixel match is correct with no error

but i want to use Variable in the Config File

Body:
i   was trying to do a config.ini with configpaser i got it working with this

from configparser import ConfigParser

#-------Message Config Start ------------#
config =  ConfigParser()
config.read('config.ini')

#Devicename for Message Curls
Geraet = str = config['DEFAULT']['Geraet_Name']
YellowBellX = str = config['DEFAULT']['YellowBellXCoord']
YellowBellY = str = config['DEFAULT']['YellowBellYCoord']

it works for urls of telegram curl and Geraet  Name works alsow

but when i use this for x y for pixelmatch i get error
Exeption windll.gdi32.GetPixel failed : return -1

if i change YellowBellX to Coords it works
YellowBellX = 355
YellowBellY = 219

this works and pixel match is correct with no error

but i want to use Variable in the Config File


问:
execute when Javafx box collides with another box
I've been coding with javafx recently and I've rendered a cube and another cube, one cube is connected to the camera which moves when the user presses 'w', (connected as the cube  moves when the camera moves). I'm trying to detect when one node collides with the other, I've tried taking the translation of 'x' on the cube connect to the camera and the translation of the other 'x' on the other cube which works but the 'z' doesn't work because the world moves and rotates instead of the camera so i cannot do that.

How can I use the attribute intersects of one javafx box to another javafx box to detect the collision. I've tried multiple ways of detecting collision, most seemed to have intersects to be the answer but they had 2d shapes instead of 3d boxes. This is what I have, either they never execute or they execute when the statement is called (getbBoundsInParent, getBoundsInLocal, getLayoutBounds). This isn't all the code, I put what I thought was relevant. How can i detect collision with intersect of a 3d javafx box?

```<code> if(eyes.getBoundsInParent().intersects(cube.getBoundsInParent())){
          System.exit(0);
}
</code>```

Body:
I've been coding with javafx recently and I've rendered a cube and another cube, one cube is connected to the camera which moves when the user presses 'w', (connected as the cube  moves when the camera moves). I'm trying to detect when one node collides with the other, I've tried taking the translation of 'x' on the cube connect to the camera and the translation of the other 'x' on the other cube which works but the 'z' doesn't work because the world moves and rotates instead of the camera so i cannot do that.

How can I use the attribute intersects of one javafx box to another javafx box to detect the collision. I've tried multiple ways of detecting collision, most seemed to have intersects to be the answer but they had 2d shapes instead of 3d boxes. This is what I have, either they never execute or they execute when the statement is called (getbBoundsInParent, getBoundsInLocal, getLayoutBounds). This isn't all the code, I put what I thought was relevant. How can i detect collision with intersect of a 3d javafx box?

 if(eyes.getBoundsInParent().intersects(cube.getBoundsInParent())){
          System.exit(0);
}


问:
How does the LSP tool/client know how to connect to my LSP server in the first place
I want to write a simple LSP server to provide autocomplete that will work with any number of IDEs and Editors that are LSP tools.

On the topic of startup, the LSP specification does say the following:

The current protocol specification defines that the lifecycle of a
server is managed by the client (e.g. a tool like VS Code or Emacs).
It is up to the client to decide when to start (process-wise) and when
to shutdown a server.

source emphasis my own

However nowhere in the specification can I find how the development tool (client) actually launches the server.

The spec just continues straight into the Initialize Request which requires the client and tool already to be connected.

So 2 questions:

If I develop a languageServer.exe that uses a RESTful API over HTTP to communicate with the LSP tool, is there some standard entrypoint where my server and client can agree on what port to use.

If I develop a new LSP tool how can I get some LSP Server from a VSCode extension and launch and connect to it. Is this standard?


问:
Display HTML5 controls in System.Windows.Forms.WebBrowser
Simple question. I have a WinFomrs app (C#) and there's a WebBrowser control which displays html to the user. The thing is I need to start using some of the css3 capabilities like rounded border for buttons.

I have tried adding the <!DOCTYPE html> node to the html code with no luck.

What should I do? Do I need to change the control? Does anybody know a good alternative?

Edit: The html code I try to show displays correctly in every browser (IE9, Chrome, Firefox)

ContentLicense: CC BY-SA 3.0


问:
docker: invalid reference format: repository name must be lowercase
```<code>docker run -d \
  -p 8081:8081 \
  -e ME_CONFIG_MONGODB_ADMINUSERNAME-admin \
  -e ME_CONFIG_ MONGODB_ADMINPASSWORD=password \
  --net mongo-network \
  --name mongo-express \
  -e ME_CONFIG_MONGODE_SERVER-mongodb \
  mongo-express

</code>```

im facing

```<code>docker: invalid reference format: repository name must be lowercase.
</code>```

Please help as i double checked capitl letters.

i tried other stack flow answers but still facing this error.

Body:
docker run -d \
  -p 8081:8081 \
  -e ME_CONFIG_MONGODB_ADMINUSERNAME-admin \
  -e ME_CONFIG_ MONGODB_ADMINPASSWORD=password \
  --net mongo-network \
  --name mongo-express \
  -e ME_CONFIG_MONGODE_SERVER-mongodb \
  mongo-express

im facing

docker: invalid reference format: repository name must be lowercase.

Please help as i double checked capitl letters.

i tried other stack flow answers but still facing this error.


问:
How to use cliptnotify with python?
cliplnotify is a simple program that ends when the X clipboard is modified. It runs something like this

while clipnotify; do
    [an event happened, do something with the selection]
done
```

How can I write something similar to the above script in python that does something, for example, append the clipboard item in a list when the clipboard is modified?

Title: How to use cliptnotify with python?

Body:
cliplnotify is a simple program that ends when the X clipboard is modified. It runs something like this

while clipnotify; do
    [an event happened, do something with the selection]
done

How can I write something similar to the above script in python that does something, for example, append the clipboard item in a list when the clipboard is modified?


问:
Software to auto-tag text, such as blog post or news articles?
I am searching for a software that would do the following:

process numerous articles varying from 100-1k words;

automatically remove stop words;

recommend best tags based on remaining words, i.e. this article is all about "car, transmission, japan".

To me this is sort of like Google's internal keyword summary tools. Any idea? Will an open source full-text search tool like Ferret be a viable option? But I am totally open to commercial software tools as well.


问:
Broken Favourites logic with c#.I want to save the story to favorites but It keeps giving me error that the page Save/storyId is not found
I want to save the story without ajax request,just with mvc logic.It keeps giving me error that the page Save/storyId is not found.Any help wiil be good.
I dont want to use api controllers,i want to take the stories id,take the data of that story and create a favstory object,inside the sql database.

Thats my Service Save method logic:

```<code>public int Save(int id,string title,string topic,string genredid,string psedonym,string favcon, string userId)
    {

        var story = this.data.Stories.Where(x => x.Id == id).FirstOrDefault();

        var favbook = new FavouriteBook
        {
            FavTitle = story.Title,
            FavTopic = story.Topic,
            FavGenreId = story.GenreId,
            FavUserAuthor = story.Pseudonym,
            FavCon = story.StoryText
        };

        this.data.FavouriteBooks.Add(favbook);
        this.data.SaveChanges();

        return favbook.Id;
    }
</code>```

Thats the Controller Save method logic:

```<code> [HttpPost]
    public IActionResult Send(int id,AddFavouriteModel postm)
    {

        var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        this.favouris.Save(
            id,
            postm.FavTitle,
            postm.FavTopic,
            postm.FavGenre.Name,
            postm.FavUserAuthor,
            postm.FavCon,
            userId
            );

        return RedirectToAction(nameof(Index));
    }
</code>```

Thats the link to the Save method,from which i try to get the stories id,

```<code> <a smooth="true" asp-controller="Favourites" asp-action="Save" asp-route-id="@sto.Id" class="btnfav"></a>
</code>```

I don't know if its right,but i have never implented favourites logic with c#.

Body:
I want to save the story without ajax request,just with mvc logic.It keeps giving me error that the page Save/storyId is not found.Any help wiil be good.
I dont want to use api controllers,i want to take the stories id,take the data of that story and create a favstory object,inside the sql database.

Thats my Service Save method logic:

public int Save(int id,string title,string topic,string genredid,string psedonym,string favcon, string userId)
    {

        var story = this.data.Stories.Where(x => x.Id == id).FirstOrDefault();

        var favbook = new FavouriteBook
        {
            FavTitle = story.Title,
            FavTopic = story.Topic,
            FavGenreId = story.GenreId,
            FavUserAuthor = story.Pseudonym,
            FavCon = story.StoryText
        };

        this.data.FavouriteBooks.Add(favbook);
        this.data.SaveChanges();

        return favbook.Id;
    }

Thats the Controller Save method logic:

 [HttpPost]
    public IActionResult Send(int id,AddFavouriteModel postm)
    {

        var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        this.favouris.Save(
            id,
            postm.FavTitle,
            postm.FavTopic,
            postm.FavGenre.Name,
            postm.FavUserAuthor,
            postm.FavCon,
            userId
            );

        return RedirectToAction(nameof(Index));
    }

Thats the link to the Save method,from which i try to get the stories id,

I don't know if its right,but i have never implented favourites logic with c#.


问:
Typescript compiles into Javascript wrong?
I'm trying to connect to MongoDB in my Node app using Typescript.

This line of code:

```<code>const MongoClient = mongoDb.MongoClient;
</code>```

Compiles into this line of code:

```<code>const MongoClient = mongodb_1.default.MongoClient;
</code>```

Throwing this error:
TypeError: Cannot read properties of undefined (reading 'MongoClient')

Removing the ".default." in the compiled code makes it run.

I've tried messing with package.json as well as tsconfig.json
Namely the esModuleInterop and allowSyntheticDefaultImports
but nothing works.

Body:
I'm trying to connect to MongoDB in my Node app using Typescript.

This line of code:

const MongoClient = mongoDb.MongoClient;

Compiles into this line of code:

const MongoClient = mongodb_1.default.MongoClient;

Throwing this error:
TypeError: Cannot read properties of undefined (reading 'MongoClient')

Removing the ".default." in the compiled code makes it run.

I've tried messing with package.json as well as tsconfig.json
Namely the esModuleInterop and allowSyntheticDefaultImports
but nothing works.


问:
Authenticate an iframe using AWS
currently, we are deploying 2 APIs on AWS (using API Gateway and Lamda ):
the 2 APIs share very similar endpoints but with different authentication/authorization mechanisms

1st API uses OAuth 2.0 client credentials (it's used for server-to-server communication ).
it uses a user pool and different scopes to authenticate the server to each lambda

2nd API uses the same endpoints as the 1st API but it's using a different authentication approach ( aws_iam on the back) and amplify on the frontend - its a client-to-server communication and requires the user to sign on the client before being able to make any API request

currently, we are looking to deploy an iframe that is able to access the same endpoints that the 2 APIs are providing.

so I hope if you can recommend the best authentication/authorization approach for our use case:

oauth 2.0 client credentials is a server-to-server approach ..so i believe it doesn't fit our iframe(client) to server approach

using the 2nd approach ( aws-iam ).. but the user requires to log in before accessing the API and we won't be able to hardcode user login info in the iframe

3rd approach which is the possible solution: the server generates a JWT on the backend and returns it in the iframe ( using jwt library ).. the iframe is now authenticated and can do API calls to the endpoints directly which are using custom lambda auth as their authorizer... the custom lambda auth verify the token .. send proper policy and forward the request to the  requested endpoint

any feedback on the points mentioned above? I'm not sure if auth mechanism can be done in a better way .. or if the way I'm proposing is the way to go?

Thank you

Title: Authenticate an iframe using AWS


问:
Xcode error when building a static library: can't locate file for: -lcurl
I am creating a static library in cpp which does some api calls. I am trying to use libcurl.a in my code but when building, I keep encountering error :

```<code>error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: can't locate file for: -lcurl
error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: -lcurl is not an object file (not allowed in a library)
Command Libtool failed with a nonzero exit code
</code>```

cpp code -

```<code>#include "client.hpp"
#include "curl/curl.h"
#include <iostream>
#include <string>

extern "C" {

    static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
    {
        ((std::string*)userp)->append((char*)contents, size * nmemb);
        return size * nmemb;
    }

    int sum1() {
        CURL *curl;
        CURLcode res;
        std::string readBuffer;

        curl = curl_easy_init();
        if(curl) {
          curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
          res = curl_easy_perform(curl);
          curl_easy_cleanup(curl);

          std::cout << readBuffer << std::endl;
            return 1;
        }
        return 0;
    }
}
</code>```

header file code -

```<code>#ifndef client_hpp
#define client_hpp

extern "C" {
int sum1();
}

#endif /* client_hpp */
</code>```

I have done the following configurations in my project:

added libcurl.a file in Build Phases > Link Binary With Libraries

copied all header files in my xcode project and added directory path in Build Settings > Search Paths > Header Search Paths

added -lcurl flag in Build Settings > Linking > Other Linker Flags

All things are working fine if instead of building a static library I build a command line tool.

Questions: Am I missing some more settings in my project? Is there any other way I can use curl and create a static library on top of it?

Thanks

Body:
I am creating a static library in cpp which does some api calls. I am trying to use libcurl.a in my code but when building, I keep encountering error :

error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: can't locate file for: -lcurl
error: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/libtool: file: -lcurl is not an object file (not allowed in a library)
Command Libtool failed with a nonzero exit code

cpp code -

#include "client.hpp"
#include "curl/curl.h"
#include <iostream>
#include <string>

extern "C" {

    static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
    {
        ((std::string*)userp)->append((char*)contents, size * nmemb);
        return size * nmemb;
    }

    int sum1() {
        CURL *curl;
        CURLcode res;
        std::string readBuffer;

        curl = curl_easy_init();
        if(curl) {
          curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
          curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
          curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
          res = curl_easy_perform(curl);
          curl_easy_cleanup(curl);

          std::cout << readBuffer << std::endl;
            return 1;
        }
        return 0;
    }
}

header file code -

#ifndef client_hpp
#define client_hpp

extern "C" {
int sum1();
}

#endif /* client_hpp */

I have done the following configurations in my project:

added libcurl.a file in Build Phases > Link Binary With Libraries

copied all header files in my xcode project and added directory path in Build Settings > Search Paths > Header Search Paths

added -lcurl flag in Build Settings > Linking > Other Linker Flags

All things are working fine if instead of building a static library I build a command line tool.

Questions: Am I missing some more settings in my project? Is there any other way I can use curl and create a static library on top of it?

Thanks


问:
Decrypting encrypted shared prefrences
I am trying to decrypt the encrypted shared preferences in android for a game I am reverse engineering. I have identified the key that the app uses to decrypt in android's keystore and need help applying it to my script.

Here is the code i am using to try and decrypt the keyset.

The keyset is AES_SIV according to the source code provided by jadx

import base64
from Crypto.Cipher import AES
def decrypt_keyset(key, encrypted_data, tag):
    decoded_data = base64.b64decode(encrypted_data)
    # key becomes 32 bytes once decoded which siv requires
    decoded_key = base64.b64decode(key)

    cipher = AES.new(decoded_key, AES.MODE_SIV)

    decrypted_data = cipher.decrypt_and_verify(decoded_data,tag)

    return decrypted_data

keyset_file_path = "/home/un/dev/decryption_tests/an"

# extracted from software keystore
keyset_key = b"shBeeokeqh1k3Mz/2PbbuFC7NG3UZEN9dGOT9VzwG9k="

with open(keyset_file_path, "rb") as f:

    tag = f.read()[-16:]
    encrypted_keyset = f.read()

decrypted_keyset = decrypt_keyset(keyset_key, encrypted_keyset,tag)
```

This results in the error "MAC check failed".

Source code snippet

Test data

Full save

Title: Decrypting encrypted shared prefrences

Body:
I am trying to decrypt the encrypted shared preferences in android for a game I am reverse engineering. I have identified the key that the app uses to decrypt in android's keystore and need help applying it to my script.

Here is the code i am using to try and decrypt the keyset.

The keyset is AES_SIV according to the source code provided by jadx

import base64
from Crypto.Cipher import AES
def decrypt_keyset(key, encrypted_data, tag):
    decoded_data = base64.b64decode(encrypted_data)
    # key becomes 32 bytes once decoded which siv requires
    decoded_key = base64.b64decode(key)

    cipher = AES.new(decoded_key, AES.MODE_SIV)

    decrypted_data = cipher.decrypt_and_verify(decoded_data,tag)

    return decrypted_data

keyset_file_path = "/home/un/dev/decryption_tests/an"

# extracted from software keystore
keyset_key = b"shBeeokeqh1k3Mz/2PbbuFC7NG3UZEN9dGOT9VzwG9k="

with open(keyset_file_path, "rb") as f:

    tag = f.read()[-16:]
    encrypted_keyset = f.read()

decrypted_keyset = decrypt_keyset(keyset_key, encrypted_keyset,tag)

This results in the error "MAC check failed".

Source code snippet

Test data

Full save


问:
Decode Httrack encoded urls in Python?
I have downloaded a full website using Httrack Website Copier and now I want to retrieve  all image source ('src') urls using Python 3.7.

Already did that but for further use I need those urls to be in plain text but instead they are something like this:

```<code>cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f6eX2fBursitisX5fElbowX5fWCX2eJPGX2f800pxX2dBursitisX5fElbowX5fWCX2eJPGX3f20070925222131
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f62X2fPDX2diconX2esvgX2f64pxX2dPDX2diconX2esvgX2epng
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f6eX2fBursitisX5fElbowX5fWCX2eJPGX2f120pxX2dBursitisX5fElbowX5fWCX2eJPGX3f20070925222131
</code>```

I don't know what these cid:urls are but google sent me to this: Replace (cid:<number>) with chars using Python when extracting text from PDF files
which is obviously something maybe somehow related to this problem but it doesn't help me (or at least I don't know how).
Also, I thought they are somehow escaped urls so I tried this solution from here which doesn't work either: Decode escaped characters in URL

This is my try to solve this problem into Python:

```<code>import urllib.parse

mystr = "cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg"

print(mystr.encode('utf-8'))
print(mystr.encode('utf-8').decode('utf-8', errors='ignore'))
print(mystr.encode('utf-8').decode('utf-8'))

print(urllib.parse.unquote(mystr, encoding='utf-8', errors='replace'))
</code>```

Note that I tried also to decode them from utf-8 because I thought maybe that way it will work but it doesn't work either.

Result of my code above is:

```<code>b'cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg'
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
</code>```

You can replace it with any of those strings from the beginning of my post and there will not be any change.

Thanks in advance!

Title: Decode Httrack encoded urls in Python?

Body:
I have downloaded a full website using Httrack Website Copier and now I want to retrieve  all image source ('src') urls using Python 3.7.

Already did that but for further use I need those urls to be in plain text but instead they are something like this:

cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f6eX2fBursitisX5fElbowX5fWCX2eJPGX2f800pxX2dBursitisX5fElbowX5fWCX2eJPGX3f20070925222131
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f62X2fPDX2diconX2esvgX2f64pxX2dPDX2diconX2esvgX2epng
cid:httpsX3aX2fX2fuploadX2ewikimediaX2eorgX2fwikipediaX2fcommonsX2fthumbX2f6X2f6eX2fBursitisX5fElbowX5fWCX2eJPGX2f120pxX2dBursitisX5fElbowX5fWCX2eJPGX3f20070925222131

I don't know what these cid:urls are but google sent me to this: Replace (cid:<number>) with chars using Python when extracting text from PDF files
which is obviously something maybe somehow related to this problem but it doesn't help me (or at least I don't know how).
Also, I thought they are somehow escaped urls so I tried this solution from here which doesn't work either: Decode escaped characters in URL

This is my try to solve this problem into Python:

import urllib.parse

mystr = "cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg"

print(mystr.encode('utf-8'))
print(mystr.encode('utf-8').decode('utf-8', errors='ignore'))
print(mystr.encode('utf-8').decode('utf-8'))

print(urllib.parse.unquote(mystr, encoding='utf-8', errors='replace'))

Note that I tried also to decode them from utf-8 because I thought maybe that way it will work but it doesn't work either.

Result of my code above is:

b'cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg'
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg
cid:httpsX3aX2fX2fcommonsX2emX2ewikimediaX2eorgX2fstaticX2fimagesX2fmobileX2fcopyrightX2fcommonswikiX2dwordmarkX2esvg

You can replace it with any of those strings from the beginning of my post and there will not be any change.

Thanks in advance!


问:
logstash filter plugin .gem file install on kubernetes Can't file local file
Im trying to install a custom .gem filter plugin using kubernetes StatefulSet. The gem file is in /tmp directory. pod log is showing ERROR: File not found for: file:///tmp/logstash-filter-kubernetes-0.3.1.gem, message: Can't file local file /tmp/logstash-filter-kubernetes-0.3.1.gem

Below is StatefulSet code snippet.

```<code>image: "grafana/logstash-output-loki:1.0.1"
        imagePullPolicy: "IfNotPresent"
        command:
            - '/bin/sh'
            - '-c'
            - 'logstash-plugin install --no-verify file:///tmp/logstash-filter-kubernetes-0.3.1.gem && logstash -f /usr/share/logstash/pipeline/logstash.conf'

</code>```

Body:
Im trying to install a custom .gem filter plugin using kubernetes StatefulSet. The gem file is in /tmp directory. pod log is showing ERROR: File not found for: file:///tmp/logstash-filter-kubernetes-0.3.1.gem, message: Can't file local file /tmp/logstash-filter-kubernetes-0.3.1.gem

Below is StatefulSet code snippet.

image: "grafana/logstash-output-loki:1.0.1"
        imagePullPolicy: "IfNotPresent"
        command:
            - '/bin/sh'
            - '-c'
            - 'logstash-plugin install --no-verify file:///tmp/logstash-filter-kubernetes-0.3.1.gem && logstash -f /usr/share/logstash/pipeline/logstash.conf'


问:
Copying Azure resources between different Azure organisations
I’ve been looking into cloud resources (specifically Azure) and looking at a lot of online tutorials.

One thing I’ve come across is copying resources. Am I right in thinking that I can move or copy resources between other cloud providers and on premise servers by use of Azure migrate, but not from Azure to Azure subscriptions? I have a couple of vms in a work supplied subscription that I’d like to copy to my personal subscription (purely for learning purposes, my company has no problem with this, not stealing any secrets haha) but I can’t figure out a way to do this.

Does any one know how I can achieve this? One is a windows vm and two Ubuntu vms but that shouldn’t make a difference I don’t think.

Looked at Azure migrate but doesn’t seem to copy from azure to azure


问:
Host a Blazor WASM app inside a Visual Studio Extension
Is it possible to create a Visual Studio Extension that has a host window (that I can dock etc inside VS like code tabs do) that I can show the contents of a #Blazor WASM app inside?

I've not written a VS extension before, and have no idea where to start.


问:
need to use put and post in same bootstrap model, but only post working
i am working on a project and need to implement ngb bootstrap  modal in angular 13, and complete the operation of put and post on the same model, but when I click on edit button it loads the data and create new object insted of updating old one. Stucked from last 3 days

service.ts

```<code> addSource(source : sources[]): Observable<sources[]>{
      return this.http.post<sources[]> (this.API_URL, source).pipe(
      tap(() => {
        this._refreshrequired.next();
      })
    );
      //console.log(user);
      }
</code>```

component.ts

```<code>import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { sources } from '../sources';
import { SourcesService } from '../sources.service';
import { FormGroup, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import {SourcesComponent} from '../sources/sources.component';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-add-source',
  templateUrl: './add-source.component.html',
  styleUrls: ['./add-source.component.css']
})
export class AddSourceComponent implements OnInit {
   // a form for entering and validating data
//    sourceForm = new FormGroup({
//     name : new FormControl('', Validators.compose([Validators.required, Validators.minLength(5)])),
//     url : new FormControl('', Validators.compose([Validators.required])),
// //     client : new FormControl(),
//   });

  constructor(private sourcesService: SourcesService, private modalService: NgbModal) { this.saveSource();

      this.sourcesService.Refreshrequired.subscribe(result=>{
        this.saveSource();
      });
    }

  @ViewChild('content') addview !: ElementRef

  ngOnInit(): void {
      }

  errormessage = '';
  errorclass = '';
  saveresponse: any;
  source: any;
  editdata: any;

//   destdata:any;

 sourceForm = new FormGroup({
      id: new FormControl({value:0, disabled:true} ),
      name: new FormControl('', Validators.compose([Validators.required, Validators.minLength(5)])),
      url: new FormControl('', Validators.compose([Validators.required])),
//     client : new FormControl(),
  });

//   sourceData_post: any;
  saveSource(){
      if(this.sourceForm.valid){
       console.log(this.sourceForm.getRawValue());
          this.saveresponse = this.sourceForm.getRawValue();
          this.sourcesService.addSource(this.saveresponse).subscribe(result => {
              this.saveresponse = result;
              console.log(this.saveresponse)
              this.errormessage = "Saved Sucessfully";
              this.errorclass = "sucessmessage";
              setTimeout(()=>{
                  this.modalService.dismissAll();
              },1000)
          });

      }else{
          this.errormessage = "Please enter valid data";
          this.errorclass = "errormessage";
      }
//       this.modalService.dismissAll()
  }

  LoadEditData(source: any) {
      this.open();
      this.sourcesService.GetSourcebyid(source).subscribe(result => {
          this.editdata = result;
          console.log(this.editdata)
          this.sourceForm.setValue({id:this.editdata.id, name:this.editdata.name,url:this.editdata.url});
      });
  }

  Clearform(){
      this.sourceForm.setValue({id:0, name:'',url:''})
  }

  open() {
      this.Clearform();
      this.modalService.open(this.addview,{ ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      }, (reason) => {
      });
  }

  private getDismissReason(reason: any): string {
      if (reason === ModalDismissReasons.ESC) {
          return 'by pressing ESC';
      } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
          return 'by clicking on a backdrop';
      } else {
          return `with: ${reason}`;
      }
  }

  get name() {
      return this.sourceForm.get("name");
  }
  get url() {
      return this.sourceForm.get("url");
  }

}

</code>```

component.html

```<code><div class="modal" role="dialog">
<ng-template #content let-modal>
  <div class="modal-content" style="z-index: 1056">
    <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">Source Form</h4>
        <button type="button" #closebtn class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
    </div>
    <div class="modal-body">
      <form method="post" [formGroup]="sourceForm" (ngSubmit)="saveSource()">

         <div class="mb-3">
           <label>Id:</label>
           <div class="input-group">
             <input name="id" class="form-control" formControlName="id">
           </div>
<!--           <span *ngIf="name && name.invalid" class="errormessage">Please Enter valid name</span>-->
         </div>

        <div class="mb-3">
           <label>Source Name:</label>
           <div class="input-group">
             <input name="name" class="form-control" formControlName="name" required>
           </div>
           <span *ngIf="name && name.invalid" class="errormessage">Please Enter valid name</span>
         </div>

         <div class="mb-3">
           <label>Source URL:</label>
           <div class="input-group">
             <input name="url" class="form-control" formControlName="url">
           </div>
           <span *ngIf="url && url.invalid" class="errormessage">Please Enter valid url</span>
         </div>

          <div class="mb-3">

            <div class="input-group">
              <button [disabled]="sourceForm.invalid" type="submit" class="btn btn-primary">Save</button>
            </div>
            <span [ngClass]="errorclass" >{{errormessage}}</span>
        </div>
      </form>
      </div>
    <div class="modal-footer">
        <button style="display: none;" type="button" class="btn btn-outline-dark"
            (click)="modal.close('Save click')">Save</button>
    </div>
  </div>
</ng-template>
</div>
<button class="btn btn-primary" #popupbtn id="popupbtn" (click)="open()">Add New</button>

</code>```

Body:
i am working on a project and need to implement ngb bootstrap  modal in angular 13, and complete the operation of put and post on the same model, but when I click on edit button it loads the data and create new object insted of updating old one. Stucked from last 3 days

service.ts

 addSource(source : sources[]): Observable<sources[]>{
      return this.http.post<sources[]> (this.API_URL, source).pipe(
      tap(() => {
        this._refreshrequired.next();
      })
    );
      //console.log(user);
      }

component.ts

import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { sources } from '../sources';
import { SourcesService } from '../sources.service';
import { FormGroup, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import {SourcesComponent} from '../sources/sources.component';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-add-source',
  templateUrl: './add-source.component.html',
  styleUrls: ['./add-source.component.css']
})
export class AddSourceComponent implements OnInit {
   // a form for entering and validating data
//    sourceForm = new FormGroup({
//     name : new FormControl('', Validators.compose([Validators.required, Validators.minLength(5)])),
//     url : new FormControl('', Validators.compose([Validators.required])),
// //     client : new FormControl(),
//   });

  constructor(private sourcesService: SourcesService, private modalService: NgbModal) { this.saveSource();

      this.sourcesService.Refreshrequired.subscribe(result=>{
        this.saveSource();
      });
    }

  @ViewChild('content') addview !: ElementRef

  ngOnInit(): void {
      }

  errormessage = '';
  errorclass = '';
  saveresponse: any;
  source: any;
  editdata: any;

//   destdata:any;

 sourceForm = new FormGroup({
      id: new FormControl({value:0, disabled:true} ),
      name: new FormControl('', Validators.compose([Validators.required, Validators.minLength(5)])),
      url: new FormControl('', Validators.compose([Validators.required])),
//     client : new FormControl(),
  });

//   sourceData_post: any;
  saveSource(){
      if(this.sourceForm.valid){
       console.log(this.sourceForm.getRawValue());
          this.saveresponse = this.sourceForm.getRawValue();
          this.sourcesService.addSource(this.saveresponse).subscribe(result => {
              this.saveresponse = result;
              console.log(this.saveresponse)
              this.errormessage = "Saved Sucessfully";
              this.errorclass = "sucessmessage";
              setTimeout(()=>{
                  this.modalService.dismissAll();
              },1000)
          });

      }else{
          this.errormessage = "Please enter valid data";
          this.errorclass = "errormessage";
      }
//       this.modalService.dismissAll()
  }

  LoadEditData(source: any) {
      this.open();
      this.sourcesService.GetSourcebyid(source).subscribe(result => {
          this.editdata = result;
          console.log(this.editdata)
          this.sourceForm.setValue({id:this.editdata.id, name:this.editdata.name,url:this.editdata.url});
      });
  }

  Clearform(){
      this.sourceForm.setValue({id:0, name:'',url:''})
  }

  open() {
      this.Clearform();
      this.modalService.open(this.addview,{ ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      }, (reason) => {
      });
  }

  private getDismissReason(reason: any): string {
      if (reason === ModalDismissReasons.ESC) {
          return 'by pressing ESC';
      } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
          return 'by clicking on a backdrop';
      } else {
          return `with: ${reason}`;
      }
  }

  get name() {
      return this.sourceForm.get("name");
  }
  get url() {
      return this.sourceForm.get("url");
  }

}

component.html

<ng-template #content let-modal>

Source Form

        <button type="button" #closebtn class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>

      <form method="post" [formGroup]="sourceForm" (ngSubmit)="saveSource()">

           Id:

             <input name="id" class="form-control" formControlName="id">

           Source Name:

             <input name="name" class="form-control" formControlName="name" required>

           Please Enter valid name

           Source URL:

             <input name="url" class="form-control" formControlName="url">

           Please Enter valid url

              <button [disabled]="sourceForm.invalid" type="submit" class="btn btn-primary">Save</button>

            {{errormessage}}

      </form>

        <button style="display: none;" type="button" class="btn btn-outline-dark"
            (click)="modal.close('Save click')">Save</button>

</ng-template>

<button class="btn btn-primary" #popupbtn id="popupbtn" (click)="open()">Add New</button>


问:
how to make readable the url of an image that comes from an api that I created?
I created an api it's been 2 weeks. the api works well but I can't retrieve the images from this api during my HTTP requests.

My Controller Api/admin/AgencyController

`

```<code></code>```

public function store(AgencyRequest $request)
{

```<code>    if ($request->hasFile('logo')) {

        $path = $request->file('logo')->store('logo','public');
       }
    $agency=Agency::create([
        'name'=>$request->name,
        'headquarters'=>$request->headquarters,
        'email'=>$request->email,
        'logo'=>$path,
        'phone_number'=>$request->phone_number,
        'state'=>$request->state,
        'password'=>bcrypt($request->password),
    ]);

    return new AgencyResource($agency);
}
</code>```
```<code>
</code>```

`

My index file

`

```<code>  @foreach ($datas as $agencies)
                                        @forelse ($agencies as $agency)
                                            <tr>
                                                <td><img src="{{ url('https://kipart.stillforce.tech/storage/'.$agency->logo) }}" width="48" alt="Product img"></td>
                                                <td><h5>{{ $agency->logo }}</h5></td>
                                                <td>
                                                    <a href="{{ route('admin.agencies.edit',$agency->id) }}" class="btn btn-default waves-effect waves-float btn-sm waves-green"><i class="zmdi zmdi-edit"></i></a>

                                                    <form method="POST" action="{{ route('admin.agencies.destroy', $agency->id) }}" onsubmit="return confirm('Are you sure?')">
                                                        @csrf
                                                        @method('delete')
                                                        <button type="submit" class="btn btn-default waves-effect waves-float btn-sm waves-red"  ><i class="zmdi zmdi-delete" aria-hidden="true" title="Suprimer"></i></button>

                                                       </form>
                                                </td>
                                            </tr>
</code>```

`

```<code>  @foreach ($datas as $agencies)
                                        @forelse ($agencies as $agency)
                                            <tr>
                                                <td><img src="{{ url('https://kipart.stillforce.tech/storage/'.$agency->logo) }}" width="48" alt="Product img"></td>
                                                <td><h5>{{ $agency->logo }}</h5></td>
                                                <td>
                                                    <a href="{{ route('admin.agencies.edit',$agency->id) }}" class="btn btn-default waves-effect waves-float btn-sm waves-green"><i class="zmdi zmdi-edit"></i></a>

                                                    <form method="POST" action="{{ route('admin.agencies.destroy', $agency->id) }}" onsubmit="return confirm('Are you sure?')">
                                                        @csrf
                                                        @method('delete')
                                                        <button type="submit" class="btn btn-default waves-effect waves-float btn-sm waves-red"  ><i class="zmdi zmdi-delete" aria-hidden="true" title="Suprimer"></i></button>

                                                       </form>
                                                </td>
                                            </tr>
</code>```

When I do a test registration of an agency. all the data is registered but when I retrieve the image to a flutter client or a laravel client the image does not appear but all the data is called

Body:
I created an api it's been 2 weeks. the api works well but I can't retrieve the images from this api during my HTTP requests.

My Controller Api/admin/AgencyController

`

public function store(AgencyRequest $request)
{

    if ($request->hasFile('logo')) {

        $path = $request->file('logo')->store('logo','public');
       }
    $agency=Agency::create([
        'name'=>$request->name,
        'headquarters'=>$request->headquarters,
        'email'=>$request->email,
        'logo'=>$path,
        'phone_number'=>$request->phone_number,
        'state'=>$request->state,
        'password'=>bcrypt($request->password),
    ]);

    return new AgencyResource($agency);
}

`

My index file

`

  @foreach ($datas as $agencies)
                                        @forelse ($agencies as $agency)

                                                logo) }}" width="48" alt="Product img">

{{ $agency->logo }}

                                                    id) }}" class="btn btn-default waves-effect waves-float btn-sm waves-green">

                                                    <form method="POST" action="{{ route('admin.agencies.destroy', $agency->id) }}" onsubmit="return confirm('Are you sure?')">
                                                        @csrf
                                                        @method('delete')
                                                        <button type="submit" class="btn btn-default waves-effect waves-float btn-sm waves-red"  ></button>

                                                       </form>

`

  @foreach ($datas as $agencies)
                                        @forelse ($agencies as $agency)

                                                logo) }}" width="48" alt="Product img">

{{ $agency->logo }}

                                                    id) }}" class="btn btn-default waves-effect waves-float btn-sm waves-green">

                                                    <form method="POST" action="{{ route('admin.agencies.destroy', $agency->id) }}" onsubmit="return confirm('Are you sure?')">
                                                        @csrf
                                                        @method('delete')
                                                        <button type="submit" class="btn btn-default waves-effect waves-float btn-sm waves-red"  ></button>

                                                       </form>

When I do a test registration of an agency. all the data is registered but when I retrieve the image to a flutter client or a laravel client the image does not appear but all the data is called


问:
Is there any Pulsar UI where messages can be updated/produced?
The only UI I found was Pulsar Manager , which don't even allow to see the messages in a topic.
By any chance is there a Pulsar UI with better features where messages can be manipulated?</p>


问:
I am try to insert data into oracle from a pandas dataframe and this error is coming '''Python value of type numpy.int64 not supported.'''
This is my code

imp = df[['ACCOUNT_TRANSACTION_ID','ID_ACC_TRAN']]
impt = [tuple(x) for x in imp.values]
impt
imptext = 'INSERT INTO ACCOUNT_TRANSACTION_DATA_TEMP(ACCOUNT_TRANSACTION_ID,ID_ACC_TRAN) values (: 1,: 2)'
cur.executemany(imptext,[x for x in impt])
connect.commit()
```
<p>But i am get an error like</p>
```NotSupportedError: Python value of type numpy.int64 not supported.
```

I tried converting the data type to normal python int that does'nt work to .can anyone help me on this

Any answer and help for the question is appreciated

Body:
This is my code

imp = df[['ACCOUNT_TRANSACTION_ID','ID_ACC_TRAN']]
impt = [tuple(x) for x in imp.values]
impt
imptext = 'INSERT INTO ACCOUNT_TRANSACTION_DATA_TEMP(ACCOUNT_TRANSACTION_ID,ID_ACC_TRAN) values (: 1,: 2)'
cur.executemany(imptext,[x for x in impt])
connect.commit()

But i am get an error like

NotSupportedError: Python value of type numpy.int64 not supported.

I tried converting the data type to normal python int that does'nt work to .can anyone help me on this

Any answer and help for the question is appreciated


问:
VideoJS - Is there a way to display the video duration in HH:SS format before the video plays
I would like to display the duration of the video in the VideoJS skin as a thumbnail while the video is not playing.

I have the following code but cannot see how to implement this via JS SDK in React.

Here is an example of how I would like the duration display to look:

video-js-duration-display-preview-window

Here is my code so far:

const VideoJsPlayer = ({ src, divStyle, autoPlay = true }) => {
  const videoRef = React.useRef(null);
  const playerRef = React.useRef(null);

  React.useEffect(() => {
    if (!window) return;
    if (window.videojs && src) {
      if (!playerRef.current) {
        const videoElement = videoRef.current;

        if (!videoElement) return;

        playerRef.current = window.videojs(videoElement);
      } else {
        // You can update player in the `else` block here, for example:
        // player.autoplay(options.autoplay);
        // player.src(options.sources);
      }
    }
  }, [src]);

  return (

      <video
        ref={videoRef}
        className={clsx([
          'video-js',
          'vjs-big-play-centered',
          styles.videoJsClass,
        ])}
        controls
        autoPlay={autoPlay}
        preload="auto"
        width="100%"
        height="400px"
        data-setup="{}"
      >
        <source src={src + '#t=0.001'} type="video/mp4" />

          To view this video please enable JavaScript, and consider upgrading to
          a web browser that supports HTML5 video

      </video>

  );
};
```

I can see the documentation here and have access to the player object by playerRef.current. But how to add this title like pictured above?

Body:
I would like to display the duration of the video in the VideoJS skin as a thumbnail while the video is not playing.

I have the following code but cannot see how to implement this via JS SDK in React.

Here is an example of how I would like the duration display to look:

video-js-duration-display-preview-window

Here is my code so far:

const VideoJsPlayer = ({ src, divStyle, autoPlay = true }) => {
  const videoRef = React.useRef(null);
  const playerRef = React.useRef(null);

  React.useEffect(() => {
    if (!window) return;
    if (window.videojs && src) {
      if (!playerRef.current) {
        const videoElement = videoRef.current;

        if (!videoElement) return;

        playerRef.current = window.videojs(videoElement);
      } else {
        // You can update player in the `else` block here, for example:
        // player.autoplay(options.autoplay);
        // player.src(options.sources);
      }
    }
  }, [src]);

  return (

      <video
        ref={videoRef}
        className={clsx([
          'video-js',
          'vjs-big-play-centered',
          styles.videoJsClass,
        ])}
        controls
        autoPlay={autoPlay}
        preload="auto"
        width="100%"
        height="400px"
        data-setup="{}"
      >
        <source src={src + '#t=0.001'} type="video/mp4" />

          To view this video please enable JavaScript, and consider upgrading to
          a web browser that supports HTML5 video

      </video>

  );
};

I can see the documentation here and have access to the player object by playerRef.current. But how to add this title like pictured above?


问:
spring data jpa null parameter to native query
exception details - Caused by : java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: exptected NUMBER got BINARY

public interface ExampleRepository extends JpaRepository {

    public static final FINDSQL = " select a, b, c from exp_attr ea, dep_attr da  where ea.id = da.id AND ea.sysId = :sysId";

    @Query(value = FINDSQL , nativeQuery=true)
    List<ProjectionInterface> getExampleDetails(@Param("sysId") Integer sysId);
}
```
<pre class="lang-java prettyprint-override"><code>public class RestApi {

    @Autowired
    private ExampleRepository exampleRepository;

    public String testJpaRepo(){
        Integer sysId = 123;
        exampleRepository.getExampleDetails(sysId);
    }
}
</code>```

public interface ProjectionInterface {

 Integer getA();

 String getB();

 String getC();

}
```

When I am passing sysId = 123, it works fine, but when sysId is null then it gives following exception

Caused by : java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: exptected NUMBER got BINARY

Body:
exception details - Caused by : java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: exptected NUMBER got BINARY

public interface ExampleRepository extends JpaRepository {

    public static final FINDSQL = " select a, b, c from exp_attr ea, dep_attr da  where ea.id = da.id AND ea.sysId = :sysId";

    @Query(value = FINDSQL , nativeQuery=true)
    List<ProjectionInterface> getExampleDetails(@Param("sysId") Integer sysId);
}

public class RestApi {

    @Autowired
    private ExampleRepository exampleRepository;

    public String testJpaRepo(){
        Integer sysId = 123;
        exampleRepository.getExampleDetails(sysId);
    }
}

public interface ProjectionInterface {

 Integer getA();

 String getB();

 String getC();

}

When I am passing sysId = 123, it works fine, but when sysId is null then it gives following exception

Caused by : java.sql.SQLSyntaxErrorException: ORA-00932: inconsistent datatypes: exptected NUMBER got BINARY


问:
Pagination Issues in AntDesign and Vue 3
Has anyone used AntDesign ever encountered the problem with Ant's pagination component? I call api with limit of 7 and total is 15 records, antD should return all 3 pages but it only calculates and outputs 2 pages? It doesn't seem to use the Math.celi function for calculations

Here are some related code snippets:

In View:

```
<p><strong>In Script:</strong></p>
<pre class="lang-js prettyprint-override"><code><script setup lang="ts">
import Pagination from "@/components/Pagination.vue";
const totalPage = ref<number>();
const current = ref(1);

async function getFile(page = 1) {
  try {
    const fileData = await request.get("api/admin/file/list", {
      params: {
        page,
        limit: 7,
        name: searchName.value.trim(),
        status: stateStatus.value,
        mimetype: typeFile.value,
        lte_size: endSize.value,
        gte_size: startSize.value,
      },
    });
    files.value = fileData.data.data;

    totalPage.value = fileData.data.count;
    console.log("Total Page:",totalPage.value) //Log the correct results
    loading.value = false;
  } catch (e) {
    console.log(e);
  }
}

  onMounted(async () => {
    await getFile();
});

//Tính phân trang
async function pagination(pageNumber: number) {
  current.value = pageNumber;
    files.value = [];
    await getFile(pageNumber);
}
</script>
</code>```

Hope to get help from everyone, thanks a lot

Body:
Has anyone used AntDesign ever encountered the problem with Ant's pagination component? I call api with limit of 7 and total is 15 records, antD should return all 3 pages but it only calculates and outputs 2 pages? It doesn't seem to use the Math.celi function for calculations

Here are some related code snippets:

In View:

In Script:

Hope to get help from everyone, thanks a lot


问:
Multiple root tags /top level element is not completed
I'm tring to build a basic chat app in android , is my first app and i'm trying to learn
Right now i'm getting stuck at the Sign in and Sign Up interface because i have some errors in AndroidManifest.xml

here is the code :

`

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="http://schemas.android.com/tools"
    package="com.example.icom"/>
<application
android:allowBackup="true"
android:fullBackupContent="false"
android:icon="@mipmap/ic_launcher"
android:label="Icom Chat"
android:icon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Icom"
tools:ignore="DataExtractionRules"
android:name=".activities.SignUpActivity"
android:windowSoftInputMode="adjustResize"
tools:ignore="MissingClass,WrongManifestParent" />
<activity
android:name=".activities.SignInActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize"
tools:ignore="MissingClass,WrongManifestParent"
android:name=".MainActivity"
tools:ignore=".MissingClass,WrongManifestParent" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</manifest>
</code>```

`
I receive the following errors :
Multiple root tags
Top level element is not completed

Can someone explain to me how i can fix this ?
Thank you very much .

Run the Sign In and SignUp interface for aan Chat app
It may sound stupid but i've tried a video tutorial from yt

Body:
I'm tring to build a basic chat app in android , is my first app and i'm trying to learn
Right now i'm getting stuck at the Sign in and Sign Up interface because i have some errors in AndroidManifest.xml

here is the code :

`

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:tools="http://schemas.android.com/tools"
    package="com.example.icom"/>
<application
android:allowBackup="true"
android:fullBackupContent="false"
android:icon="@mipmap/ic_launcher"
android:label="Icom Chat"
android:icon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Icom"
tools:ignore="DataExtractionRules"
android:name=".activities.SignUpActivity"
android:windowSoftInputMode="adjustResize"
tools:ignore="MissingClass,WrongManifestParent" />
<activity
android:name=".activities.SignInActivity"
android:exported="true"
android:windowSoftInputMode="adjustResize"
tools:ignore="MissingClass,WrongManifestParent"
android:name=".MainActivity"
tools:ignore=".MissingClass,WrongManifestParent" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</manifest>

`
I receive the following errors :
Multiple root tags
Top level element is not completed

Can someone explain to me how i can fix this ?
Thank you very much .

Run the Sign In and SignUp interface for aan Chat app
It may sound stupid but i've tried a video tutorial from yt


问:
Change Value of Passed Range Object in Excel
I have an User-Defined function in Excel Vba. I want to change the values of the cells in the range passed through as parameter using this function.

```<code>=ChangeCellValues(J18:J19)
</code>```

When I call the function in formula editor as above in excel, the execution stops in the line where the assignment is performed and I get an value error in runtime. I have tried many syntactical options but no way.

However when I call the function in a main sub procedure, it works somehow and changes the values of the cells

```<code>Function ChangeCellValues(myrange As range) As Double
    Dim i As Integer
    For i = 1 To myrange.Rows.count
        'None of them works.
        mycell.Cells(i, 1).Value = 1
        mycell.Cells.Item(i, 1).Value = 1
        mycell.Item(i, 1).Value = 1
    Next i
    ChangeCellValues = 0
 End Function
 Sub Main()
     Debug.Print ChangeCellValues(range("J17:J18")) 'This works.
     range("J17").Value = 10 'This works also.
 End Sub
</code>```

In essence, the question is how can I change the values of some cells in a worksheet passed through as argument in Excel Vba function?

Body:
I have an User-Defined function in Excel Vba. I want to change the values of the cells in the range passed through as parameter using this function.

=ChangeCellValues(J18:J19)

When I call the function in formula editor as above in excel, the execution stops in the line where the assignment is performed and I get an value error in runtime. I have tried many syntactical options but no way.

However when I call the function in a main sub procedure, it works somehow and changes the values of the cells

Function ChangeCellValues(myrange As range) As Double
    Dim i As Integer
    For i = 1 To myrange.Rows.count
        'None of them works.
        mycell.Cells(i, 1).Value = 1
        mycell.Cells.Item(i, 1).Value = 1
        mycell.Item(i, 1).Value = 1
    Next i
    ChangeCellValues = 0
 End Function
 Sub Main()
     Debug.Print ChangeCellValues(range("J17:J18")) 'This works.
     range("J17").Value = 10 'This works also.
 End Sub

In essence, the question is how can I change the values of some cells in a worksheet passed through as argument in Excel Vba function?


问:
Flutter Edit and new Item on same component
At the moment I have a component that edits the info of a Record, it comes from localsorage so I have a FutureBuilder. I want to reuse this component for new records as well but the examples that I find online always have separate components for edit/add.
What is the best practice for this?</p>
```<code>  Widget build(BuildContext context) {
    txtDuration.text = '';
    txtDescription.text = '';
    return Scaffold(
      appBar: AppBar(title: const Text('Detail')),
      body: FutureBuilder<Record?>(
          future: recordController.getRecord(widget.recordId),
          builder: (context, response) {
            if (!response.hasData) {
              return const Center(child: Text('Loading..'));
            } else {
              var result = response.data ?? [];
              return SingleChildScrollView(
                  child: Column(children: [
                Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        TextFormField(
                          //2. textform field with validator logic
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "field cannot be empty";
                            }
                            return null;
                          },
                          controller: txtDescription,
                          decoration: const InputDecoration(
                            hintText: 'Enter the first number',
                            labelText: 'First Number',
                          ),
                        ),
                        const SizedBox(height: 20),
                        TextFormField(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "field cannot be empty";
                            }
                            return null;
                          },
                          controller: txtDuration,
                          minLines: 1,
                          maxLines: 10,
                          decoration: const InputDecoration(
                            hintText: 'Enter the second number',
                            labelText: 'Second Number',
                          ),
                        ),
                        const SizedBox(height: 20),
                        new DropdownButtonHideUnderline(
                          child: new FutureBuilder<List<Category>>(
                            future: categoryController.getAll(),
                            builder: (context, snapshot) {
                              if (snapshot.hasError) {
                                return new Container();
                              } else if (snapshot.hasData) {
                                return DropdownButton<String>(
                                  isExpanded: true,
                                  value: dropdownValue,
                                  hint: Text('Select a category'),
                                  icon: const Icon(Icons.arrow_drop_down),
                                  onChanged: (String? newValue) {
                                    setState(() {
                                      dropdownValue = newValue!;
                                    });
                                  },
                                  items: snapshot.data!
                                      .map<DropdownMenuItem<String>>(
                                          (Category value) {
                                    return DropdownMenuItem<String>(
                                      value: value.title,
                                      child: Text(value.title),
                                    );
                                  }).toList(),
                                );
                              } else {
                                return CircularProgressIndicator();
                              }
                            },
                          ),
                        ),
                      ],
                    )),
              ]));
            }
          }),
      bottomNavigationBar: const MenuBottom(),
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.save), onPressed: saveSession),
    );
  }
</code>```

Body:
At the moment I have a component that edits the info of a Record, it comes from localsorage so I have a FutureBuilder. I want to reuse this component for new records as well but the examples that I find online always have separate components for edit/add.
What is the best practice for this?

  Widget build(BuildContext context) {
    txtDuration.text = '';
    txtDescription.text = '';
    return Scaffold(
      appBar: AppBar(title: const Text('Detail')),
      body: FutureBuilder<Record?>(
          future: recordController.getRecord(widget.recordId),
          builder: (context, response) {
            if (!response.hasData) {
              return const Center(child: Text('Loading..'));
            } else {
              var result = response.data ?? [];
              return SingleChildScrollView(
                  child: Column(children: [
                Form(
                    key: _formKey,
                    child: Column(
                      children: [
                        TextFormField(
                          //2. textform field with validator logic
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "field cannot be empty";
                            }
                            return null;
                          },
                          controller: txtDescription,
                          decoration: const InputDecoration(
                            hintText: 'Enter the first number',
                            labelText: 'First Number',
                          ),
                        ),
                        const SizedBox(height: 20),
                        TextFormField(
                          validator: (value) {
                            if (value == null || value.isEmpty) {
                              return "field cannot be empty";
                            }
                            return null;
                          },
                          controller: txtDuration,
                          minLines: 1,
                          maxLines: 10,
                          decoration: const InputDecoration(
                            hintText: 'Enter the second number',
                            labelText: 'Second Number',
                          ),
                        ),
                        const SizedBox(height: 20),
                        new DropdownButtonHideUnderline(
                          child: new FutureBuilder<List<Category>>(
                            future: categoryController.getAll(),
                            builder: (context, snapshot) {
                              if (snapshot.hasError) {
                                return new Container();
                              } else if (snapshot.hasData) {
                                return DropdownButton<String>(
                                  isExpanded: true,
                                  value: dropdownValue,
                                  hint: Text('Select a category'),
                                  icon: const Icon(Icons.arrow_drop_down),
                                  onChanged: (String? newValue) {
                                    setState(() {
                                      dropdownValue = newValue!;
                                    });
                                  },
                                  items: snapshot.data!
                                      .map<DropdownMenuItem<String>>(
                                          (Category value) {
                                    return DropdownMenuItem<String>(
                                      value: value.title,
                                      child: Text(value.title),
                                    );
                                  }).toList(),
                                );
                              } else {
                                return CircularProgressIndicator();
                              }
                            },
                          ),
                        ),
                      ],
                    )),
              ]));
            }
          }),
      bottomNavigationBar: const MenuBottom(),
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.save), onPressed: saveSession),
    );
  }


问:
C# EF - DBContext the best practice for updating objects in memory
I'm creating an online text editor, where the user connects with the application using WebSocket.

When connected, an object called UserControl is created and maintained with a copy of the entity in memory until the user disconnects.

As the original code is too big and complex to understand, here's a minimalist example:

```<code>public class UserControl
{
    public int Id => Entity.Id;
    public int LastUpdateId => Entity.LastUpdate;

    private readonly User Entity;
    private readonly DatabaseConnection Database;

    public UserControl(DatabaseConnection database, User entity)
    {
        Entity = entity;
        Database = database;
    }

    public async void Update()
    {
        var context = Database.GetContext();

        User user = await context.Users.FirstAsync(a => a.Id == Id);
        user.LastUpdate++;

        if (context.SaveChanges() > 0)
            Entity.LastUpdate = user.LastUpdate;

        context.Dispose();
    }
}
</code>```

As you can see, any change that needs updating in the database a new DBContext is created, then I look for the entity again to make the change and finally I update the entity that was in memory.

This process is causing confusion when the complexity increases.

I thought about the possibility of simplifying the update process by keeping the entity's DBContext open:

```<code>public class UserControl
{
    public int Id => Entity.Id;
    public int LastUpdateId => Entity.LastUpdate;

    private readonly User Entity;
    private readonly DatabaseContext Context;

    public UserControl(DatabaseContext context, User entity)
    {
        Entity = entity;
        Context = context;
    }

    public async void Update()
    {
        Entity.LastUpdate++;
        await Context.SaveChangesAsync();
    }
}
</code>```

However, I looked a lot about good practices for using the DBContext and they always say that the lifetime needs to be very short.

Does anyone have any suggestions for me to improve the structure of my code?

I'm aware of the async/lock issues from the example code, the idea is
just to represent as simply as possible how I'm dealing with the
entity update issue in memory.

Body:
I'm creating an online text editor, where the user connects with the application using WebSocket.

When connected, an object called UserControl is created and maintained with a copy of the entity in memory until the user disconnects.

As the original code is too big and complex to understand, here's a minimalist example:

public class UserControl
{
    public int Id => Entity.Id;
    public int LastUpdateId => Entity.LastUpdate;

    private readonly User Entity;
    private readonly DatabaseConnection Database;

    public UserControl(DatabaseConnection database, User entity)
    {
        Entity = entity;
        Database = database;
    }

    public async void Update()
    {
        var context = Database.GetContext();

        User user = await context.Users.FirstAsync(a => a.Id == Id);
        user.LastUpdate++;

        if (context.SaveChanges() > 0)
            Entity.LastUpdate = user.LastUpdate;

        context.Dispose();
    }
}

As you can see, any change that needs updating in the database a new DBContext is created, then I look for the entity again to make the change and finally I update the entity that was in memory.

This process is causing confusion when the complexity increases.

I thought about the possibility of simplifying the update process by keeping the entity's DBContext open:

public class UserControl
{
    public int Id => Entity.Id;
    public int LastUpdateId => Entity.LastUpdate;

    private readonly User Entity;
    private readonly DatabaseContext Context;

    public UserControl(DatabaseContext context, User entity)
    {
        Entity = entity;
        Context = context;
    }

    public async void Update()
    {
        Entity.LastUpdate++;
        await Context.SaveChangesAsync();
    }
}

However, I looked a lot about good practices for using the DBContext and they always say that the lifetime needs to be very short.

Does anyone have any suggestions for me to improve the structure of my code?

I'm aware of the async/lock issues from the example code, the idea is
just to represent as simply as possible how I'm dealing with the
entity update issue in memory.


问:
How to check URL is returning 200 response or not using Javascript in AWS LAMDA
enter image description here
I have a requirement in my project ,where I need to the check the URL is working or not in Javascript. If that URL is working in need to get 200 response code

I tried this code,with this code I getting error. I am not getting 200 response

```<code>function checkLink(url) {
  var http = new XMLHttpRequest();

      http.open('GET',url, true);
       http.setRequestHeader("Access-Control-Allow-Origin","https://vivr.pgf-life.co.jp/1/top");
      http.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
      http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      http.send();
      console.log("status=",http.status);
      if(http.status===404)
      return false;
      else
      return true;
  }
var a=checkLink("https://www.google.com/")
console.log(a);
</code>```

Body:
enter image description here
I have a requirement in my project ,where I need to the check the URL is working or not in Javascript. If that URL is working in need to get 200 response code

I tried this code,with this code I getting error. I am not getting 200 response

function checkLink(url) {
  var http = new XMLHttpRequest();

      http.open('GET',url, true);
       http.setRequestHeader("Access-Control-Allow-Origin","https://vivr.pgf-life.co.jp/1/top");
      http.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT");
      http.setRequestHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      http.send();
      console.log("status=",http.status);
      if(http.status===404)
      return false;
      else
      return true;
  }
var a=checkLink("https://www.google.com/")
console.log(a);


问:
Expected unqualified-id before numeric constant error
I have an enum structure like this. I am getting the above error on this enum structure. Me not understanding why this error coming</p>
```<code>typedef enum
{
a=-3,b=-2,c=-1,d=0,e=1,f=2,

}Variable;
</code>```

Body:
I have an enum structure like this. I am getting the above error on this enum structure. Me not understanding why this error coming

typedef enum
{
a=-3,b=-2,c=-1,d=0,e=1,f=2,

}Variable;


问:
creating matrix of chars and read strings in Java
gritting's

I'm new in Java and I'm trying for 2 days now to fix a bug in my code
I wanted to create a matrix of chars (user input) that look for the string (user input) inside the rows/columns/main diagonal and secondery diagonal

Evrything works except the second diagonal.
I used the debuger and it seems that no matter what I do I can't reach to a point I able to store what's inside the second diagonal in order..

please help thank you

you can try with the matrix:

h b q c c

p h n t x

o j e t l

h e t l o

p r q s l

string: cte

size = 5

```<code>import java.util.Scanner;

public class Main {

public static boolean is_equal(char[] arr1, String str)
// check if one dimension array and string are equal.
{
    if (arr1.length != str.length())
    {
        return false;
    }

    for(int i =0; i < arr1.length; i++)
    {
        if (arr1[i] != str.charAt(i))
        {
            return false;
        }
    }
    return true;
}

public static int[] insert_values_to_array(int val1, int val2, int val3, int val4)
{
    int[] arr = new int[4];
    arr[0] = val1;
    arr[1] = val2;
    arr[2] = val3;
    arr[3] = val4;

    return arr;
}

public static int absolute_num(int num)
{
    if (num < 0)
    {
        num = num * -1;
    }
    return num;
}

public static int[] find_str(String string, char[][] arr)
{
    int i, j, k, m;

    // if the string have grater length from the rows and columns of the matrix than the string couldn't be found.
    if(string.length() > arr[0].length && string.length() > arr.length)
    {
        return null;
    }

    char[] row = new char[string.length()], col = new char[string.length()], main_d = new char[string.length()],
            sec_d = new char[string.length()];

        for(k = 0, m = 0; k <= absolute_num(arr.length - string.length()) && m <= absolute_num(arr.length - string.length()); k++, m++)
        {
            for(i =k; i < arr.length + k && i < string.length() + k; i++)
            {
                for (j = m; j < arr.length + m && j < string.length() + m; j++)
                {
                    row[j-m] = arr[i-m][j];
                    col[j-m] = arr[j][i-k];
                    if (i + j == arr.length-1 + k)
                    {
                        sec_d[i-k] = arr[i][j];
                    }

                    if (i == j)
                    {
                        main_d[i-k] = arr[i][i];
                    }
                }
                if(is_equal(row, string))
                {
                    return insert_values_to_array(i-k, m, i-k, m+string.length()-1);
                }
                else if(is_equal(col, string))
                {
                    return insert_values_to_array(j-string.length(), i-k, k+string.length()-1, i-k);
                }
                if(is_equal(main_d, string))
                {
                    return insert_values_to_array(k, m, string.length()-1 + k, string.length()-1 + m);
                }

                if(is_equal(sec_d, string))
                {
                    return insert_values_to_array(k, string.length()-1+m, string.length()-1+k, m);
                }
            }
        }

    return null;
}

public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);

    System.out.println("please enter a string: ");
    String str = inp.next();

    System.out.println("please enter the number of rows and columns in the array: ");
    int n = inp.nextInt();

    char[][] arr = new char[n][n];

    System.out.println("fill the array with chars: ");

    for(int i =0; i<n; i++)
        for (int j = 0; j<n; j++)
            arr[i][j] = inp.next().charAt(0);

    int[] result = find_str(str, arr);

    if(result == null)
    {
        System.out.println("string not in array.");
    }
    else
    {
        for(int i =0; i<n; i++) {

            for (int j = 0; j < n; j++) {
                System.out.print(" " + arr[i][j]);

            }
            System.out.println();
        }
        System.out.println("(" + result[0] + ", " + result[1] + ")" + ", (" + result[2] + ", " + result[3] + ")");
    }

}
</code>```

}

Body:
gritting's

I'm new in Java and I'm trying for 2 days now to fix a bug in my code
I wanted to create a matrix of chars (user input) that look for the string (user input) inside the rows/columns/main diagonal and secondery diagonal

Evrything works except the second diagonal.
I used the debuger and it seems that no matter what I do I can't reach to a point I able to store what's inside the second diagonal in order..

please help thank you

you can try with the matrix:

h b q c c

p h n t x

o j e t l

h e t l o

p r q s l

string: cte

size = 5

import java.util.Scanner;

public class Main {

public static boolean is_equal(char[] arr1, String str)
// check if one dimension array and string are equal.
{
    if (arr1.length != str.length())
    {
        return false;
    }

    for(int i =0; i < arr1.length; i++)
    {
        if (arr1[i] != str.charAt(i))
        {
            return false;
        }
    }
    return true;
}

public static int[] insert_values_to_array(int val1, int val2, int val3, int val4)
{
    int[] arr = new int[4];
    arr[0] = val1;
    arr[1] = val2;
    arr[2] = val3;
    arr[3] = val4;

    return arr;
}

public static int absolute_num(int num)
{
    if (num < 0)
    {
        num = num * -1;
    }
    return num;
}

public static int[] find_str(String string, char[][] arr)
{
    int i, j, k, m;

    // if the string have grater length from the rows and columns of the matrix than the string couldn't be found.
    if(string.length() > arr[0].length && string.length() > arr.length)
    {
        return null;
    }

    char[] row = new char[string.length()], col = new char[string.length()], main_d = new char[string.length()],
            sec_d = new char[string.length()];

        for(k = 0, m = 0; k <= absolute_num(arr.length - string.length()) && m <= absolute_num(arr.length - string.length()); k++, m++)
        {
            for(i =k; i < arr.length + k && i < string.length() + k; i++)
            {
                for (j = m; j < arr.length + m && j < string.length() + m; j++)
                {
                    row[j-m] = arr[i-m][j];
                    col[j-m] = arr[j][i-k];
                    if (i + j == arr.length-1 + k)
                    {
                        sec_d[i-k] = arr[i][j];
                    }

                    if (i == j)
                    {
                        main_d[i-k] = arr[i][i];
                    }
                }
                if(is_equal(row, string))
                {
                    return insert_values_to_array(i-k, m, i-k, m+string.length()-1);
                }
                else if(is_equal(col, string))
                {
                    return insert_values_to_array(j-string.length(), i-k, k+string.length()-1, i-k);
                }
                if(is_equal(main_d, string))
                {
                    return insert_values_to_array(k, m, string.length()-1 + k, string.length()-1 + m);
                }

                if(is_equal(sec_d, string))
                {
                    return insert_values_to_array(k, string.length()-1+m, string.length()-1+k, m);
                }
            }
        }

    return null;
}

public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);

    System.out.println("please enter a string: ");
    String str = inp.next();

    System.out.println("please enter the number of rows and columns in the array: ");
    int n = inp.nextInt();

    char[][] arr = new char[n][n];

    System.out.println("fill the array with chars: ");

    for(int i =0; i<n; i++)
        for (int j = 0; j<n; j++)
            arr[i][j] = inp.next().charAt(0);

    int[] result = find_str(str, arr);

    if(result == null)
    {
        System.out.println("string not in array.");
    }
    else
    {
        for(int i =0; i<n; i++) {

            for (int j = 0; j < n; j++) {
                System.out.print(" " + arr[i][j]);

            }
            System.out.println();
        }
        System.out.println("(" + result[0] + ", " + result[1] + ")" + ", (" + result[2] + ", " + result[3] + ")");
    }

}

}


问:
Get YouTube Channel views in asp.net
In YouTube Data API V3 how can I get views of my channel?

I can't find right documentation.

I try to search in YouTube documentation.

Title: Get YouTube Channel views in asp.net


问:
How to Install Debug Symbols for libc on Ubuntu 22.04?
Before Ubuntu 20.04, I can install debug symbols for libc by installing the libc6-dbg package (which contains a long list of dynamic libraries compiled with debug symbols as shown in https://packages.ubuntu.com/focal/amd64/libc6-dbg/filelist). However, on later Ubuntu distributions, the libc6-dbg package contains only some *.debug files, as shown in the two links below.

https://packages.ubuntu.com/focal-updates/amd64/libc6-dbg/filelist

https://packages.ubuntu.com/jammy/amd64/libc6-dbg/filelist

I also search the debug symbol packages archive (http://ddebs.ubuntu.com) and found nothing.

It seems to be a known issue but without much activity. (https://bugs.launchpad.net/ubuntu/+source/glibc/+bug/1918035)

Is there still a package that gives dynamic libraries with debug symbols for libc on Ubuntu 22.04? Do I have other ways to get the debug symbols besides compiling the libc myself?


问:
What is the replacement for workbench.action.files.saveWithoutFormatting?
In an older version of VSCode there was a setting introduced to list files which to exclude from autoformatting:

workbench.action.files.saveWithoutFormatting: [
      // patterns to exclude...
]
```

But this options seem to be deprecated, what is now an equivalent replacement?

Body:
In an older version of VSCode there was a setting introduced to list files which to exclude from autoformatting:

workbench.action.files.saveWithoutFormatting: [
      // patterns to exclude...
]

But this options seem to be deprecated, what is now an equivalent replacement?


问:
React: Customise react-scroll behaviour
As per the react-scroll readme, we have to pass in

```<code>to="target"
</code>```

props to help in tracking the element and also to navigate to the element when clicked.

We have a use-case where we need to make the link active some pixels before the element reaches the top. And, when clicked on the link, it should navigate to where the start of the element.

I tried setting

```<code>offset={-200}
</code>```

to negative values. It solves the use-case of making the link active even before the element reaches the top. But, when clicked on the link, it navigates to the element with set offset, meaning, not bringing the element to the top and adding the offset pixel.

How can we customise these two behaviours? In case of click, the navigation point should be the start of element and in case of scrolling the link should become active even before the start of element is reached.

I think, if we can stop the navigate to behaviour of Link somehow then we can use onClink callback function to scroll to an element start while keeping the scrolling with mouse behaviour working with desired offset.

Please let me know if you have a way out. Thanks in advance!!

Title: React: Customise react-scroll behaviour

Body:
As per the react-scroll readme, we have to pass in

to="target"

props to help in tracking the element and also to navigate to the element when clicked.

We have a use-case where we need to make the link active some pixels before the element reaches the top. And, when clicked on the link, it should navigate to where the start of the element.

I tried setting

offset={-200}

to negative values. It solves the use-case of making the link active even before the element reaches the top. But, when clicked on the link, it navigates to the element with set offset, meaning, not bringing the element to the top and adding the offset pixel.

How can we customise these two behaviours? In case of click, the navigation point should be the start of element and in case of scrolling the link should become active even before the start of element is reached.

I think, if we can stop the navigate to behaviour of Link somehow then we can use onClink callback function to scroll to an element start while keeping the scrolling with mouse behaviour working with desired offset.

Please let me know if you have a way out. Thanks in advance!!


问:
Using PyWhatKit to Automate Message
I am trying to send same message to all nummers in a list.
I created nummer list and added the nummers there. But it works only for the first index, the first telephone number in the list.

```<code>import pywhatkit
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M") #what time is it
h,m = current_time.split(':')

h = int(h) #cascade
m = int(m)+1

nummer_list = ["+49xxx","+49xxx"] #nummer list
for nummers in nummer_list:
    pywhatkit.sendwhatmsg(nummers, "Hello Guys!", h,m,10)

</code>```

I expected to send the same message to all nummers in a list.

Title: Using PyWhatKit to Automate Message

Body:
I am trying to send same message to all nummers in a list.
I created nummer list and added the nummers there. But it works only for the first index, the first telephone number in the list.

import pywhatkit
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M") #what time is it
h,m = current_time.split(':')

h = int(h) #cascade
m = int(m)+1

nummer_list = ["+49xxx","+49xxx"] #nummer list
for nummers in nummer_list:
    pywhatkit.sendwhatmsg(nummers, "Hello Guys!", h,m,10)

I expected to send the same message to all nummers in a list.


问:
Can't update model with mongoose schema
i'm trying to make an update functionality but it doesn't update the model :( First i make a get request to get the data from the server and populate it in form(handlebars)

so, here's the router:

```<code>router.get('/edit/:id', async (req, res) => {
    const warum = await Warum.findById(req.params.id)
    res.render('edit', warum);
});

router.post('/edit/:id', (req, res) => {
    return Warum.findOneAndUpdate(req.params.id, { new: true }, {
        title: req.body.title,
        description: req.body.description,
    })
        .then(() => {
            res.redirect('/warum');
        })
        .catch((err) => {
            console.log(err);
        });
});
</code>```

that's the form:

```<code><form method="post">
    <h2>Beitrag bearbeiten</h2>
    <ul class="noBullet">
        <li>
            <label for="title">Titel:</label>
            <input type="text" name="title" value="{{title}}" />
        </li>
        <li>
            <label for="description">Beschreibung:</label>
            <textarea class="texterea" name="description">
                {{description}}
            </textarea>
        </li>
        <div>
            <button class="login-button">save</button>
        </div>
    </ul>
</form>
</code>```

and that's the schema:

```<code>const mongoose = require('mongoose')

const WarumSchema = new mongoose.Schema({
    title: String,
    description: String,

});
const Warum = mongoose.model('Warumschema', WarumSchema);
module.exports = Warum;
</code>```

I tried to change the route from post to put, but then it says 404. After clicking the save button it just redirects me, but the result is not edited.

Title: Can't update model with mongoose schema

Body:
i'm trying to make an update functionality but it doesn't update the model :( First i make a get request to get the data from the server and populate it in form(handlebars)

so, here's the router:

router.get('/edit/:id', async (req, res) => {
    const warum = await Warum.findById(req.params.id)
    res.render('edit', warum);
});

router.post('/edit/:id', (req, res) => {
    return Warum.findOneAndUpdate(req.params.id, { new: true }, {
        title: req.body.title,
        description: req.body.description,
    })
        .then(() => {
            res.redirect('/warum');
        })
        .catch((err) => {
            console.log(err);
        });
});

that's the form:

<form method="post">

Beitrag bearbeiten

            Titel:
            <input type="text" name="title" value="{{title}}" />

            Beschreibung:
            <textarea class="texterea" name="description">
                {{description}}
            </textarea>

            <button class="login-button">save</button>

</form>

and that's the schema:

const mongoose = require('mongoose')

const WarumSchema = new mongoose.Schema({
    title: String,
    description: String,

});
const Warum = mongoose.model('Warumschema', WarumSchema);
module.exports = Warum;

I tried to change the route from post to put, but then it says 404. After clicking the save button it just redirects me, but the result is not edited.


问:
How to check if a value exist in a 2d matrix array PHP
I recently started experimenting with multidimensional arrays in PHP and I was wondering what is the most effective way to check if a value exists in a 2D matrix array.

Example: I want to find if user_id = 7 exists in the 2d matrix array. How can I achieved that ?

```<code>$matrix = array();
$query = "SELECT
            CAST(AVG(r.rating_value) AS DECIMAL(10,1)) as 'rating',
            u.user_id,
            s.store_id
        FROM odr o
            INNER JOIN rating r ON o.rating_id = r.rating_id
            INNER JOIN store s ON o.store_id = s.store_id
            INNER JOIN user u ON o.user_id = u.user_id
        GROUP BY s.store_id, u.user_id
        ORDER BY rating_value;";

$result = $mysqli->query($query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 1) {
    while ($row = $result->fetch_array()) {
        $matrix[$row['user_id']][$row['store_id']] = $row['rating'];
    }
}
var_dump($matrix);

//output:
//array(2) { [41]=> array(1) { [35]=> string(3) "5.0" } [37]=> array(2) {
//[37]=> string(3) "5.0" [35]=> string(3) "5.0" } }
</code>```

Body:
I recently started experimenting with multidimensional arrays in PHP and I was wondering what is the most effective way to check if a value exists in a 2D matrix array.

Example: I want to find if user_id = 7 exists in the 2d matrix array. How can I achieved that ?

$matrix = array();
$query = "SELECT
            CAST(AVG(r.rating_value) AS DECIMAL(10,1)) as 'rating',
            u.user_id,
            s.store_id
        FROM odr o
            INNER JOIN rating r ON o.rating_id = r.rating_id
            INNER JOIN store s ON o.store_id = s.store_id
            INNER JOIN user u ON o.user_id = u.user_id
        GROUP BY s.store_id, u.user_id
        ORDER BY rating_value;";

$result = $mysqli->query($query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 1) {
    while ($row = $result->fetch_array()) {
        $matrix[$row['user_id']][$row['store_id']] = $row['rating'];
    }
}
var_dump($matrix);

//output:
//array(2) { [41]=> array(1) { [35]=> string(3) "5.0" } [37]=> array(2) {
//[37]=> string(3) "5.0" [35]=> string(3) "5.0" } }