问:
Keep checkbox checked after refreshing the page
I'm trying to fetch all objects from the favorites array and set the checkbox to checked
I've checked online and tried using the localStorage for that yet nothing works and the values aren't saved after refreshing.

Would appreciate any help!

Selected Book Component :

```<code>import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service';

export const SelectedBook = ({ selectedBook, setFavorites, favorites, removeFavorite }) => {
  const onHandleFavorite = (book, e) => {
    if (e.currentTarget.checked) {
      setFavorites([...favorites, book]);
      bookService.addFavorite(book);
    } else {
      removeFavorite(book);
    }
  };

  const isFavorite = () => {
    if (!favorites.includes(selectedBook)) {
      return false;
    } else {
      return true;
    }
  };

  return (
    <div className='selected-book-container'>
      <input type='checkbox' checked={isFavorite()} onChange={(e) => onHandleFavorite(selectedBook, e)} />
      <div className='title'>{selectedBook?.title}</div>
    </div>
  );
};
</code>```

Book Page component :

```<code>import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service.js';
import { BookList } from '../cmps/BookList';
import { SelectedBook } from '../cmps/SelectedBook.jsx';
import { utilService } from '../service/util.service';

export const BookPage = () => {
  const [books, setBooks] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [index, setIndex] = useState(0);
  const [selectedBook, setSelectedBook] = useState();

  useEffect(() => {
    bookService.favoriteQuery().then((res) => {
      setFavorites(res);
    });
  }, []);

  useEffect(() => {
    bookService.query().then((res) => {
      setBooks(res);
      setSelectedBook(res[0]);
    });
  }, []);

  document.onkeydown = checkKey;

  function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {
      if (index === 0) return;
      setIndex(index - 1);
    } else if (e.keyCode == '39') {
      if (index >= books.length - 1) return;
      setIndex(index + 1);
    }
  }
  useEffect(() => {
    setSelectedBook(books[index]);
  }, [index]);

  const removeFavorite = (book) => {
    setFavorites(favorites.filter((favorite) => favorite.id !== book.id));
    bookService.removeFavorite(selectedBook);
  };

  return (
    <div>
      <div className='main-container main-layout'>
        <div className='second'>
          <SelectedBook
            selectedBook={selectedBook}
            setFavorites={setFavorites}
            favorites={favorites}
            removeFavorite={removeFavorite}
          />
          <BookList books={favorites} removeFavorite={removeFavorite} />
        </div>
      </div>
      <div className='footer-container'>
        <section className='footer'>Footer</section>
      </div>
    </div>
  );
};
</code>```

Service :

```<code>async function favoriteQuery() {
  try {
    let favorites = await _loadeFavoriteFromStorage();
    if (!favorites) return (favorites = []);
    return favorites;
  } catch (err) {
    console.log('cannot load favorites', err);
  }
}

function _loadeFavoriteFromStorage() {
  return storageService.loadFromStorage(STORAGE_FAVORITE_KEY);
}
</code>```

Storage Service :

```<code>export const storageService = {
    loadFromStorage,
    saveToStorage
}

function saveToStorage(key, val) {
    localStorage.setItem(key, JSON.stringify(val))
}

function loadFromStorage(key) {
    var val = localStorage.getItem(key)
    return JSON.parse(val)
}
</code>```

thanks for any kind of help

答:
You're not updating localstorage each time that checked is being changed. You're calling setFavorites with a new set of favorites but this is just changing state. I would suggest creating a function within the book page component which does

```<code>function changeFavorite(book, checked){
saveToStorage(book?, checked)
rerender()
}
</code>```

and having rerender set the state of favorites to whatever is in localstorage to ensure that you have a single source of truth which is found in localstorage and that you change that and not anything else

I'll just add

```<code>    if (!favorites.includes(selectedBook)) {
      return false;
    } else {
      return true;
    }
  };
</code>```

Could really look like

```<code>const isFavorite () => favorites.includes(selectedBook)
</code>```

I also didn't quite understand how you're doing about storing the books in object storage. You should probably have an id of some sorts which you use to save favorite information with

Body:
I'm trying to fetch all objects from the favorites array and set the checkbox to checked
I've checked online and tried using the localStorage for that yet nothing works and the values aren't saved after refreshing.

Would appreciate any help!

Selected Book Component :

import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service';

export const SelectedBook = ({ selectedBook, setFavorites, favorites, removeFavorite }) => {
  const onHandleFavorite = (book, e) => {
    if (e.currentTarget.checked) {
      setFavorites([...favorites, book]);
      bookService.addFavorite(book);
    } else {
      removeFavorite(book);
    }
  };

  const isFavorite = () => {
    if (!favorites.includes(selectedBook)) {
      return false;
    } else {
      return true;
    }
  };

  return (

      <input type='checkbox' checked={isFavorite()} onChange={(e) => onHandleFavorite(selectedBook, e)} />

{selectedBook?.title}

  );
};

Book Page component :

import React, { useEffect, useState } from 'react';
import { bookService } from '../service/book.service.js';
import { BookList } from '../cmps/BookList';
import { SelectedBook } from '../cmps/SelectedBook.jsx';
import { utilService } from '../service/util.service';

export const BookPage = () => {
  const [books, setBooks] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [index, setIndex] = useState(0);
  const [selectedBook, setSelectedBook] = useState();

  useEffect(() => {
    bookService.favoriteQuery().then((res) => {
      setFavorites(res);
    });
  }, []);

  useEffect(() => {
    bookService.query().then((res) => {
      setBooks(res);
      setSelectedBook(res[0]);
    });
  }, []);

  document.onkeydown = checkKey;

  function checkKey(e) {
    e = e || window.event;
    if (e.keyCode == '37') {
      if (index === 0) return;
      setIndex(index - 1);
    } else if (e.keyCode == '39') {
      if (index >= books.length - 1) return;
      setIndex(index + 1);
    }
  }
  useEffect(() => {
    setSelectedBook(books[index]);
  }, [index]);

  const removeFavorite = (book) => {
    setFavorites(favorites.filter((favorite) => favorite.id !== book.id));
    bookService.removeFavorite(selectedBook);
  };

  return (

          <SelectedBook
            selectedBook={selectedBook}
            setFavorites={setFavorites}
            favorites={favorites}
            removeFavorite={removeFavorite}
          />
          <BookList books={favorites} removeFavorite={removeFavorite} />

Footer

  );
};

Service :

async function favoriteQuery() {
  try {
    let favorites = await _loadeFavoriteFromStorage();
    if (!favorites) return (favorites = []);
    return favorites;
  } catch (err) {
    console.log('cannot load favorites', err);
  }
}

function _loadeFavoriteFromStorage() {
  return storageService.loadFromStorage(STORAGE_FAVORITE_KEY);
}

Storage Service :

export const storageService = {
    loadFromStorage,
    saveToStorage
}

function saveToStorage(key, val) {
    localStorage.setItem(key, JSON.stringify(val))
}

function loadFromStorage(key) {
    var val = localStorage.getItem(key)
    return JSON.parse(val)
}

thanks for any kind of help

Body:
You're not updating localstorage each time that checked is being changed. You're calling setFavorites with a new set of favorites but this is just changing state. I would suggest creating a function within the book page component which does

function changeFavorite(book, checked){
saveToStorage(book?, checked)
rerender()
}

and having rerender set the state of favorites to whatever is in localstorage to ensure that you have a single source of truth which is found in localstorage and that you change that and not anything else

I'll just add

    if (!favorites.includes(selectedBook)) {
      return false;
    } else {
      return true;
    }
  };

Could really look like

const isFavorite () => favorites.includes(selectedBook)

I also didn't quite understand how you're doing about storing the books in object storage. You should probably have an id of some sorts which you use to save favorite information with


来源: stackexchange

问:
Validate Certificates on Ethereum blockchain
i have a function transferWithData(address to, uint256 amount, bytes data) it basically transfer ERC20 token but it has an additional 'data' field, in order to inject a certificate generated off-chain by an issuer.

Certificate contains:

The function ID which ensures the certificate can’t be used on an other function.

parameters which ensures the input parameters have been validated by the issuer.

validity date which ensures the certificate can’t be used after validity date.

nonce which ensures the certificate can’t be used twice.

Finally the certificate is signed by the issuer and passed as parameter in the transferWithData function.

my question is that how to verify this certificate on chain. i am able to recover the issuer address using ecrecover. but i also need to validate the certificate content. I am following this repo https://github.com/NDAXlO/ERC1400/blob/master/contracts/mocks/CertificateControllerMock.sol
thanks

答:
It seems that the repo you provided does not implement the modifier isValidCertificate as it mentioned. If you want to do certificate validation, you should implement your own modifier to fulfill that.

```<code>modifier isValidCertificate(bytes data) {
    require(something);
    // go verify with data here
    _;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
It seems that the repo you provided does not implement the modifier isValidCertificate as it mentioned. If you want to do certificate validation, you should implement your own modifier to fulfill that.

modifier isValidCertificate(bytes data) {
    require(something);
    // go verify with data here
    _;
}


问:
Django TemplateDoesNotExist Error on Windows machine
I have been following the tutorial for Django Tango with Django

I was trying to add a template as instructed on the link.
I am working with Python 2.7, Django 1.8 on a windows 7 machine.

Below is the error that I get:

```<code>TemplateDoesNotExist at /rango/
rango/index.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/rango/
Django Version: 1.8
Exception Type: TemplateDoesNotExist
Exception Value:rango/index.html
Exception Location: C:\Python27\lib\site-packages\django\template\loader.py in get_template, line 46
</code>```

```<code>Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
C:\Python27\lib\site-packages\django\contrib\admin\templates\rango\index.html (File does not exist)
C:\Python27\lib\site-packages\django\contrib\auth\templates\rango\index.html    (File does not exist)
</code>```

Below is my file structure:

```<code>tango_with_django_project
+-- rango
|   +--views.py
|   +--other files
+-- tango_with_django_project
|   +--templates
|   |   +--rango
|   |   |  +--index.html
|   +--settings.py
|   +--other files
+-- db.sqlite3
+-- manage.py`
</code>```

I have given the template path as below in settings.py:

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR,'templates')
TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)
</code>```

And have set the view as in views.py:

```<code>from django.shortcuts import render
from django.http import HttpResponse

def index(request):
   context_dict = {'boldmessage': "I am bold font from the context"}
   return render(request, 'rango/index.html', context_dict)
</code>```

Without using the template, it works fine and displays plain text. But when I do the changes required for the template, it does not work and throws the Error.
There are many links on SO with the same issue but none have worked for me.
The one with almost the same Error description and on Windows machine has a vague answer.

I have tried directly specifying the absolute path instead of getting it from os.path and have also tried placing the template folder in different paths.

Any help would be appreciated.

答:
In my case modifying INSTALLED_APPS doesn't help, so based on previos answers I just modified my settings.py in the following way:

Add import OS

Add  os.getcwd() into DIRS

So it looks like this:

```<code>...
from pathlib import Path
import os
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.getcwd()],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been following the tutorial for Django Tango with Django

I was trying to add a template as instructed on the link.
I am working with Python 2.7, Django 1.8 on a windows 7 machine.

Below is the error that I get:

TemplateDoesNotExist at /rango/
rango/index.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/rango/
Django Version: 1.8
Exception Type: TemplateDoesNotExist
Exception Value:rango/index.html
Exception Location: C:\Python27\lib\site-packages\django\template\loader.py in get_template, line 46

Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
C:\Python27\lib\site-packages\django\contrib\admin\templates\rango\index.html (File does not exist)
C:\Python27\lib\site-packages\django\contrib\auth\templates\rango\index.html    (File does not exist)

Below is my file structure:

tango_with_django_project
+-- rango
|   +--views.py
|   +--other files
+-- tango_with_django_project
|   +--templates
|   |   +--rango
|   |   |  +--index.html
|   +--settings.py
|   +--other files
+-- db.sqlite3
+-- manage.py`

I have given the template path as below in settings.py:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR,'templates')
TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)

And have set the view as in views.py:

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
   context_dict = {'boldmessage': "I am bold font from the context"}
   return render(request, 'rango/index.html', context_dict)

Without using the template, it works fine and displays plain text. But when I do the changes required for the template, it does not work and throws the Error.
There are many links on SO with the same issue but none have worked for me.
The one with almost the same Error description and on Windows machine has a vague answer.

I have tried directly specifying the absolute path instead of getting it from os.path and have also tried placing the template folder in different paths.

Any help would be appreciated.

Body:
In my case modifying INSTALLED_APPS doesn't help, so based on previos answers I just modified my settings.py in the following way:

Add import OS

Add  os.getcwd() into DIRS

So it looks like this:

...
from pathlib import Path
import os
...
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.getcwd()],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]


问:
How do I upload my apk to Slack with Github Actions
I want to upload my Flutter APK to a slack channel, Solutions I got were pretty outdated,

```<code>    name: CI

on:
  push:
    branches: [develop]
  pull_request:
    branches: [develop]

  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        shell: bash

    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          flutter-version: "2.8.1"
      - run: flutter pub get
      - run: flutter pub run flutter_native_splash:create
      - run: flutter pub run flutter_launcher_icons:main
      - run: flutter build apk
      - run: flutter build appbundle
      - uses: actions/upload-artifact@v1
        with:
          name: release-apk
          path: build/app/outputs/flutter-apk/app-release.apk
</code>```

This is the current workflow that I have, It builds and adds it to Artefacts on Actions.

答:
Easiest solution is to use one of Actions available in Marketplace:</p>
```<code>jobs:
  upload:
    runs-on: ubuntu-latest
    name: Upload APK
    steps:
      - name: Upload to slack step
        uses: adrey/slack-file-upload-action@master
        with:
          token: ${{ secrets.SLACK_TOKEN }}
          path: build/app/outputs/flutter-apk/app-release.apk
          channel: apkchannel
</code>```

Body:
I want to upload my Flutter APK to a slack channel, Solutions I got were pretty outdated,

    name: CI

on:
  push:
    branches: [develop]
  pull_request:
    branches: [develop]

  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    defaults:
      run:
        shell: bash

    steps:
      - uses: actions/checkout@v2

      - uses: actions/setup-java@v1
        with:
          java-version: "12.x"
      - uses: subosito/flutter-action@v1
        with:
          flutter-version: "2.8.1"
      - run: flutter pub get
      - run: flutter pub run flutter_native_splash:create
      - run: flutter pub run flutter_launcher_icons:main
      - run: flutter build apk
      - run: flutter build appbundle
      - uses: actions/upload-artifact@v1
        with:
          name: release-apk
          path: build/app/outputs/flutter-apk/app-release.apk

This is the current workflow that I have, It builds and adds it to Artefacts on Actions.

Body:
Easiest solution is to use one of Actions available in Marketplace:

jobs:
  upload:
    runs-on: ubuntu-latest
    name: Upload APK
    steps:
      - name: Upload to slack step
        uses: adrey/slack-file-upload-action@master
        with:
          token: ${{ secrets.SLACK_TOKEN }}
          path: build/app/outputs/flutter-apk/app-release.apk
          channel: apkchannel


问:
How do I know a `LazyColumn` can be navigated?
How do I know a LazyColumn can be navigated?

For example, a list contains 100 elements, then it is a lazy column that can be scroll and we show a fab button to scroll up, but when this list contains 5 elements, the lazy column is not scrollable and the FabButton is no longer needed.

答:
The lazy list layout information can be obtained from state, which is passed to LazyColumn.

In my example, I use derivedStateOf to prevent redundant recompositions - this will cause a recomposition only when the value actually changes. Reading LazyColumn state information without derivedStateOf or side effect function can cause significant performance problems.

The most basic logic in such cases is to check if the first element has been scrolled:

val canScrollToTop by remember {
    derivedStateOf {
        state.layoutInfo.visibleItemsInfo.run {
            isNotEmpty() && (first().index > 0 || first().offset < 0)
        }
    }
}
LazyColumn(state = state) {
   // ...
}
if (canScrollToTop) {
    // your button
}
```


问:
TestData doesn't work when try to filtering? React
I trying to filter all users. First check my code:

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

I got errro message ->

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

What's going on here?

i don't use the filteredUsers variable anywhere in the code

答:
You are not returning anything from the selector, since you've wrapped the filter with curly brackets, and no return statement. Remove the curlies.

In addition, the selector is creating a new array, and not an object with the property filteredUsers. Remove the destructuring assignment.

```<code>const filteredUsers = useSelector(({ organisationUsers }) =>
  organisationUsers.users.filter(user => selectedUsers?.includes(user.uuid))
);
</code>```

Body:
I trying to filter all users. First check my code:

  const

I got errro message ->

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

What's going on here?

i don't use the filteredUsers variable anywhere in the code

Body:
You are not returning anything from the selector, since you've wrapped the filter with curly brackets, and no return statement. Remove the curlies.

In addition, the selector is creating a new array, and not an object with the property filteredUsers. Remove the destructuring assignment.

const filteredUsers = useSelector(({ organisationUsers }) =>
  organisationUsers.users.filter(user => selectedUsers?.includes(user.uuid))
);


问:
Override functions in Solidity
I try to make a smart contract with a child contract and override another function that derived from another interface.

This is an example code:

```<code>// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

interface Base1 {
    function h() external public {}
}

interface Base2 {
    function f() external public {}
}

contract Inherited is Base1 {
    function h() external override {}
    function f() external override {}
}
</code>```

And I got this error: "TypeError: Function has override specified but does not override anything." in function f().

I know that could be solved by adding Base2 to the contract (contract Inherited is Base1, Base2) and specifying the interface in each function. But, is there another way to override function f() without adding Base2?

答:
is there another way to override function f() without adding Base2?

You cannot override something that does not exist.

In this context (Inherited is Base1), the only definition of function f() is the one in the Inherited contract.

An quick solution is to remove the override modifier, because the function in fact does not override anything.

Title: Override functions in Solidity

Body:
I try to make a smart contract with a child contract and override another function that derived from another interface.

This is an example code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

interface Base1 {
    function h() external public {}
}

interface Base2 {
    function f() external public {}
}

contract Inherited is Base1 {
    function h() external override {}
    function f() external override {}
}

And I got this error: "TypeError: Function has override specified but does not override anything." in function f().

I know that could be solved by adding Base2 to the contract (contract Inherited is Base1, Base2) and specifying the interface in each function. But, is there another way to override function f() without adding Base2?


问:
Azure Data Residency and Azure storage queues options & GDPR
All our current Azure workloads and SQL databases are located in the West-Europe region
We want to create new databases in US East, US West regions and want to use existing Azure workloads. Just checking if this violates the GDPR compliance?

Can we store also East-US data in West-Europe based Azure storage queues for processing? will the azure storage queue be considered as persistent storage? if yes, can we switch to Azure service bus queues instead?

答:
This is a question you should ask a lawyer, and not random people on the internet.

That said (and not a lawyer), GDPR is not location dependant, it depends on the security you can offer the data stored. So if Azure in West-Europe is good enough for your workloads, East-US should be fine as well.


问:
How do I implement a drag after a long press using React Native Gesture Handler v2?
The docs say:

Simply set manualActivation to true on a PanGesture and use StateManager to fail the gesture if the user attempts to drag the component sooner than the duration of the long press.

However, I can't figure out how to measure timing in the callbacks of the PanGesture, because the app crashes if I try to use setTimeout, and even if I were able to use setTimeout, I can't get a reference to the GestureStateManager except in the touch callbacks, so I'm not sure how to move the gesture into the START state.

Is there a tool besides setTimeout that I can use to implement a timer in what seems to be an RN Reanimated worklet? For example, can I use performance.now()?

Here's what I have so far:

```<code>
  const isPressed = useSharedValue(false);
  const isDragging = useSharedValue(false);

  const start = useSharedValue({
    x: 0,
    y: 0,
  });

  const offset = useSharedValue({
    x: 0,
    y: 0,
  });

const gesture =
  Gesture.Pan()
    .manualActivation(true)
    .onBegin((evt) => {
      console.log('pan begin');
    })
    .onStart(() => {
      console.log('pan start');
      isPressed.value = true;
      offset.value = {
        x: 0,
        y: 0,
      };
    })
    .onTouchesDown((evt, state) => {
      if (evt.numberOfTouches !== 1) {
        state.fail();
      }

      isPressed.value = true;
      start.value = {
        x: evt.allTouches[0].x,
        y: evt.allTouches[0].y,
      };

      // using setTimeout here causes a crash, and using runOnJS doesn't fix it

      // runOnJS(setTimeout)(() => {
      //   isDragging.value = true;
      //   state.activate();
      // }, 500);
    })
    .onTouchesMove((evt, state) => {
      isPressed.value = true;

      const offsetX = start.value.x - evt.allTouches[0].x;
      const offsetY = start.value.y - evt.allTouches[0].y;

      const dist = Math.sqrt(offsetX * offsetX + offsetY * offsetY);

      if (dist > 10) {
        state.fail();
      }
    })
    .onUpdate((evt) => {
      offset.value = {
        x: evt.translationX,
        y: evt.translationY,
      };
    })
    .onFinalize(() => {
      offset.value = {
        x: 0,
        y: 0,
      };
      isPressed.value = false;
      isDragging.value = false;

      console.log('pan finalize');
    });
</code>```

答:
I could achieve the result by using the Composed Gestures concept and by using a boolean SharedValue. I composed the LongPress gesture and PanGesture so I could detect when the LongPress begins and set the SharedValue boolean to true. So basically it would become true after a duration has passed after pressing the button. Then I use the SharedValue in the onTouchesMove function to enable the Pan Gesture</p>
```<code>const MyComponent = () => {

  const isLongPressed = useSharedValue(false);

  const longPress = Gesture.LongPress()
    .minDuration(1000)
    .onStart(event => {
      isLongPressed.value = true;
    });

  const panGesture = Gesture.Pan()
    .manualActivation(true)
    .onTouchesMove((event, stateManager) => {
      if (isLongPressed.value) {
        stateManager.activate();
      } else {
        stateManager.fail();
      }
    })
    .onUpdate(event => {
      console.log(event.x);
    })
    .onTouchesUp(() => {
      isLongPressed.value = false;
    });

  const composed = Gesture.Simultaneous(longPress, panGesture);

  return (
    <GestureDetector gesture={composed}>
      <Animated.View style={styles.container}>
       .........
      </Animated.View>
    </GestureDetector>
  );
};
</code>```

Body:
The docs say:

Simply set manualActivation to true on a PanGesture and use StateManager to fail the gesture if the user attempts to drag the component sooner than the duration of the long press.

However, I can't figure out how to measure timing in the callbacks of the PanGesture, because the app crashes if I try to use setTimeout, and even if I were able to use setTimeout, I can't get a reference to the GestureStateManager except in the touch callbacks, so I'm not sure how to move the gesture into the START state.

Is there a tool besides setTimeout that I can use to implement a timer in what seems to be an RN Reanimated worklet? For example, can I use performance.now()?

Here's what I have so far:

  const isPressed = useSharedValue(false);
  const isDragging = useSharedValue(false);

  const start = useSharedValue({
    x: 0,
    y: 0,
  });

  const offset = useSharedValue({
    x: 0,
    y: 0,
  });

const gesture =
  Gesture.Pan()
    .manualActivation(true)
    .onBegin((evt) => {
      console.log('pan begin');
    })
    .onStart(() => {
      console.log('pan start');
      isPressed.value = true;
      offset.value = {
        x: 0,
        y: 0,
      };
    })
    .onTouchesDown((evt, state) => {
      if (evt.numberOfTouches !== 1) {
        state.fail();
      }

      isPressed.value = true;
      start.value = {
        x: evt.allTouches[0].x,
        y: evt.allTouches[0].y,
      };

      // using setTimeout here causes a crash, and using runOnJS doesn't fix it

      // runOnJS(setTimeout)(() => {
      //   isDragging.value = true;
      //   state.activate();
      // }, 500);
    })
    .onTouchesMove((evt, state) => {
      isPressed.value = true;

      const offsetX = start.value.x - evt.allTouches[0].x;
      const offsetY = start.value.y - evt.allTouches[0].y;

      const dist = Math.sqrt(offsetX * offsetX + offsetY * offsetY);

      if (dist > 10) {
        state.fail();
      }
    })
    .onUpdate((evt) => {
      offset.value = {
        x: evt.translationX,
        y: evt.translationY,
      };
    })
    .onFinalize(() => {
      offset.value = {
        x: 0,
        y: 0,
      };
      isPressed.value = false;
      isDragging.value = false;

      console.log('pan finalize');
    });

Body:
I could achieve the result by using the Composed Gestures concept and by using a boolean SharedValue. I composed the LongPress gesture and PanGesture so I could detect when the LongPress begins and set the SharedValue boolean to true. So basically it would become true after a duration has passed after pressing the button. Then I use the SharedValue in the onTouchesMove function to enable the Pan Gesture

const MyComponent = () => {

  const isLongPressed = useSharedValue(false);

  const longPress = Gesture.LongPress()
    .minDuration(1000)
    .onStart(event => {
      isLongPressed.value = true;
    });

  const panGesture = Gesture.Pan()
    .manualActivation(true)
    .onTouchesMove((event, stateManager) => {
      if (isLongPressed.value) {
        stateManager.activate();
      } else {
        stateManager.fail();
      }
    })
    .onUpdate(event => {
      console.log(event.x);
    })
    .onTouchesUp(() => {
      isLongPressed.value = false;
    });

  const composed = Gesture.Simultaneous(longPress, panGesture);

  return (
    <GestureDetector gesture={composed}>
      <Animated.View style={styles.container}>
       .........
      </Animated.View>
    </GestureDetector>
  );
};


问:
How to create an image file from Firebird blob data?
I have a Firebird DB table, which contains fields with image data (as blob sybtype -5). I need to get this data and convert it to an image file. Code example below creates a file (but size is very large, and while trying to open it - it is said, that file is not right BMP file). What am I missing here?

```<code>result[0].OBJ_IMAGE1((err, name, eventEmitter) => {
    if(err) throw err;

    let chunks = [];
    eventEmitter.on('data', chunk => {
        chunks.push(chunk);
    });
    eventEmitter.once('end', () => {
        let buffer = Buffer.concat(chunks);

        fs.writeFile('test.png',  buffer, err => {
            if(err) throw err;
            console.log('image file written');
        });
    });
});
</code>```

答:
I have tested your code, and it will correctly write out the blob to a file. Your problem is therefore - as also discussed in the comments - one of not knowing what the actual image file type is, so you're storing it with the wrong file extension. You need to know the file type (or encoding, or encryption) used by the application storing the image data to be able to select the right file extension, image viewer to display the data and/or additional transformations required to get a viewable file.

Looking at the example data and the File Signatures link Marcodor provided, it is possible that the stored data is type "Standard JPEG file with Exif metadata" (FF D8 FF E1 xx xx 45 78 69 66 00), but the file is prefixed with 5 bytes of application specific data (maybe some sort of type identifier, or a file length, or something like that). Based on that, try using SUBSTRING(OBJ_IMAGE1 FROM 6) and see if saving as jpg allows you to open the file (NOTE: This doesn't necessarily mean all files stored in these blobs are JPEGs!).

As an aside, it is more efficient to store the image using:

result[0].OBJ_IMAGE1((err, name, e) => {
    if (err) throw err;
    var imgStream = fs.createWriteStream('filename.ext')
    e.pipe(imgStream);
});
```

Using pipe will write the chunks directly to a file as they are received, instead of accumulating the entire file into memory before writing it out.

Body:
I have a Firebird DB table, which contains fields with image data (as blob sybtype -5). I need to get this data and convert it to an image file. Code example below creates a file (but size is very large, and while trying to open it - it is said, that file is not right BMP file). What am I missing here?

result[0].OBJ_IMAGE1((err, name, eventEmitter) => {
    if(err) throw err;

    let chunks = [];
    eventEmitter.on('data', chunk => {
        chunks.push(chunk);
    });
    eventEmitter.once('end', () => {
        let buffer = Buffer.concat(chunks);

        fs.writeFile('test.png',  buffer, err => {
            if(err) throw err;
            console.log('image file written');
        });
    });
});

Body:
I have tested your code, and it will correctly write out the blob to a file. Your problem is therefore - as also discussed in the comments - one of not knowing what the actual image file type is, so you're storing it with the wrong file extension. You need to know the file type (or encoding, or encryption) used by the application storing the image data to be able to select the right file extension, image viewer to display the data and/or additional transformations required to get a viewable file.

Looking at the example data and the File Signatures link Marcodor provided, it is possible that the stored data is type "Standard JPEG file with Exif metadata" (FF D8 FF E1 xx xx 45 78 69 66 00), but the file is prefixed with 5 bytes of application specific data (maybe some sort of type identifier, or a file length, or something like that). Based on that, try using SUBSTRING(OBJ_IMAGE1 FROM 6) and see if saving as jpg allows you to open the file (NOTE: This doesn't necessarily mean all files stored in these blobs are JPEGs!).

As an aside, it is more efficient to store the image using:

result[0].OBJ_IMAGE1((err, name, e) => {
    if (err) throw err;
    var imgStream = fs.createWriteStream('filename.ext')
    e.pipe(imgStream);
});

Using pipe will write the chunks directly to a file as they are received, instead of accumulating the entire file into memory before writing it out.


问:
How do I make ScrollView auto scroll to the bottom?
How can i make it once the ScrollView is out of the screen it will auto scroll to the bottom?

答:
```<code>scrollView.post(new Runnable() {
               @Override
               public void run() {
                 scrollView.fullScroll(View.FOCUS_DOWN);
               }
});
</code>```

This worked for me

Body:
scrollView.post(new Runnable() {
               @Override
               public void run() {
                 scrollView.fullScroll(View.FOCUS_DOWN);
               }
});

This worked for me


问:
How to set different images alternately in listView's row?
I have a listview, in which I am fetching data from Twitter, I also show it in listView,
but I want to show different images in different rows of listView.

I used convert-view.setBackGroundResource(R.drawable.strip1);, it repeats this image in all rows, but I want to set it alternatively. How is it possible?

答:
Use an adapter like this, replace List with what you need.</p>

```<code>/**
 * Handles the listView.
 */
private class ListAdapter extends ArrayAdapter<Call> {

    private ArrayList<List> items;

    public ListAdapter(Context context, int textViewResourceId,
            ArrayList<List> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    /**
     * Returns the View populated with data.
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        List l = items.get(position);
        if (l != null) {
            ImageView ci = (ImageView) v.findViewById(R.id.iv_listIcon);
        }
        return v;
    }
}
</code>```

Body:
Use an adapter like this, replace List with what you need.

/**
 * Handles the listView.
 */
private class ListAdapter extends ArrayAdapter<Call> {

    private ArrayList<List> items;

    public ListAdapter(Context context, int textViewResourceId,
            ArrayList<List> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    /**
     * Returns the View populated with data.
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        List l = items.get(position);
        if (l != null) {
            ImageView ci = (ImageView) v.findViewById(R.id.iv_listIcon);
        }
        return v;
    }
}


问:
Negative exponent in division in Sympy
I make a division

```<code>fn=n/3**(n+1)
</code>```

But the view has

```<code>fn=3**(-n-1)*n
</code>```

Please tell me how to force as fn=n/3**(n+1)

答: Other than modifying the printer, I can only think of symbol-trickery: make the denominator a Symbol:  n/Symbol('3^{n+1}').

Title: Negative exponent in division in Sympy

Body:
I make a division

fn=n/3**(n+1)

But the view has

fn=3**(-n-1)*n

Please tell me how to force as fn=n/3**(n+1)


问:
How to set default CultureInfo for float.Parse?
My current CultureInfo setting is "CultureInfo("de-DE")" (by default settings), when I parse a String, it would be non-english result.

Can I set InvariantCulture default globally(init)?

```<code>        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // not work
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; // not work
        // new CultureInfo("de-DE")
        Debug.Log(float.Parse("0.11")); // 11
</code>```

答:
The parser must know which decimal separator should be used. Normally the CultureInfo.InvariantCulture should use a . but..

You could pass an English culture as argument:

```<code>Debug.Log(float.Parse("0.11", new CultureInfo("en-US")); // 0.11
</code>```

This won't affect the rest of the program.

Body:
My current CultureInfo setting is "CultureInfo("de-DE")" (by default settings), when I parse a String, it would be non-english result.

Can I set InvariantCulture default globally(init)?

        System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // not work
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; // not work
        // new CultureInfo("de-DE")
        Debug.Log(float.Parse("0.11")); // 11

Body:
The parser must know which decimal separator should be used. Normally the CultureInfo.InvariantCulture should use a . but..

You could pass an English culture as argument:

Debug.Log(float.Parse("0.11", new CultureInfo("en-US")); // 0.11

This won't affect the rest of the program.


问:
Hive - flutter: are boxes deleted when app is closed?
I need a way to store simple data in my Flutter project, and I'm considering using Hive flutter.

What I don't quite understand, is if the data stored in the boxes is cleared (as in, deleted from the disk) when the user closes the app/website.

The official documentation says:

Before your application exits, you should call Hive.close() to close all open boxes. Don't worry if the app is killed before you close Hive, it doesn't matter.

which is somewhat ambiguous.

So: Is data stored in boxes cleared upon closing the app/website; and if not, how can I manually clear it?

答:
When you close a box, hive saves the data in the box to a local storage file ("long term memory") and frees the cache ("short term memory") to be used for other stuff. You will not lose your app data. Closing the box is also not strictly necessary, Hive will close the boxes itself on exit.
Hive's FAQ has more details: https://docs.hivedb.dev/#/more/faq

If you want to clear data from a given Box box = Hive.box("box_name"), you can:

Delete a single entry: box.delete("entry_key")

Delete all entries: box.deleteAll(box.keys)

Delete the whole box: box.deleteFromDisk() or Hive.deleteBoxFromDisk("box_name")

Delete all (open) boxes: Hive.deleteFromDisk()

Note that while the behavior is the same for browsers and apps, the way this is implemented is different: https://docs.hivedb.dev/#/more/browser


问:
shopify custom liquid section show blank when added via theme editor into an existing page
I created a "custom liquid" section with following code

```<code><ul>
{% for product_type in collection.all_types %}
<li class="{{ product_type | handleize }}">
{{ product_type | link_to_type }}
</li>
{% endfor %}
</ul>
</code>```

It suppose to show a list of product type name as link. But I see nothing. However, when I simply add text into the "Custom Liquid" section, I see it in the page when I add the liquid custom section in the theme's visual editor.

I am using the Free OS2.0 theme
Any idea why?

答:
The above code will only work on Collection page as it is based on collection object. Homepage and other product pages does not have access to collection object directly. However, you can use collections object to get a specific collection.

Show Type on Collection Page

```<code>{% for product_type in collection.all_types %}
  {{ product_type | link_to_type }}
{% endfor %}
</code>```

Show Type for all collections on any page

```<code>{% for collection in collections %}
    {% for product_type in collection.all_types %}
        {{ product_type | link_to_type }}
    {% endfor %}
{% endfor %}
</code>```

Show Type for specific collection on any page

```<code>{% for product_type in collections['collection-handle'].all_types %}
  {{ product_type | link_to_type }}
{% endfor %}
</code>```

Collection Object

Collections Object

Body:
I created a "custom liquid" section with following code

{% for product_type in collection.all_types %}

{{ product_type | link_to_type }}

{% endfor %}

It suppose to show a list of product type name as link. But I see nothing. However, when I simply add text into the "Custom Liquid" section, I see it in the page when I add the liquid custom section in the theme's visual editor.

I am using the Free OS2.0 theme
Any idea why?

Body:
The above code will only work on Collection page as it is based on collection object. Homepage and other product pages does not have access to collection object directly. However, you can use collections object to get a specific collection.

Show Type on Collection Page

{% for product_type in collection.all_types %}
  {{ product_type | link_to_type }}
{% endfor %}

Show Type for all collections on any page

{% for collection in collections %}
    {% for product_type in collection.all_types %}
        {{ product_type | link_to_type }}
    {% endfor %}
{% endfor %}

Show Type for specific collection on any page

{% for product_type in collections['collection-handle'].all_types %}
  {{ product_type | link_to_type }}
{% endfor %}

Collection Object

Collections Object


问:
CompileSDKtarget 30 taking the screenshot is not working
```<code>compileSdkVersion = 30
minSdkVersion = 24
targetSdkVersion = 30
</code>```

till 29 it was working but from 30 my code stop working for taking screenshot

```<code>public static Bitmap getScreenShot(LinearLayout view) {
    Bitmap bm = Bitmap.createBitmap(view.getChildAt(0).getWidth(),
            view.getChildAt(0).getHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return bm;
}
</code>```

in return I m getting null value

答:
try this..</p>
```<code>public static Bitmap takescreenshot(View v) {
    v.setDrawingCacheEnabled(true);
    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    return b;
}
</code>```

Body:
compileSdkVersion = 30
minSdkVersion = 24
targetSdkVersion = 30

till 29 it was working but from 30 my code stop working for taking screenshot

public static Bitmap getScreenShot(LinearLayout view) {
    Bitmap bm = Bitmap.createBitmap(view.getChildAt(0).getWidth(),
            view.getChildAt(0).getHeight(),
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bm);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return bm;
}

in return I m getting null value

Body:
try this..

public static Bitmap takescreenshot(View v) {
    v.setDrawingCacheEnabled(true);
    v.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);
    return b;
}


答:
Yes, you can do that, but I would not recommend it. It will confuse users, when they expect to enter numbers in their native format (using a "," as decimal separator for the german culture).

Instead of globally setting the culture to invariant, you should always use the overloads to Parse that take a culture as argument, explicitly specifying whether at this particular location you expect local input (the data typically comes from the UI) or invariant input (the data comes from a file or database). If you get used to this, you'll avoid a lot of culture-dependent errors.

The same applies for the related methods ToString() and TryParse().

So, for data coming from a file use:

```<code>float value = float.Parse("0.11", CultureInfo.InvariantCulture);
</code>```

or better still:

```<code>float value = 0;
if (!float.TryParse("0.11", CultureInfo.InvariantCulture))
{
    // use default value, or throw exception
}
</code>```

If you really want to set it globally, your code appears to be correct. It works for me. To be sure, you could try:

```<code>var culture = new CultureInfo(...);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
</code>```

Title: How to set default CultureInfo for float.Parse?

Body:
Yes, you can do that, but I would not recommend it. It will confuse users, when they expect to enter numbers in their native format (using a "," as decimal separator for the german culture).

Instead of globally setting the culture to invariant, you should always use the overloads to Parse that take a culture as argument, explicitly specifying whether at this particular location you expect local input (the data typically comes from the UI) or invariant input (the data comes from a file or database). If you get used to this, you'll avoid a lot of culture-dependent errors.

The same applies for the related methods ToString() and TryParse().

So, for data coming from a file use:

float value = float.Parse("0.11", CultureInfo.InvariantCulture);

or better still:

float value = 0;
if (!float.TryParse("0.11", CultureInfo.InvariantCulture))
{
    // use default value, or throw exception
}

If you really want to set it globally, your code appears to be correct. It works for me. To be sure, you could try:

var culture = new CultureInfo(...);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;


问:
Extract URL from below code with beautifulsoup

```

I wanted to extract the data-purl link. How can i do that with beautiful soup

答:
To access the attribute of a tag simply call get('attribute') or treat it like a dict ['attribute']:

```<code>soup.find('li').get('data-purl')
</code>```

or

```<code>soup.find('li')['data-purl']
</code>```

Example

from bs4 import BeautifulSoup

```<code>html='''
<li class="option image" data-originalv="https://yellow_28_38_0_z_2.jpg" data-id="16693" data-pname="Yellow Classic Fit Casual Shirt"
data-purl="https://www.my-required-link-classic-fit-yellow-shirt.html">
<img loading="lazy" src="https://www.myimage-yellow_28_38_0_z_2.jpg" alt="" title="" width="40" height="40"></li>
'''

soup = BeautifulSoup(html)

soup.find('li').get('data-purl')
</code>```

Output

```<code>https://www.my-required-link-classic-fit-yellow-shirt.html
</code>```

Body:
To access the attribute of a tag simply call get('attribute') or treat it like a dict ['attribute']:

soup.find('li').get('data-purl')

or

soup.find('li')['data-purl']

Example

from bs4 import BeautifulSoup

html='''
<li class="option image" data-originalv="https://yellow_28_38_0_z_2.jpg" data-id="16693" data-pname="Yellow Classic Fit Casual Shirt"
data-purl="https://www.my-required-link-classic-fit-yellow-shirt.html">
<img loading="lazy" src="https://www.myimage-yellow_28_38_0_z_2.jpg" alt="" title="" width="40" height="40"></li>
'''

soup = BeautifulSoup(html)

soup.find('li').get('data-purl')

Output

https://www.my-required-link-classic-fit-yellow-shirt.html


问:
How to create a fat JAR with Gradle Kotlin script?
As titled, I'd like to know how to modify the gradle.build.kts in order to have a task to create a unique jar with all the dependencies (kotlin lib included) inside.

I found this sample in Groovy:

```<code>//create a single Jar with all dependencies
task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',
            'Implementation-Version': version,
            'Main-Class': 'com.mkyong.DateUtils'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}
</code>```

But I have no idea how I could write that in kotlin, other than:

```<code>task("fatJar") {

}
</code>```

答:
Here are 4 ways to do this. Note that the first 3 methods modify the existing Jar task of Gradle.

Method 1: Placing library files beside the result JAR

This method does not need application or any other plugins.

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    manifest.attributes["Class-Path"] = configurations
        .runtimeClasspath
        .get()
        .joinToString(separator = " ") { file ->
            "libs/${file.name}"
        }
}
```
<p>Note that Java requires us to use relative URLs for the <code>Class-Path</code> attribute. So, we cannot use the absolute path of Gradle dependencies (which is also prone to being changed and not available on other systems). If you want to use absolute paths, maybe this workaround will work.</p>
<p>Create the JAR with the following command:</p>
<pre class="lang-bash prettyprint-override"><code>./gradlew jar
</code>```

The result JAR will be created in build/libs/ directory by default.

After creating your JAR, copy your library JARs in libs/ sub-directory of where you put your result JAR. Make sure your library JAR files do not contain space in their file name (their file name should match the one specified by ${file.name} variable above in the task).

Method 2: Embedding the libraries in the result JAR file (fat or uber JAR)

This method too does not need any Gradle plugin.

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree) // OR .map { zipTree(it) }
    from(dependencies)
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
```
<p>Creating the JAR is exactly the same as the previous method.</p>
<h3>Method 3: Using the Shadow plugin (to create a fat or uber JAR)</h3>
<pre class="lang-kotlin prettyprint-override"><code>plugins {
    id("com.github.johnrengelman.shadow") version "6.0.0"
}
// Shadow task depends on Jar task, so these configs are reflected for Shadow as well
tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
}
</code>```

Create the JAR with this command:

./gradlew shadowJar
```
<p>See Shadow documentations for more information about configuring the plugin.</p>
<h3>Method 4: Creating a new task (instead of modifying the <code>Jar</code> task)</h3>
<pre class="lang-kotlin prettyprint-override"><code>tasks.create("MyFatJar", Jar::class) {
    group = "my tasks" // OR, for example, "build"
    description = "Creates a self-contained fat JAR of the application that can be run."
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree)
    from(dependencies)
    with(tasks.jar.get())
}
</code>```

Running the created JAR

java -jar my-artifact.jar
```
<p>The above solutions were tested with:</p>
<ul>
<li>Java 17</li>
<li>Gradle 7.1 (which uses Kotlin 1.4.31 for <em>.kts</em> build scripts)</li>
</ul>
<p>See the official Gradle documentation for creating uber (fat) JARs.<br />
For more information about manifests, see Oracle Java Documentation: Working with Manifest files.<br />
For difference between <code>tasks.create()</code> and <code>tasks.register()</code> see this post.</p>
<p>Note that your resource files will be included in the JAR file automatically (assuming they were placed in <em>/src/main/resources/</em> directory or any custom directory set as resources root in the build file). To access a resource file in your application, use this code (note the <code>/</code> at the start of names):</p>
<ul>
<li>Kotlin
<pre class="lang-kotlin prettyprint-override"><code>val vegetables = MyClass::class.java.getResource("/vegetables.txt").readText()
// Alternative ways:
// val vegetables = object{}.javaClass.getResource("/vegetables.txt").readText()
// val vegetables = MyClass::class.java.getResourceAsStream("/vegetables.txt").reader().readText()
// val vegetables = object{}.javaClass.getResourceAsStream("/vegetables.txt").reader().readText()
</code>```

Java

var stream = MyClass.class.getResource("/vegetables.txt").openStream();
// OR var stream = MyClass.class.getResourceAsStream("/vegetables.txt");

var reader = new BufferedReader(new InputStreamReader(stream));
var vegetables = reader.lines().collect(Collectors.joining("\n"));
```

Body:
As titled, I'd like to know how to modify the gradle.build.kts in order to have a task to create a unique jar with all the dependencies (kotlin lib included) inside.

I found this sample in Groovy:

//create a single Jar with all dependencies
task fatJar(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'Gradle Jar File Example',
            'Implementation-Version': version,
            'Main-Class': 'com.mkyong.DateUtils'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

But I have no idea how I could write that in kotlin, other than:

task("fatJar") {

}

Body:
Here are 4 ways to do this. Note that the first 3 methods modify the existing Jar task of Gradle.

Method 1: Placing library files beside the result JAR

This method does not need application or any other plugins.

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    manifest.attributes["Class-Path"] = configurations
        .runtimeClasspath
        .get()
        .joinToString(separator = " ") { file ->
            "libs/${file.name}"
        }
}

Note that Java requires us to use relative URLs for the Class-Path attribute. So, we cannot use the absolute path of Gradle dependencies (which is also prone to being changed and not available on other systems). If you want to use absolute paths, maybe this workaround will work.

Create the JAR with the following command:

./gradlew jar

The result JAR will be created in build/libs/ directory by default.

After creating your JAR, copy your library JARs in libs/ sub-directory of where you put your result JAR. Make sure your library JAR files do not contain space in their file name (their file name should match the one specified by ${file.name} variable above in the task).

Method 2: Embedding the libraries in the result JAR file (fat or uber JAR)

This method too does not need any Gradle plugin.

tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree) // OR .map { zipTree(it) }
    from(dependencies)
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

Creating the JAR is exactly the same as the previous method.

Method 3: Using the Shadow plugin (to create a fat or uber JAR)

plugins {
    id("com.github.johnrengelman.shadow") version "6.0.0"
}
// Shadow task depends on Jar task, so these configs are reflected for Shadow as well
tasks.jar {
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
}

Create the JAR with this command:

./gradlew shadowJar

See Shadow documentations for more information about configuring the plugin.

Method 4: Creating a new task (instead of modifying the Jar task)

tasks.create("MyFatJar", Jar::class) {
    group = "my tasks" // OR, for example, "build"
    description = "Creates a self-contained fat JAR of the application that can be run."
    manifest.attributes["Main-Class"] = "com.example.MyMainClass"
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
    val dependencies = configurations
        .runtimeClasspath
        .get()
        .map(::zipTree)
    from(dependencies)
    with(tasks.jar.get())
}

Running the created JAR

java -jar my-artifact.jar

The above solutions were tested with:

Java 17

Gradle 7.1 (which uses Kotlin 1.4.31 for .kts build scripts)

See the official Gradle documentation for creating uber (fat) JARs.

For more information about manifests, see Oracle Java Documentation: Working with Manifest files.

For difference between tasks.create() and tasks.register() see this post.

Note that your resource files will be included in the JAR file automatically (assuming they were placed in /src/main/resources/ directory or any custom directory set as resources root in the build file). To access a resource file in your application, use this code (note the / at the start of names):

Kotlin

val vegetables = MyClass::class.java.getResource("/vegetables.txt").readText()
// Alternative ways:
// val vegetables = object{}.javaClass.getResource("/vegetables.txt").readText()
// val vegetables = MyClass::class.java.getResourceAsStream("/vegetables.txt").reader().readText()
// val vegetables = object{}.javaClass.getResourceAsStream("/vegetables.txt").reader().readText()

Java

var stream = MyClass.class.getResource("/vegetables.txt").openStream();
// OR var stream = MyClass.class.getResourceAsStream("/vegetables.txt");

var reader = new BufferedReader(new InputStreamReader(stream));
var vegetables = reader.lines().collect(Collectors.joining("\n"));


问:
Django, Html: How i can display the (number of page / total pages exist) on a pdf printout rendered
I have to render an HTML template to pdf as a response working with the framework Django and I want to add a footer containing the number of pages in the pdf-printout / total number of pages for example, if I have 2 pages in total, the first page should display to me 1/2, How I can do that please using HTML!

I have tried with this code :

```<code>      <footer>
        {%block page_foot%}
        <div style="display: block;margin: 0 auto;text-align: center;">
          page: <pdf:pagenumber />
        </div>
      {%endblock%}
      </footer>
</code>```

But it displays 0 on the first page.

Thanks in advance

答: I recommend wkhtml2pdf which allows converting html to PDF and it has such features as having TOC and page numbering.</p>

Body:
I have to render an HTML template to pdf as a response working with the framework Django and I want to add a footer containing the number of pages in the pdf-printout / total number of pages for example, if I have 2 pages in total, the first page should display to me 1/2, How I can do that please using HTML!

I have tried with this code :

        {%block page_foot%}

          page: <pdf:pagenumber />

      {%endblock%}

But it displays 0 on the first page.

Thanks in advance


问:
How can I solve this problem - Instance of 'CategoryModel'? Flutter
I am trying to fetch data from api with Dio , But I found an error in my debug console - Instance of 'CategoryModel' . I don't know why I face this error.

My Problem Issue ScreenShot

The Json File

{
    "categories": [{
        "id": 1,
        "name": "Fruits & Vegetables",
        "slug": "fruits--vegetables",
        "image": "public\/uploads\/category\/1642326298-fruits-and-vegetables.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:15:36.000000Z",
        "updated_at": "2022-01-15T22:44:58.000000Z",
        "subcategories": [{
            "id": 1,
            "subcategoryName": "Formula and Energy Boosters",
            "slug": "formula-and-energy-boosters",
            "image": "public\/uploads\/subcategory\/1642051209-formula-n-energy-boosters.jpg",
            "banner": "public\/uploads\/subcategory\/1642060781-banner.jpg",
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:00:19.000000Z",
            "updated_at": "2022-01-12T20:59:41.000000Z",
            "childcategories": [{
                "id": 1,
                "childcategoryName": "Stylish T-shirts",
                "slug": "stylish-t-shirts",
                "image": null,
                "banner": null,
                "subcategory_id": "1",
                "status": "1",
                "created_at": "2022-01-01T19:02:45.000000Z",
                "updated_at": "2022-01-01T19:02:45.000000Z"
            }]
        }, {
            "id": 2,
            "subcategoryName": "Baby Milk and Foods",
            "slug": "baby-milk-and-foods",
            "image": "public\/uploads\/subcategory\/1642053444-baby-milk-and-food.jpg",
            "banner": null,
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:07:13.000000Z",
            "updated_at": "2022-01-12T18:57:24.000000Z",
            "childcategories": [{
                "id": 2,
                "childcategoryName": "Shirt Collection",
                "slug": "shirt-collection",
                "image": null,
                "banner": null,
                "subcategory_id": "2",
                "status": "1",
                "created_at": "2022-01-01T19:08:35.000000Z",
                "updated_at": "2022-01-01T19:08:35.000000Z"
            }]
        }, {
            "id": 3,
            "subcategoryName": "Diapers",
            "slug": "diapers",
            "image": "public\/uploads\/subcategory\/1642053483-diaper.jpg",
            "banner": null,
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:25:37.000000Z",
            "updated_at": "2022-01-12T18:58:03.000000Z",
            "childcategories": [{
                "id": 5,
                "childcategoryName": "Jeans Pant",
                "slug": "jeans-pant",
                "image": null,
                "banner": null,
                "subcategory_id": "3",
                "status": "1",
                "created_at": "2022-01-01T19:39:23.000000Z",
                "updated_at": "2022-01-01T19:39:23.000000Z"
            }]
        }]
    }, {
        "id": 2,
        "name": "Meat & Fish",
        "slug": "meat--fish",
        "image": "public\/uploads\/category\/1642326372-meat-and-fish.webp",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:17:51.000000Z",
        "updated_at": "2022-01-15T22:46:12.000000Z",
        "subcategories": [{
            "id": 4,
            "subcategoryName": "Saree",
            "slug": "saree",
            "image": "public\/uploads\/subcategory\/1641816956-subcategory-6.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:27:23.000000Z",
            "updated_at": "2022-01-10T01:15:56.000000Z",
            "childcategories": [{
                "id": 6,
                "childcategoryName": "Cotton Saree",
                "slug": "cotton-saree",
                "image": null,
                "banner": null,
                "subcategory_id": "4",
                "status": "1",
                "created_at": "2022-01-01T19:40:00.000000Z",
                "updated_at": "2022-01-01T19:40:00.000000Z"
            }]
        }, {
            "id": 5,
            "subcategoryName": "Salwar Kamiz",
            "slug": "salwar-kamiz",
            "image": "public\/uploads\/subcategory\/1641816945-subcategory-7.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:28:02.000000Z",
            "updated_at": "2022-01-10T01:15:45.000000Z",
            "childcategories": [{
                "id": 3,
                "childcategoryName": "Original Indian Dress",
                "slug": "original-indian-dress",
                "image": null,
                "banner": null,
                "subcategory_id": "5",
                "status": "1",
                "created_at": "2022-01-01T19:29:25.000000Z",
                "updated_at": "2022-01-01T19:29:25.000000Z"
            }, {
                "id": 4,
                "childcategoryName": "Block Batik Dress",
                "slug": "block-batik-dress",
                "image": null,
                "banner": null,
                "subcategory_id": "5",
                "status": "1",
                "created_at": "2022-01-01T19:30:12.000000Z",
                "updated_at": "2022-01-01T19:30:12.000000Z"
            }]
        }, {
            "id": 6,
            "subcategoryName": "Western",
            "slug": "western",
            "image": "public\/uploads\/subcategory\/1641816838-subcategory-3.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:28:31.000000Z",
            "updated_at": "2022-01-10T01:13:58.000000Z",
            "childcategories": [{
                "id": 7,
                "childcategoryName": "Tops",
                "slug": "tops",
                "image": null,
                "banner": null,
                "subcategory_id": "6",
                "status": "1",
                "created_at": "2022-01-01T19:40:30.000000Z",
                "updated_at": "2022-01-01T19:40:30.000000Z"
            }, {
                "id": 8,
                "childcategoryName": "Leggings",
                "slug": "leggings",
                "image": null,
                "banner": null,
                "subcategory_id": "6",
                "status": "1",
                "created_at": "2022-01-01T19:40:46.000000Z",
                "updated_at": "2022-01-01T19:40:46.000000Z"
            }]
        }]
    }, {
        "id": 3,
        "name": "Milk & Dairy",
        "slug": "milk--dairy",
        "image": "public\/uploads\/category\/1642326427-milk-and-dairy.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:47:07.000000Z",
        "updated_at": "2022-01-15T22:47:07.000000Z",
        "subcategories": [{
            "id": 7,
            "subcategoryName": "Dress",
            "slug": "dress",
            "image": "public\/uploads\/subcategory\/1641816822-subcategory-2.jpg",
            "banner": null,
            "category_id": "3",
            "status": "1",
            "created_at": "2022-01-01T19:55:10.000000Z",
            "updated_at": "2022-01-10T01:13:42.000000Z",
            "childcategories": [{
                "id": 11,
                "childcategoryName": "Shirt",
                "slug": "shirt",
                "image": null,
                "banner": null,
                "subcategory_id": "7",
                "status": "1",
                "created_at": "2022-01-01T19:58:39.000000Z",
                "updated_at": "2022-01-01T19:58:39.000000Z"
            }, {
                "id": 12,
                "childcategoryName": "Pant",
                "slug": "pant",
                "image": "public\/uploads\/childcategory\/1642335874-pant-logo.jpg",
                "banner": "public\/uploads\/childcategory\/1642335874-pants-banner.png",
                "subcategory_id": "7",
                "status": "1",
                "created_at": "2022-01-01T19:59:05.000000Z",
                "updated_at": "2022-01-16T01:24:34.000000Z"
            }]
        }, {
            "id": 8,
            "subcategoryName": "Footwear",
            "slug": "footwear",
            "image": "public\/uploads\/subcategory\/1641816595-subcategory.jpg",
            "banner": "public\/uploads\/subcategory\/1641821574-kids-banner.png",
            "category_id": "3",
            "status": "1",
            "created_at": "2022-01-01T19:55:36.000000Z",
            "updated_at": "2022-01-10T02:32:54.000000Z",
            "childcategories": [{
                "id": 9,
                "childcategoryName": "Shoe",
                "slug": "shoe",
                "image": null,
                "banner": null,
                "subcategory_id": "8",
                "status": "1",
                "created_at": "2022-01-01T19:57:23.000000Z",
                "updated_at": "2022-01-01T19:57:23.000000Z"
            }, {
                "id": 10,
                "childcategoryName": "Leather Sandal",
                "slug": "leather-sandal",
                "image": null,
                "banner": null,
                "subcategory_id": "8",
                "status": "1",
                "created_at": "2022-01-01T19:58:02.000000Z",
                "updated_at": "2022-01-01T19:58:02.000000Z"
            }]
        }]
    }, {
        "id": 4,
        "name": "Food",
        "slug": "food",
        "image": "public\/uploads\/category\/1642326638-food.jpg",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:24:59.000000Z",
        "updated_at": "2022-01-15T22:50:38.000000Z",
        "subcategories": []
    }, {
        "id": 5,
        "name": "Baby Care",
        "slug": "baby-care",
        "image": "public\/uploads\/category\/1642326689-baby-care.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:27:28.000000Z",
        "updated_at": "2022-01-15T22:51:29.000000Z",
        "subcategories": []
    }, {
        "id": 6,
        "name": "Health & Beauty",
        "slug": "health--beauty",
        "image": "public\/uploads\/category\/1642326774-health-and-beauty.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:43:51.000000Z",
        "updated_at": "2022-01-15T22:52:54.000000Z",
        "subcategories": []
    }, {
        "id": 7,
        "name": "Office & Stationery",
        "slug": "office--stationery",
        "image": "public\/uploads\/category\/1642326827-office-stationary.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:53:47.000000Z",
        "updated_at": "2022-01-15T22:53:47.000000Z",
        "subcategories": []
    }, {
        "id": 8,
        "name": "Pet Care",
        "slug": "pet-care",
        "image": "public\/uploads\/category\/1642326888-pet-care.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:54:48.000000Z",
        "updated_at": "2022-01-15T22:54:48.000000Z",
        "subcategories": [{
            "id": 9,
            "subcategoryName": "Kitten Food",
            "slug": "kitten-food",
            "image": "public\/uploads\/subcategory\/1642334752-kitten-food.jpg",
            "banner": "public\/uploads\/subcategory\/1642334752-kitten-food-banner.jpg",
            "category_id": "8",
            "status": "1",
            "created_at": "2022-01-16T01:05:52.000000Z",
            "updated_at": "2022-01-16T01:05:52.000000Z",
            "childcategories": []
        }]
    }, {
        "id": 9,
        "name": "Toys & Games",
        "slug": "toys--games",
        "image": "public\/uploads\/category\/1642327094-toy-and-games.jpg",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:58:14.000000Z",
        "updated_at": "2022-01-15T22:58:14.000000Z",
        "subcategories": []
    }, {
        "id": 10,
        "name": "Home & Cleaning",
        "slug": "home--cleaning",
        "image": "public\/uploads\/category\/1642327182-house-cleaning.jpg",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:59:42.000000Z",
        "updated_at": "2022-01-15T22:59:42.000000Z",
        "subcategories": []
    }, {
        "id": 11,
        "name": "Sports & Fitness",
        "slug": "sports--fitness",
        "image": "public\/uploads\/category\/1642327903-sports-and-fitness.jpg",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T23:11:43.000000Z",
        "updated_at": "2022-01-15T23:11:43.000000Z",
        "subcategories": []
    }, {
        "id": 12,
        "name": "Kitchen & Home Appliances",
        "slug": "kitchen--home-appliances",
        "image": "public\/uploads\/category\/1642327984-home-and-kitchen.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T23:13:04.000000Z",
        "updated_at": "2022-01-15T23:13:04.000000Z",
        "subcategories": []
    }]
}
```
<p><strong>Here Is My all Code -</strong></p>
<p><code>CategoryModel.dart</code> file</p>
```import 'package:Darucheeni/src/models/subCategoryModel.dart';
import 'package:json_annotation/json_annotation.dart';
part 'categoryModel.g.dart';

@JsonSerializable()
class CategoryModel {
  final int? id;
  final String? name;
  final String? slug;
  final String? image;
  final SubCategoryModel? subCategoryModel;

  CategoryModel({
    required this.id,
    required this.name,
    required this.slug,
    required this.image,
    required this.subCategoryModel,
  });

  factory CategoryModel.fromJson(Map<String, dynamic> json) =>
      _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);
}
```
<p><strong>Here Is CategoryModel.g.dart</strong></p>
```// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'categoryModel.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

CategoryModel _$CategoryModelFromJson(Map<String, dynamic> json) =>
    CategoryModel(
      id: json['id'] as int?,
      name: json['name'] as String?,
      slug: json['slug'] as String?,
      image: json['image'] as String?,
      subCategoryModel: json['subCategoryModel'] == null
          ? null
          : SubCategoryModel.fromJson(
              json['subCategoryModel'] as Map<String, dynamic>),
    );

Map<String, dynamic> _$CategoryModelToJson(CategoryModel instance) =>
    <String, dynamic>{
      'id': instance.id,
      'name': instance.name,
      'slug': instance.slug,
      'image': instance.image,
      'subCategoryModel': instance.subCategoryModel,
    };
```
<p>Here Is my <code>categoryController.dart</code> file</p>
```import 'package:Darucheeni/src/configs/appConfigs.dart';
import 'package:Darucheeni/src/models/categoryModel.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';

class CategoryController extends GetxController {
  final dio = Dio();

  final allCategoryList = RxList<CategoryModel>();

  getAllCategory() async {
    try {
      final res = await dio.get(baseUrl + 'all-category');

      final List<CategoryModel> categoryData = res.data['categories']
          .map((json) => CategoryModel.fromJson(json))
          .toList()
          .cast<CategoryModel>();

      print('------------------------------>');
      print('Status Code : ${res.statusCode}');
      print('Headers : ${res.headers}');
      print('realUri : ${res.realUri}');
      print('statusMessage : ${res.statusMessage}');
      print(res.data);
      print('Category Data : $categoryData');
      print('requestOptions : ${res.requestOptions}');
      // print(res.body);
      // print(res.unauthorized);
      print('------------------------------>');

      if (res.data == 200) {
        allCategoryList.addAll(
            (res.data as List).map((e) => CategoryModel.fromJson(e)).toList());
      }
    } catch (e) {
      print(e);
    }
  }
}
```

答:
If you want to print a class, you should override 'toString' method. Console is don't know how to print classes

import 'package:Darucheeni/src/models/subCategoryModel.dart';
import 'package:json_annotation/json_annotation.dart';
part 'categoryModel.g.dart';

@JsonSerializable()
class CategoryModel {
  final int? id;
  final String? name;
  final String? slug;
  final String? image;
  final SubCategoryModel? subCategoryModel;

  CategoryModel({
    required this.id,
    required this.name,
    required this.slug,
    required this.image,
    required this.subCategoryModel,
  });

  factory CategoryModel.fromJson(Map<String, dynamic> json) =>
      _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);

  @override
  String toString() {
    return 'CategoryModel{ id: $id, name: $name, slug: $slug, image: $image, SubCategoryModel: $subCategoryModel}';
  }

}
```

Body:
I am trying to fetch data from api with Dio , But I found an error in my debug console - Instance of 'CategoryModel' . I don't know why I face this error.

My Problem Issue ScreenShot

The Json File

{
    "categories": [{
        "id": 1,
        "name": "Fruits & Vegetables",
        "slug": "fruits--vegetables",
        "image": "public\/uploads\/category\/1642326298-fruits-and-vegetables.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:15:36.000000Z",
        "updated_at": "2022-01-15T22:44:58.000000Z",
        "subcategories": [{
            "id": 1,
            "subcategoryName": "Formula and Energy Boosters",
            "slug": "formula-and-energy-boosters",
            "image": "public\/uploads\/subcategory\/1642051209-formula-n-energy-boosters.jpg",
            "banner": "public\/uploads\/subcategory\/1642060781-banner.jpg",
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:00:19.000000Z",
            "updated_at": "2022-01-12T20:59:41.000000Z",
            "childcategories": [{
                "id": 1,
                "childcategoryName": "Stylish T-shirts",
                "slug": "stylish-t-shirts",
                "image": null,
                "banner": null,
                "subcategory_id": "1",
                "status": "1",
                "created_at": "2022-01-01T19:02:45.000000Z",
                "updated_at": "2022-01-01T19:02:45.000000Z"
            }]
        }, {
            "id": 2,
            "subcategoryName": "Baby Milk and Foods",
            "slug": "baby-milk-and-foods",
            "image": "public\/uploads\/subcategory\/1642053444-baby-milk-and-food.jpg",
            "banner": null,
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:07:13.000000Z",
            "updated_at": "2022-01-12T18:57:24.000000Z",
            "childcategories": [{
                "id": 2,
                "childcategoryName": "Shirt Collection",
                "slug": "shirt-collection",
                "image": null,
                "banner": null,
                "subcategory_id": "2",
                "status": "1",
                "created_at": "2022-01-01T19:08:35.000000Z",
                "updated_at": "2022-01-01T19:08:35.000000Z"
            }]
        }, {
            "id": 3,
            "subcategoryName": "Diapers",
            "slug": "diapers",
            "image": "public\/uploads\/subcategory\/1642053483-diaper.jpg",
            "banner": null,
            "category_id": "1",
            "status": "1",
            "created_at": "2022-01-01T19:25:37.000000Z",
            "updated_at": "2022-01-12T18:58:03.000000Z",
            "childcategories": [{
                "id": 5,
                "childcategoryName": "Jeans Pant",
                "slug": "jeans-pant",
                "image": null,
                "banner": null,
                "subcategory_id": "3",
                "status": "1",
                "created_at": "2022-01-01T19:39:23.000000Z",
                "updated_at": "2022-01-01T19:39:23.000000Z"
            }]
        }]
    }, {
        "id": 2,
        "name": "Meat & Fish",
        "slug": "meat--fish",
        "image": "public\/uploads\/category\/1642326372-meat-and-fish.webp",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:17:51.000000Z",
        "updated_at": "2022-01-15T22:46:12.000000Z",
        "subcategories": [{
            "id": 4,
            "subcategoryName": "Saree",
            "slug": "saree",
            "image": "public\/uploads\/subcategory\/1641816956-subcategory-6.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:27:23.000000Z",
            "updated_at": "2022-01-10T01:15:56.000000Z",
            "childcategories": [{
                "id": 6,
                "childcategoryName": "Cotton Saree",
                "slug": "cotton-saree",
                "image": null,
                "banner": null,
                "subcategory_id": "4",
                "status": "1",
                "created_at": "2022-01-01T19:40:00.000000Z",
                "updated_at": "2022-01-01T19:40:00.000000Z"
            }]
        }, {
            "id": 5,
            "subcategoryName": "Salwar Kamiz",
            "slug": "salwar-kamiz",
            "image": "public\/uploads\/subcategory\/1641816945-subcategory-7.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:28:02.000000Z",
            "updated_at": "2022-01-10T01:15:45.000000Z",
            "childcategories": [{
                "id": 3,
                "childcategoryName": "Original Indian Dress",
                "slug": "original-indian-dress",
                "image": null,
                "banner": null,
                "subcategory_id": "5",
                "status": "1",
                "created_at": "2022-01-01T19:29:25.000000Z",
                "updated_at": "2022-01-01T19:29:25.000000Z"
            }, {
                "id": 4,
                "childcategoryName": "Block Batik Dress",
                "slug": "block-batik-dress",
                "image": null,
                "banner": null,
                "subcategory_id": "5",
                "status": "1",
                "created_at": "2022-01-01T19:30:12.000000Z",
                "updated_at": "2022-01-01T19:30:12.000000Z"
            }]
        }, {
            "id": 6,
            "subcategoryName": "Western",
            "slug": "western",
            "image": "public\/uploads\/subcategory\/1641816838-subcategory-3.jpg",
            "banner": null,
            "category_id": "2",
            "status": "1",
            "created_at": "2022-01-01T19:28:31.000000Z",
            "updated_at": "2022-01-10T01:13:58.000000Z",
            "childcategories": [{
                "id": 7,
                "childcategoryName": "Tops",
                "slug": "tops",
                "image": null,
                "banner": null,
                "subcategory_id": "6",
                "status": "1",
                "created_at": "2022-01-01T19:40:30.000000Z",
                "updated_at": "2022-01-01T19:40:30.000000Z"
            }, {
                "id": 8,
                "childcategoryName": "Leggings",
                "slug": "leggings",
                "image": null,
                "banner": null,
                "subcategory_id": "6",
                "status": "1",
                "created_at": "2022-01-01T19:40:46.000000Z",
                "updated_at": "2022-01-01T19:40:46.000000Z"
            }]
        }]
    }, {
        "id": 3,
        "name": "Milk & Dairy",
        "slug": "milk--dairy",
        "image": "public\/uploads\/category\/1642326427-milk-and-dairy.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:47:07.000000Z",
        "updated_at": "2022-01-15T22:47:07.000000Z",
        "subcategories": [{
            "id": 7,
            "subcategoryName": "Dress",
            "slug": "dress",
            "image": "public\/uploads\/subcategory\/1641816822-subcategory-2.jpg",
            "banner": null,
            "category_id": "3",
            "status": "1",
            "created_at": "2022-01-01T19:55:10.000000Z",
            "updated_at": "2022-01-10T01:13:42.000000Z",
            "childcategories": [{
                "id": 11,
                "childcategoryName": "Shirt",
                "slug": "shirt",
                "image": null,
                "banner": null,
                "subcategory_id": "7",
                "status": "1",
                "created_at": "2022-01-01T19:58:39.000000Z",
                "updated_at": "2022-01-01T19:58:39.000000Z"
            }, {
                "id": 12,
                "childcategoryName": "Pant",
                "slug": "pant",
                "image": "public\/uploads\/childcategory\/1642335874-pant-logo.jpg",
                "banner": "public\/uploads\/childcategory\/1642335874-pants-banner.png",
                "subcategory_id": "7",
                "status": "1",
                "created_at": "2022-01-01T19:59:05.000000Z",
                "updated_at": "2022-01-16T01:24:34.000000Z"
            }]
        }, {
            "id": 8,
            "subcategoryName": "Footwear",
            "slug": "footwear",
            "image": "public\/uploads\/subcategory\/1641816595-subcategory.jpg",
            "banner": "public\/uploads\/subcategory\/1641821574-kids-banner.png",
            "category_id": "3",
            "status": "1",
            "created_at": "2022-01-01T19:55:36.000000Z",
            "updated_at": "2022-01-10T02:32:54.000000Z",
            "childcategories": [{
                "id": 9,
                "childcategoryName": "Shoe",
                "slug": "shoe",
                "image": null,
                "banner": null,
                "subcategory_id": "8",
                "status": "1",
                "created_at": "2022-01-01T19:57:23.000000Z",
                "updated_at": "2022-01-01T19:57:23.000000Z"
            }, {
                "id": 10,
                "childcategoryName": "Leather Sandal",
                "slug": "leather-sandal",
                "image": null,
                "banner": null,
                "subcategory_id": "8",
                "status": "1",
                "created_at": "2022-01-01T19:58:02.000000Z",
                "updated_at": "2022-01-01T19:58:02.000000Z"
            }]
        }]
    }, {
        "id": 4,
        "name": "Food",
        "slug": "food",
        "image": "public\/uploads\/category\/1642326638-food.jpg",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:24:59.000000Z",
        "updated_at": "2022-01-15T22:50:38.000000Z",
        "subcategories": []
    }, {
        "id": 5,
        "name": "Baby Care",
        "slug": "baby-care",
        "image": "public\/uploads\/category\/1642326689-baby-care.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:27:28.000000Z",
        "updated_at": "2022-01-15T22:51:29.000000Z",
        "subcategories": []
    }, {
        "id": 6,
        "name": "Health & Beauty",
        "slug": "health--beauty",
        "image": "public\/uploads\/category\/1642326774-health-and-beauty.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-01T18:43:51.000000Z",
        "updated_at": "2022-01-15T22:52:54.000000Z",
        "subcategories": []
    }, {
        "id": 7,
        "name": "Office & Stationery",
        "slug": "office--stationery",
        "image": "public\/uploads\/category\/1642326827-office-stationary.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:53:47.000000Z",
        "updated_at": "2022-01-15T22:53:47.000000Z",
        "subcategories": []
    }, {
        "id": 8,
        "name": "Pet Care",
        "slug": "pet-care",
        "image": "public\/uploads\/category\/1642326888-pet-care.png",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:54:48.000000Z",
        "updated_at": "2022-01-15T22:54:48.000000Z",
        "subcategories": [{
            "id": 9,
            "subcategoryName": "Kitten Food",
            "slug": "kitten-food",
            "image": "public\/uploads\/subcategory\/1642334752-kitten-food.jpg",
            "banner": "public\/uploads\/subcategory\/1642334752-kitten-food-banner.jpg",
            "category_id": "8",
            "status": "1",
            "created_at": "2022-01-16T01:05:52.000000Z",
            "updated_at": "2022-01-16T01:05:52.000000Z",
            "childcategories": []
        }]
    }, {
        "id": 9,
        "name": "Toys & Games",
        "slug": "toys--games",
        "image": "public\/uploads\/category\/1642327094-toy-and-games.jpg",
        "frontProduct": "1",
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:58:14.000000Z",
        "updated_at": "2022-01-15T22:58:14.000000Z",
        "subcategories": []
    }, {
        "id": 10,
        "name": "Home & Cleaning",
        "slug": "home--cleaning",
        "image": "public\/uploads\/category\/1642327182-house-cleaning.jpg",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T22:59:42.000000Z",
        "updated_at": "2022-01-15T22:59:42.000000Z",
        "subcategories": []
    }, {
        "id": 11,
        "name": "Sports & Fitness",
        "slug": "sports--fitness",
        "image": "public\/uploads\/category\/1642327903-sports-and-fitness.jpg",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T23:11:43.000000Z",
        "updated_at": "2022-01-15T23:11:43.000000Z",
        "subcategories": []
    }, {
        "id": 12,
        "name": "Kitchen & Home Appliances",
        "slug": "kitchen--home-appliances",
        "image": "public\/uploads\/category\/1642327984-home-and-kitchen.png",
        "frontProduct": null,
        "level": null,
        "status": "1",
        "created_at": "2022-01-15T23:13:04.000000Z",
        "updated_at": "2022-01-15T23:13:04.000000Z",
        "subcategories": []
    }]
}

Here Is My all Code -

CategoryModel.dart file

import 'package:Darucheeni/src/models/subCategoryModel.dart';
import 'package:json_annotation/json_annotation.dart';
part 'categoryModel.g.dart';

@JsonSerializable()
class CategoryModel {
  final int? id;
  final String? name;
  final String? slug;
  final String? image;
  final SubCategoryModel? subCategoryModel;

  CategoryModel({
    required this.id,
    required this.name,
    required this.slug,
    required this.image,
    required this.subCategoryModel,
  });

  factory CategoryModel.fromJson(Map<String, dynamic> json) =>
      _$CategoryModelFromJson(json);
  Map<String, dynamic> toJson() => _$CategoryModelToJson(this);
}

Here Is CategoryModel.g.dart

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'categoryModel.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

CategoryModel _$CategoryModelFromJson(Map<String, dynamic> json) =>
    CategoryModel(
      id: json['id'] as int?,
      name: json['name'] as String?,
      slug: json['slug'] as String?,
      image: json['image'] as String?,
      subCategoryModel: json['subCategoryModel'] == null
          ? null
          : SubCategoryModel.fromJson(
              json['subCategoryModel'] as Map<String, dynamic>),
    );

Map<String, dynamic> _$CategoryModelToJson(CategoryModel instance) =>
    <String, dynamic>{
      'id': instance.id,
      'name': instance.name,
      'slug': instance.slug,
      'image': instance.image,
      'subCategoryModel': instance.subCategoryModel,
    };

Here Is my categoryController.dart file

import 'package:Darucheeni/src/configs/appConfigs.dart';
import 'package:Darucheeni/src/models/categoryModel.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';

class CategoryController extends GetxController {
  final dio = Dio();

  final allCategoryList = RxList<CategoryModel>();

  getAllCategory() async {
    try {
      final res = await dio.get(baseUrl + 'all-category');

      final List<CategoryModel> categoryData = res.data['categories']
          .map((json) => CategoryModel.fromJson(json))
          .toList()
          .cast<CategoryModel>();

      print('------------------------------>');
      print('Status Code : ${res.statusCode}');
      print('Headers : ${res.headers}');
      print('realUri : ${res.realUri}');
      print('statusMessage : ${res.statusMessage}');
      print(res.data);
      print('Category Data : $categoryData');
      print('requestOptions : ${res.requestOptions}');
      // print(res.body);
      // print(res.unauthorized);
      print('------------------------------>');

      if (res.data == 200) {
        allCategoryList.addAll(
            (res.data as List).map((e) => CategoryModel.fromJson(e)).toList());
      }
    } catch (e) {
      print(e);
    }
  }
}