问:
Android - Can't find all string resource localizations
I currently have 2 localizations, English and Spanish, for an app I'm building to create recipes. Part of the recipe creation process involves doing some text parsing on each step. I am attempting to build a MutableMap of each localization and all the strings from a string-array of common measurement units. Here is how I am attempting to do this:

```<code>                for (i in 0 until resources.configuration.locales.size()) {
                    val currentLocaleList = resources.configuration.locales
                    val currentLocale = currentLocaleList.get(i).toLanguageTag()
                    val configuration = Configuration()
                    configuration.setLocale(Locale.forLanguageTag(currentLocale))
                    val context = context?.createConfigurationContext(configuration)
                    val measurementsLocaleUnits = context?.resources?.getStringArray(
                        R.array.measurement_units) as Array<String>
                    measurementLocales[currentLocale] = measurementsLocaleUnits
                }
</code>```

When I test this on my Galaxy S21+ (Android 13), it works correctly. It finds the English and Spanish localizations of my string-array, measurement_units, but I gave the app to my girlfriend who has a Galaxy A71 (Android 12), it only finds the current localization her phone is set to. I also tested it on an emulated Google Pixel 4, which also uses Android 12, and I have the same issue. I have tried a variety of different ways of retrieving the locales, but everything I tried seemed to be getting EVERY locale that exists on the phone, not the locales of the localizations for the string resources. I don't want to hard code the language tags of the localizations in case I add more later, so I want it to be generalized. Any help would be appreciated.

Edit: I have discovered the source of the problem. It is not related to the version of Android, but rather the phone itself. If you don't have English and Spanish on the device, it will crash, but if you have English and Spanish installed on the device, it will work. I have realized now that resources.configuration.locales is getting the locales of the actual device, not all the locales of the string resources I have created in Android Studio. So I need to get these locales, not the locales of the device.

Body:
I currently have 2 localizations, English and Spanish, for an app I'm building to create recipes. Part of the recipe creation process involves doing some text parsing on each step. I am attempting to build a MutableMap of each localization and all the strings from a string-array of common measurement units. Here is how I am attempting to do this:

                for (i in 0 until resources.configuration.locales.size()) {
                    val currentLocaleList = resources.configuration.locales
                    val currentLocale = currentLocaleList.get(i).toLanguageTag()
                    val configuration = Configuration()
                    configuration.setLocale(Locale.forLanguageTag(currentLocale))
                    val context = context?.createConfigurationContext(configuration)
                    val measurementsLocaleUnits = context?.resources?.getStringArray(
                        R.array.measurement_units) as Array<String>
                    measurementLocales[currentLocale] = measurementsLocaleUnits
                }

When I test this on my Galaxy S21+ (Android 13), it works correctly. It finds the English and Spanish localizations of my string-array, measurement_units, but I gave the app to my girlfriend who has a Galaxy A71 (Android 12), it only finds the current localization her phone is set to. I also tested it on an emulated Google Pixel 4, which also uses Android 12, and I have the same issue. I have tried a variety of different ways of retrieving the locales, but everything I tried seemed to be getting EVERY locale that exists on the phone, not the locales of the localizations for the string resources. I don't want to hard code the language tags of the localizations in case I add more later, so I want it to be generalized. Any help would be appreciated.

Edit: I have discovered the source of the problem. It is not related to the version of Android, but rather the phone itself. If you don't have English and Spanish on the device, it will crash, but if you have English and Spanish installed on the device, it will work. I have realized now that resources.configuration.locales is getting the locales of the actual device, not all the locales of the string resources I have created in Android Studio. So I need to get these locales, not the locales of the device.


来源: stackexchange

问:
Python - API Tokens persisting across multiple threads with refresh token functionality
My goal here is to create a python script that makes many API calls as part of a back filling data ingestion process I am creating. We are taking a multithreaded approach to this as it has done wonders for us in the past. The difference that we have with this script versus the last time we used this approach is we have a limitation of 25 API sessions and the last time we had no limit. In order to limit the number of sessions open at a given moment, I was thinking about using a "library" of tokens. I'm using the actual idea of a book library, where a thread will "check out" a token and the max number of tokens available will be equal to the number of threads being used. There will be a check for if a token needs to be refreshed and if it does, it will replace the token in the token library. Has anyone done something like this in the past or have any other thoughts on how to approach this without exceeding the limit of 25 API sessions?

```<code>def generate_file(params):
    # thread lock
    # Check if all tokens are checked out and if library entry count is less than or equal to thread
    # count
    #    if no tokens are available, add a new k/v pair with a new token
    #    if at least 1 token available, update checked out status for token to Yes
    #         check if token needs to be refreshed, replace token in the token library if refresh
    #         needed
    # thread release
    # Do rest of the function

def run_process(params):
    with concurrent.futures.ThreadPoolExecutor(max_workers=cpu_count()-4) as executor:
        executor.map(generate_file, params)

if __name__ == "__main__":
    token_library = {}
    '''
    Example Structure:
    {'token_numX': [<token value>, <checked out status>],
     'token_numX2': [<token value>, <checked out status>]}
    '''
    run_process(params)
</code>```

To this point, I have gotten stuck trying to implement the token library. I'd love some feedback on my approach though.

ContentLicense: CC BY-SA 4.0

Body:
My goal here is to create a python script that makes many API calls as part of a back filling data ingestion process I am creating. We are taking a multithreaded approach to this as it has done wonders for us in the past. The difference that we have with this script versus the last time we used this approach is we have a limitation of 25 API sessions and the last time we had no limit. In order to limit the number of sessions open at a given moment, I was thinking about using a "library" of tokens. I'm using the actual idea of a book library, where a thread will "check out" a token and the max number of tokens available will be equal to the number of threads being used. There will be a check for if a token needs to be refreshed and if it does, it will replace the token in the token library. Has anyone done something like this in the past or have any other thoughts on how to approach this without exceeding the limit of 25 API sessions?

def generate_file(params):
    # thread lock
    # Check if all tokens are checked out and if library entry count is less than or equal to thread
    # count
    #    if no tokens are available, add a new k/v pair with a new token
    #    if at least 1 token available, update checked out status for token to Yes
    #         check if token needs to be refreshed, replace token in the token library if refresh
    #         needed
    # thread release
    # Do rest of the function

def run_process(params):
    with concurrent.futures.ThreadPoolExecutor(max_workers=cpu_count()-4) as executor:
        executor.map(generate_file, params)

if __name__ == "__main__":
    token_library = {}
    '''
    Example Structure:
    {'token_numX': [<token value>, <checked out status>],
     'token_numX2': [<token value>, <checked out status>]}
    '''
    run_process(params)

To this point, I have gotten stuck trying to implement the token library. I'd love some feedback on my approach though.


问:
Running python script that imports other python scripts with task scheduler
I'm trying to schedule a python script to run with Windows Task Scheduler but my run.py script imports many other python scripts in different directory (but in the same project). How do I do this?

I created a bat file that looks like this: "C:\Program Files\Python39\python.exe" "C:\Users\abxsdfd\PycharmProjects\abcxyz\run.py"
pause

but it doesn't work even though the status is running. I clicked the bat file to run and looked like it can't reference the other python scripts i imported in the run.py.


问:
Child UITableViewController does not scroll up when keyboard appears
I have searched as many posts as I found and still I cannot solve the problem. Please keep in mind that I have tried all the solutions provided that I have found and still when the keyboard appears the table does not scroll up, nor does it adjust its content view. The table v.c. is a child of a v.c., it is being pushed by the nav con (modal also does not work), below all of this sits a tab bar controller. Below is the code which I consider to be relevant.
Code inside the v.c.:

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    safeGuide = self.view.safeAreaLayoutGuide
    view.backgroundColor = UIColor.customColoursForAllElements(colourName: "background blue")
    programMainMenu = self.tabBarController as? ProgramMainMenu
    setTopViews()
    let msgsArea = ChatMsgsAreaTVC(typeForCurrentInstance: .singleChat(otherMemberName: self.otherMemberName), userUID: self.userUID, searchResultMsg: msgSelectedInSearch != nil ? msgSelectedInSearch : nil, searchTxt: self.searchTxt)
    msgsArea.valuesForSingleChat = chatDetails
    displayChild(controller: msgsArea)
}

    fileprivate func displayChild(controller: UIViewController) {
    self.addChild(controller)
    self.view.addSubview(controller.view)
    controller.view.translatesAutoresizingMaskIntoConstraints = false
    let childConstraints = [
        controller.view.topAnchor.constraint(equalTo: detailsContainer.bottomAnchor, constant: 10),
        controller.view.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: -55),
        controller.view.leadingAnchor.constraint(equalTo: backBtn.leadingAnchor),
        controller.view.trailingAnchor.constraint(equalTo: optionBtn.trailingAnchor)
    ]
    NSLayoutConstraint.activate(childConstraints)
    controller.didMove(toParent: self)
}
</code>```

the code below is from the child table view controller:

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIResponder.keyboardDidHideNotification, object: nil)
    configureMsgsTable()
    observeAudioRecAccess()
    setupAudioRecorder()
}
    override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.resignFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {self.becomeFirstResponder()}
}
override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
    override var canBecomeFirstResponder: Bool {return true}
override var canResignFirstResponder: Bool {return true}
@objc func keyboardWillShow(notification: Notification) {
    // note: changing the content size of the table does not work at all.
}
@objc fileprivate func keyboardDidHide() {
    if !bypassForSetup {bypassForSetup = true}
    else {
        if msgTxtArea.isFirstResponder {msgTxtArea.resignFirstResponder()}
        if addFileToMsgBtn.isSelected {addFileToMsgBtn.isSelected = false; addFileToMsgBtn.resignFirstResponder(); alterFileToMsgBtn(selected: false)}
    }
}
    fileprivate func configureMsgsTable() {
    tableView.contentInsetAdjustmentBehavior = .always
    tableView.backgroundColor = .clear
    tableView.keyboardDismissMode = .interactive
    tableView.separatorStyle = .none
    tableView.showsVerticalScrollIndicator = false
    tableView.estimatedRowHeight = 100
    tableView.sectionFooterHeight = 0.0
    tableView.scrollsToTop = false
    tableView.setBottomInset(to: -15)
}
</code>```

I also have a custom input accessory view that I have not included in this code.

Body:
I have searched as many posts as I found and still I cannot solve the problem. Please keep in mind that I have tried all the solutions provided that I have found and still when the keyboard appears the table does not scroll up, nor does it adjust its content view. The table v.c. is a child of a v.c., it is being pushed by the nav con (modal also does not work), below all of this sits a tab bar controller. Below is the code which I consider to be relevant.
Code inside the v.c.:

    override func viewDidLoad() {
    super.viewDidLoad()
    safeGuide = self.view.safeAreaLayoutGuide
    view.backgroundColor = UIColor.customColoursForAllElements(colourName: "background blue")
    programMainMenu = self.tabBarController as? ProgramMainMenu
    setTopViews()
    let msgsArea = ChatMsgsAreaTVC(typeForCurrentInstance: .singleChat(otherMemberName: self.otherMemberName), userUID: self.userUID, searchResultMsg: msgSelectedInSearch != nil ? msgSelectedInSearch : nil, searchTxt: self.searchTxt)
    msgsArea.valuesForSingleChat = chatDetails
    displayChild(controller: msgsArea)
}

    fileprivate func displayChild(controller: UIViewController) {
    self.addChild(controller)
    self.view.addSubview(controller.view)
    controller.view.translatesAutoresizingMaskIntoConstraints = false
    let childConstraints = [
        controller.view.topAnchor.constraint(equalTo: detailsContainer.bottomAnchor, constant: 10),
        controller.view.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: -55),
        controller.view.leadingAnchor.constraint(equalTo: backBtn.leadingAnchor),
        controller.view.trailingAnchor.constraint(equalTo: optionBtn.trailingAnchor)
    ]
    NSLayoutConstraint.activate(childConstraints)
    controller.didMove(toParent: self)
}

the code below is from the child table view controller:

    override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIResponder.keyboardDidHideNotification, object: nil)
    configureMsgsTable()
    observeAudioRecAccess()
    setupAudioRecorder()
}
    override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    self.resignFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    DispatchQueue.main.async {self.becomeFirstResponder()}
}
override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
    override var canBecomeFirstResponder: Bool {return true}
override var canResignFirstResponder: Bool {return true}
@objc func keyboardWillShow(notification: Notification) {
    // note: changing the content size of the table does not work at all.
}
@objc fileprivate func keyboardDidHide() {
    if !bypassForSetup {bypassForSetup = true}
    else {
        if msgTxtArea.isFirstResponder {msgTxtArea.resignFirstResponder()}
        if addFileToMsgBtn.isSelected {addFileToMsgBtn.isSelected = false; addFileToMsgBtn.resignFirstResponder(); alterFileToMsgBtn(selected: false)}
    }
}
    fileprivate func configureMsgsTable() {
    tableView.contentInsetAdjustmentBehavior = .always
    tableView.backgroundColor = .clear
    tableView.keyboardDismissMode = .interactive
    tableView.separatorStyle = .none
    tableView.showsVerticalScrollIndicator = false
    tableView.estimatedRowHeight = 100
    tableView.sectionFooterHeight = 0.0
    tableView.scrollsToTop = false
    tableView.setBottomInset(to: -15)
}

I also have a custom input accessory view that I have not included in this code.


问:
Swiper.js and Alpine.js - Hide Navigation When Not Needed
I'm using Swiper.js with Alpine.js to create a slider, but I'd like to hide the navigation buttons if there are no items on either side. So, if there are no items to the left, the navigation button should be hidden until there are some items.

This is how I'm using Swiper with Alpine:

```<code><div x-data="{swiper: null}"
    x-init="
    swiper = new Swiper
    ($refs.container, {
        loop: false,
        slidesPerView: 'auto',
        spaceBetween: 0,

        observer: true,
        observeParents: true,

        breakpoints: {
                640: {
                slidesPerView: 2,
                spaceBetween: 0,
                },
                768: {
                slidesPerView: 4,
                spaceBetween: 0,
                },
                1024: {
                slidesPerView: 7.5,
                spaceBetween: 0,
                },
        },
    })
    "
    class="relative max-w-screen-xl mx-auto flex flex-row"
>
</code>```

And then for the navigation buttons on each side:

```<code><div class="absolute inset-y-0 left-0 z-10 flex items-center">
    <button @click="swiper.slidePrev()"
            class="bg-white -ml-2 lg:-ml-4 flex justify-center items-center w-10 h-10 rounded-full shadow focus:outline-none">
        <svg viewBox="0 0 20 20" fill="currentColor" class="chevron-left w-6 h-6">
            <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
                    clip-rule="evenodd"></path>
        </svg>
    </button>
</div>
</code>```

I'd love any help, thanks!

Body:
I'm using Swiper.js with Alpine.js to create a slider, but I'd like to hide the navigation buttons if there are no items on either side. So, if there are no items to the left, the navigation button should be hidden until there are some items.

This is how I'm using Swiper with Alpine:

<div x-data="{swiper: null}"
    x-init="
    swiper = new Swiper
    ($refs.container, {
        loop: false,
        slidesPerView: 'auto',
        spaceBetween: 0,

        observer: true,
        observeParents: true,

        breakpoints: {
                640: {
                slidesPerView: 2,
                spaceBetween: 0,
                },
                768: {
                slidesPerView: 4,
                spaceBetween: 0,
                },
                1024: {
                slidesPerView: 7.5,
                spaceBetween: 0,
                },
        },
    })
    "
    class="relative max-w-screen-xl mx-auto flex flex-row"
>

And then for the navigation buttons on each side:

    <button @click="swiper.slidePrev()"
            class="bg-white -ml-2 lg:-ml-4 flex justify-center items-center w-10 h-10 rounded-full shadow focus:outline-none">
        <svg viewBox="0 0 20 20" fill="currentColor" class="chevron-left w-6 h-6">
            <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
                    clip-rule="evenodd"></path>
        </svg>
    </button>

I'd love any help, thanks!


问:
how to use |safe in Rich Text Field with django to json
how to use |safe in Rich Text Field with django to json

enter image description here
enter image description here

**models
**```</p>
<p>class Question(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)</p>
```# image = models.FileField(upload_to = "files/images", blank=True, null=True)
# question = models.CharField(max_length=500)
question= RichTextField()
answer = models.IntegerField()
option_one = models.CharField(max_length=500)
option_two = models.CharField(max_length=500)
option_three = models.CharField(max_length=500 , blank=True)
option_four = models.CharField(max_length=500 , blank=True)
is_preview = models.BooleanField(default = False)
marks = models.IntegerField(default=1)

def __str__(self):
    return self.question

def get_questions(self):
    questions = list(self.raw_questions.all())
    random.shuffle(questions)
    return questions[:self.number_of_questions]

class Meta:
    verbose_name_plural = 'Quizes'
```
``` views
```
<p>def api_question(request , id):</p>
```raw_questions = Question.objects.filter(course =id ,is_preview=True)

questions = []

for raw_question in raw_questions:
    question = {}
    question['id'] = raw_question.id
    question['question']= raw_question.question

    # question['image'] = raw_question.question
    question['answer'] = raw_question.answer
    question['marks'] = raw_question.marks
    options = []
    options.append(raw_question.option_one)
    options.append(raw_question.option_two)
    # options.append(raw_question.image)
    if raw_question.option_three != '':
        options.append(raw_question.option_three)

    if raw_question.option_four != '':
        options.append(raw_question.option_four)

    question['options'] = options

    questions.append(question)
    random.shuffle(questions)
```
<p>def take_quiz(request , id):
Active = Course.objects.all()</p>
```context = {'id' : id,'active':Active}

return render(request , 'quiz2.html'  , context)
```
```

>! html
```
```    <form @submit.prevent="handleSubmit()"'>
```

<p>**           <h3 >  [[index + 1 ]].[[ question.question|safe ]] </h3>
**</p>
```

                [[option]]

Prof. AboRashad

  <button class="btn btn-danger" type="submit" style='width: 100%'>Send</button>
    </form>

var app = new Vue({
    delimiters: ['[[', ']]'],
    el: '#app',
    data: {
        message: 'Hello Vue!',
        course_id: '{{id}}',
        questions: [],
        solutions: []
    },
    methods: {
        greet: function (name) {
            console.log('Hello from ' + name + '!')
        },
        check(question_index, option_index, id) {

            var question = this.questions[question_index]
            var element = document.getElementById(`show_message-${id}`)

            // if((option_index + 1).toString()==question.answer){
            //  element.classList="text-success mt-3"
            //  element.innerHTML ="Right Answer "
            //  }else{
            //   element.classList="text-danger mt-3"
            //   element.innerHTML ="weong Answer "
            //  },

            var radios = document.querySelectorAll(`#radio-${id}`)
            for (var i = 0; i < radios.length; i++) {
                radios[i].disabled = true
            }

            var solution = {
                'question_id': id,
                'option': option_index + 1
            }
            this.solutions.push(solution)
        },
        handleSubmit() {

            fetch('/api/check_score', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                   data : JSON.stringify(this.solutions),
                   course_id : this.course_id
                })
            })
        .then(res => res.json())
        .then(result => {
            console.log(result)
            window.location = '/view_score'
        })

    }
},

mounted() {

    fetch(`/api/${this.course_id }`)
        .then(res => res.json())
        .then(result => {
            this.questions = result

        })

}
});
```

Body:
how to use |safe in Rich Text Field with django to json

enter image description here
enter image description here

**models
**```

class Question(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)

# image = models.FileField(upload_to = "files/images", blank=True, null=True)
# question = models.CharField(max_length=500)
question= RichTextField()
answer = models.IntegerField()
option_one = models.CharField(max_length=500)
option_two = models.CharField(max_length=500)
option_three = models.CharField(max_length=500 , blank=True)
option_four = models.CharField(max_length=500 , blank=True)
is_preview = models.BooleanField(default = False)
marks = models.IntegerField(default=1)

def __str__(self):
    return self.question

def get_questions(self):
    questions = list(self.raw_questions.all())
    random.shuffle(questions)
    return questions[:self.number_of_questions]

class Meta:
    verbose_name_plural = 'Quizes'

 views

def api_question(request , id):

raw_questions = Question.objects.filter(course =id ,is_preview=True)

questions = []

for raw_question in raw_questions:
    question = {}
    question['id'] = raw_question.id
    question['question']= raw_question.question

    # question['image'] = raw_question.question
    question['answer'] = raw_question.answer
    question['marks'] = raw_question.marks
    options = []
    options.append(raw_question.option_one)
    options.append(raw_question.option_two)
    # options.append(raw_question.image)
    if raw_question.option_three != '':
        options.append(raw_question.option_three)

    if raw_question.option_four != '':
        options.append(raw_question.option_four)

    question['options'] = options

    questions.append(question)
    random.shuffle(questions)

def take_quiz(request , id):
Active = Course.objects.all()

context = {'id' : id,'active':Active}

return render(request , 'quiz2.html'  , context)

>! html

    <form @submit.prevent="handleSubmit()"'>

**
  [[index + 1 ]].[[ question.question|safe ]]

**

                [[option]]

Prof. AboRashad

  <button class="btn btn-danger" type="submit" style='width: 100%'>Send</button>
    </form>

var app = new Vue({
    delimiters: ['[[', ']]'],
    el: '#app',
    data: {
        message: 'Hello Vue!',
        course_id: '{{id}}',
        questions: [],
        solutions: []
    },
    methods: {
        greet: function (name) {
            console.log('Hello from ' + name + '!')
        },
        check(question_index, option_index, id) {

            var question = this.questions[question_index]
            var element = document.getElementById(`show_message-${id}`)

            // if((option_index + 1).toString()==question.answer){
            //  element.classList="text-success mt-3"
            //  element.innerHTML ="Right Answer "
            //  }else{
            //   element.classList="text-danger mt-3"
            //   element.innerHTML ="weong Answer "
            //  },

            var radios = document.querySelectorAll(`#radio-${id}`)
            for (var i = 0; i < radios.length; i++) {
                radios[i].disabled = true
            }

            var solution = {
                'question_id': id,
                'option': option_index + 1
            }
            this.solutions.push(solution)
        },
        handleSubmit() {

            fetch('/api/check_score', {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                   data : JSON.stringify(this.solutions),
                   course_id : this.course_id
                })
            })
        .then(res => res.json())
        .then(result => {
            console.log(result)
            window.location = '/view_score'
        })

    }
},

mounted() {

    fetch(`/api/${this.course_id }`)
        .then(res => res.json())
        .then(result => {
            this.questions = result

        })

}
});


问:
NextJS Actioncable Proxy
So I'm trying to do two things at the same time and it's not going too well.
I have a NextJS app and a Rails API server this app connects to. For authentication I'm using a JWT token stored in an http-only encrypted cookie that the Rails API sets and the front end should not be touching. Naturally that creates a necessity for the frontend to send all the api requests though the NextJs server which proxies them to the real API.

To do that I have set up a next-http-proxy-middleware in my /pages/api/[...path] in the following way:

export const config = { api: { bodyParser: false, externalResolver: true } }

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  httpProxyMiddleware(req, res, {
    target: process.env.BACKEND_URL,
    pathRewrite: [{ patternStr: "^/?api", replaceStr: "" }],
  })
}
```
<p>Which works great and life would be just great, but turns out I need to do the same thing with ActionCable subscriptions. Not to worry, found some handy tutorials, packed <code>@rails/actioncable</code> into my package list and off we go.</p>
<pre class="lang-js prettyprint-override"><code>import {useCurrentUser} from "../../../data";
import {useEffect, useState} from "react";

const UserSocket = () => {
  const { user } = useCurrentUser()
  const [roomSocket, setRoomSocket] = useState<any>(null)

  const loadConsumer = async () => {
    // @ts-ignore
    const { createConsumer } = await import("@rails/actioncable")
    const newCable = createConsumer('/api/wsp')
    console.log('Cable loaded')
    setRoomSocket(newCable.subscriptions.create({
      channel: 'RoomsChannel'
    },{
      connected: () => { console.log('Room Connected') },
      received: (data: any) => { console.log(data) },
    }))
    return newCable
  }

  useEffect(() => {
    if (typeof window !== 'undefined' && user?.id) {
      console.log('Cable loading')
      loadConsumer().then(() => {
        console.log('Cable connected')
      })
    }
    return () => { roomSocket?.disconnect() }
  }, [typeof window, user?.id])

  return <></>
}

export default UserSocket
</code>```

Now when I go to load the page with that component, I get the log output all the way to Cable connected however I don't see the Room Connected part.

I tried looking at the requests made and for some reason I see 2 requests made to wsp. First is directed at the Rails backend (which means the proxy worked) but it lacks the Cookie headers and thus gets disconnected like this:

{
    "type": "disconnect",
    "reason": "unauthorized",
    "reconnect": false
}
```

The second request is just shown as ws://localhost:5000/api/wsp (which is my NextJS dev server) with provisional headers and it just hangs up in pending. So neither actually connect properly to the websocket. But if I just replace the /api/wsp parameter with the actual hardcoded API address (ws://localhost:3000/wsp) it all works at once (that however would not work in production since those will be different domains).
Can anyone help me here? I might be missing something dead obvious but can't figure it out.

Title: NextJS Actioncable Proxy

Body:
So I'm trying to do two things at the same time and it's not going too well.
I have a NextJS app and a Rails API server this app connects to. For authentication I'm using a JWT token stored in an http-only encrypted cookie that the Rails API sets and the front end should not be touching. Naturally that creates a necessity for the frontend to send all the api requests though the NextJs server which proxies them to the real API.

To do that I have set up a next-http-proxy-middleware in my /pages/api/[...path] in the following way:

export const config = { api: { bodyParser: false, externalResolver: true } }

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  httpProxyMiddleware(req, res, {
    target: process.env.BACKEND_URL,
    pathRewrite: [{ patternStr: "^/?api", replaceStr: "" }],
  })
}

Which works great and life would be just great, but turns out I need to do the same thing with ActionCable subscriptions. Not to worry, found some handy tutorials, packed @rails/actioncable into my package list and off we go.

import {useCurrentUser} from "../../../data";
import {useEffect, useState} from "react";

const UserSocket = () => {
  const { user } = useCurrentUser()
  const [roomSocket, setRoomSocket] = useState<any>(null)

  const loadConsumer = async () => {
    // @ts-ignore
    const { createConsumer } = await import("@rails/actioncable")
    const newCable = createConsumer('/api/wsp')
    console.log('Cable loaded')
    setRoomSocket(newCable.subscriptions.create({
      channel: 'RoomsChannel'
    },{
      connected: () => { console.log('Room Connected') },
      received: (data: any) => { console.log(data) },
    }))
    return newCable
  }

  useEffect(() => {
    if (typeof window !== 'undefined' && user?.id) {
      console.log('Cable loading')
      loadConsumer().then(() => {
        console.log('Cable connected')
      })
    }
    return () => { roomSocket?.disconnect() }
  }, [typeof window, user?.id])

  return <></>
}

export default UserSocket

Now when I go to load the page with that component, I get the log output all the way to Cable connected however I don't see the Room Connected part.

I tried looking at the requests made and for some reason I see 2 requests made to wsp. First is directed at the Rails backend (which means the proxy worked) but it lacks the Cookie headers and thus gets disconnected like this:

{
    "type": "disconnect",
    "reason": "unauthorized",
    "reconnect": false
}

The second request is just shown as ws://localhost:5000/api/wsp (which is my NextJS dev server) with provisional headers and it just hangs up in pending. So neither actually connect properly to the websocket. But if I just replace the /api/wsp parameter with the actual hardcoded API address (ws://localhost:3000/wsp) it all works at once (that however would not work in production since those will be different domains).
Can anyone help me here? I might be missing something dead obvious but can't figure it out.


问:
Telegrambots and several pictures in message
When sending several photos in telegram messenger, bot recieves each picture separately with same mediaGroupId. But how can I resend all the pictures somewhere if I don't know how much messages/pictures I'm going to receive?</p>


问:
Automatically reduce thumbnail image size on Quarto website
I've set up a website using the Quarto blog template, which includes a list of several posts and thumbnails for each of the posts. By default the thumbnails are taken from the first image included the post, if there is no image: specified in the YAML-like section at the start of the post's .qmd file. This works great, but many of the images I use in are very high definition (thousands of px across) – this is what I want in the posts themselves, but means that even on fast internet the website's homepage can take a while to load all the images.

Is there any automatic way to resize each of the thumbnail images so they're at most a few hundred px across?

If there isn't already a simple way to do this, I could write a script that found the thumbnail image for each post, created a resized version, saved it to the directory for the post, then specified that thumbnail as the image: for the post – I think I could get that to run using the pre-render: project option. But thought it worth checking there isn't already an easier way to achieve the same thing!


问:
nodejs shopify rest api pagination
I'm trying to get all products from Shopify store via rest API and with

```<code>direction=next&last_id=id
</code>```

it does not return all products.

I see that there is a different way to paginate products endpoint with headers but I'm not pretty good with NodeJS and don't know how to strip strings that I receive to have only needed parameters.

Below is response example and I need only page_info from rel="next" element

```<code><https://xxx.myshopify.com/admin/api/2022-10/products.json?limit=250&page_info=xxx>; rel="previous", <https://xxx.myshopify.com/admin/api/2022-10/products.json?limit=250&page_info=xxx>; rel="next"
</code>```

any ideas?

splitting to array and search by chars

Title: nodejs shopify rest api pagination

Body:
I'm trying to get all products from Shopify store via rest API and with

direction=next&last_id=id

it does not return all products.

I see that there is a different way to paginate products endpoint with headers but I'm not pretty good with NodeJS and don't know how to strip strings that I receive to have only needed parameters.

Below is response example and I need only page_info from rel="next" element

<https://xxx.myshopify.com/admin/api/2022-10/products.json?limit=250&page_info=xxx>; rel="previous", <https://xxx.myshopify.com/admin/api/2022-10/products.json?limit=250&page_info=xxx>; rel="next"

any ideas?

splitting to array and search by chars


问:
MUI snackbar div persist on DOM after being closed
I created a global modal with the purpose of only calling it when I need it, but the problem is that the snackbar div persists in the DOM and this causes certain elements to be blocked because they are below this div. Any idea what the problem would be?

My GlobalAlert component:

```<code>export function GlobalAlert() {
  const {alertState, handleClose} = useAlertContext();
  const {open, type, message} = alertState;

  function TransitionDown(props: TransitionProps) {
    return <Slide {...props} direction="down" />;
  }

  return (
    <Snackbar
      key={"top" + "center"}
      TransitionComponent={TransitionDown}
      anchorOrigin={{vertical: "top", horizontal: "center"}}
      autoHideDuration={4000}
      disableWindowBlurListener={true}
      open={open}
      onClose={handleClose}
    >
      <Alert severity={type} sx={useStyles.alert} variant="filled" onClose={handleClose}>
        {message}
      </Alert>
    </Snackbar>
  );
}
</code>```

Context where I get the info

```<code>const AlertContextProvider = (props: any) => {
  const [alertState, setAlertState] = React.useState<AlertState>({
    open: false,
    type: "error",
    message: "",
  });

  const handleClose = React.useCallback((event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === "clickaway") {
      return;
    }
    setAlertState({
      open: false,
      type: "error",
      message: "",
    });
  }, []);

  const value = React.useMemo(
    () => ({
      alertState,
      setAlertState,
      handleClose,
    }),
    [alertState, handleClose],
  );

  return <AlertContext.Provider value={value} {...props} />;
};
</code>```

Bug image

Body:
I created a global modal with the purpose of only calling it when I need it, but the problem is that the snackbar div persists in the DOM and this causes certain elements to be blocked because they are below this div. Any idea what the problem would be?

My GlobalAlert component:

export function GlobalAlert() {
  const {alertState, handleClose} = useAlertContext();
  const {open, type, message} = alertState;

  function TransitionDown(props: TransitionProps) {
    return <Slide {...props} direction="down" />;
  }

  return (
    <Snackbar
      key={"top" + "center"}
      TransitionComponent={TransitionDown}
      anchorOrigin={{vertical: "top", horizontal: "center"}}
      autoHideDuration={4000}
      disableWindowBlurListener={true}
      open={open}
      onClose={handleClose}
    >
      <Alert severity={type} sx={useStyles.alert} variant="filled" onClose={handleClose}>
        {message}
      </Alert>
    </Snackbar>
  );
}

Context where I get the info

const AlertContextProvider = (props: any) => {
  const [alertState, setAlertState] = React.useState<AlertState>({
    open: false,
    type: "error",
    message: "",
  });

  const handleClose = React.useCallback((event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === "clickaway") {
      return;
    }
    setAlertState({
      open: false,
      type: "error",
      message: "",
    });
  }, []);

  const value = React.useMemo(
    () => ({
      alertState,
      setAlertState,
      handleClose,
    }),
    [alertState, handleClose],
  );

  return <AlertContext.Provider value={value} {...props} />;
};

Bug image


Title: Python: Linear interpolation for CDS rates based on maturity represented in years

Body:
I am trying to linearly interpolate a series of CDS rates. Below is the data I have available; it is represented as maturities and in years.

    Maturity    Company 1   Company 2
0   0.5 186.73  186.73
1   1.0 210.65  210.65
2   2.0 249.09  249.09
3   3.0 285.4   285.4
4   4.0 317.59  317.59
5   5.0 344.06  344.06
6   6.0 363.01  363.01
7   7.0 375.69  375.69
8   8.0 384.31  384.31
9   9.0 391.0   391.0
10  10.0    396.12  396.12

I am now trying to use this set of maturities and their CDS rate in a similar format to interpolate the rate; below is an example of the maturities I will need to interpolate.

    Maturity Years
28  0.10410958904109589
29  0.1863013698630137
30  0.27671232876712326
31  0.3561643835616438
32  0.4328767123287671
33  0.5260273972602739
34  0.5945205479452055
35  0.684931506849315
36  0.7753424657534247
37  0.852054794520548
38  0.9397260273972603
39  1.0164383561643835
40  1.104109589041096
41  1.1863013698630136
42  1.2728102189781023
43  1.35492700729927
44  1.4343065693430657
45  1.5136861313868615
46  1.6012773722627738
47  1.686131386861314
48  1.770985401459854
49  1.853102189781022
50  1.9434306569343067
51  2.02007299270073
52  2.10492700729927
53  2.184306569343066
54  2.2751540041067764
55  2.3572895277207393
56  2.433949349760438
57  2.518822724161533
58  2.6009582477754964
59  2.6830937713894594
60  2.7707049965776864
61  2.8528405201916494
62  2.940451745379877
63  3.0198494182067077
64  3.1047227926078027
65  3.1813826146475015
66  3.2749178532311065
67  3.3543263964950714
68  3.4309967141292446
69  3.521358159912377
70  3.6007667031763417
71  3.6801752464403066
72  3.7677984665936473
73  3.8526834611171963
74  3.940306681270537
75  4.019715224534502
76  4.101861993428258
77  4.186746987951808
78  4.274760383386581
79  4.351437699680511
80  4.4281150159744405
81  4.518484710178001
82  4.600638977635782
83  4.68553172067549
84  4.767685988133272
85  4.8498402555910545
86  4.940209949794614
87  5.0196257416704695
88  5.099041533546326
89  5.18667275216796
90  5.269847477512711
91  5.354712553773954
92  5.434102463824795
93  5.518967540086038
94  5.595619867031678
95  5.685960109503324
96  5.776300351974971
97  5.8529526789206106
98  5.940555338287055
99  6.017207665232695
100 6.10481032459914
101 6.186937817755182
102 6.275154004106776
103 6.357289527720739
104 6.433949349760438
105 6.5160848733744015
106 6.6009582477754964
107 6.685831622176591
108 6.7734428473648185
109 6.852840520191649
110 6.945927446954141
111 7.014373716632443
112 7.104722792607803
113 7.186858316221766
114 7.275022817158503
115 7.3571645877700025
116 7.433830240340736
117 7.513233951931853
118 7.600851840584119
119 7.685731670216002
120 7.7706114998478855
121 7.852753270459385
122 7.943109218132035
123 8.019774870702769
124 8.10465470033465
125 8.184058411925768
126 8.274917853231106
127 8.357064622124863
128 8.433734939759036
129 8.518619934282585
130 8.600766703176342
131 8.6829134720701
132 8.77053669222344
133 8.852683461117197
134 8.940306681270537
135 9.019715224534503
136 9.104600219058051
137 9.181270536692224
138 9.272523643603783
139 9.35191637630662

In the past, I have created log-linear interpolation functions that will allow me to interpolate discount rates based on maturities represented as dates, not as yearly numerical values; below is an example of that function.

def loglinearinterpolation(df, list_of_dates, dt_rng_name, rate_rng_name):
    asofDate = pd.to_datetime(list_of_dates)
    low_lim = df[df[dt_rng_name] <= asofDate].tail(1)
    upper_lim = df[df[dt_rng_name] >= asofDate].head(1)
    if low_lim.index == upper_lim.index:
        return low_lim[rate_rng_name].iloc[0]
    mat_dt_min = low_lim[dt_rng_name].iloc[0]
    mat_dt_max = upper_lim[dt_rng_name].iloc[0]
    y_min = low_lim[rate_rng_name].iloc[0]
    y_max = upper_lim[rate_rng_name].iloc[0]
    return np.exp(((np.log(y_max) - np.log(y_min))/((mat_dt_max - mat_dt_min).days))*(asofDate - mat_dt_min).days + np.log(y_min))

df_Libor_interpolated = pd.DataFrame()
df_Libor_interpolated = [(pd.to_datetime(x), loglinearinterpolation(df_libor_curve, pd.to_datetime(
    x), 'Dates', 'value')) for x in df_client_curve['Date'].unique()]

I now need to do a similar task using the same formula in the return function, except linearly, not log linearly; however, my code is breaking as the values I am feeding for dates are being converted to DateTime and providing numpy and timestamp comparison errors.

I have tried using the code below as a workaround; however, it is not providing me with the values my team expects.

[np.interp(x,df_cds['Maturity'],df_cds['Company 1']) for x in df_cds_interpolated['Maturity Years']]

Any guidance or insight on how I can modify the function and formula above to work with the input data I provided would be greatly appreciated!


问:
Electron - How to write e2e tests?
I am using electron react boilerplate as base for my project. I wrote small backend for it, which uses winston to write logs.
Jest can easly test single functions and components but I need help with e2e tests. Because this app is using ipcRenderer, cypress throws errors that ipcRenderer is undefined so it cannot connect backend.

Are there any tools that can access electron's ipcRenderer to send messages ? Easiest way to fix it would be to push electron as dependency, instead of devDependency, but I don't think it should be done that way
Thx in advance

Title: Electron - How to write e2e tests?


问:
I got this bug while tryimg to run my app "Error in Inflating Class Fragment"
```<code>Caused by: android.view.InflateException: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Error inflating class fragment                                                                                Caused by: android.view.InflateException: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Error inflating class fragment                                                                                Caused by: kotlin.UninitializedPropertyAccessException: lateinit property viewModel has not been initialized
at com.androiddevs.mvvmnewsapp.ui.NewsActivity.getViewModel(NewsActivity.kt:15)                                                                                at com.androiddevs.mvvmnewsapp.ui.fragments.BreakingNewsFragment.onCreateView(BreakingNewsFragment.kt:29)                                                                           at
</code>```

These are the codes Involved
My activity News Xml

```<code>    <FrameLayout
        android:id="@+id/flFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <fragment
            android:id="@+id/newsNavHostFragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/news_nav_graph" />
    </FrameLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:menu="@menu/bottom_navigation_menu"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

Breaking News Fragment

```<code>class BreakingNewsFragment:Fragment() {
    lateinit var binding: FragmentBreakingNewsBinding
    lateinit var viewModel: NewsViewModel
    lateinit var newsAdapter:NewsAdapter
    val TAG = "BreakingNewsFragment"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBreakingNewsBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupRecyclerView()
        viewModel = (activity as NewsActivity).viewModel
        viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response ->
            when(response){
                is Resource.Success -> {
                    hideProgressBar()
                    response.data?.let { newsResponse ->
                        newsAdapter.differ.submitList(newsResponse.articles)
                    }
                }
                is Resource.Error ->{
                    hideProgressBar()
                    response.message?.let { message ->
                        Log.e(TAG, "An error occured: $message")
                    }
                }
                is Resource.Loading ->{
                    showProgressBar()
                }
            }
        })
    }

    private fun hideProgressBar(){
        binding.paginationProgressBar.visibility = View.INVISIBLE
    }

    private fun showProgressBar(){
        binding.paginationProgressBar.visibility = View.VISIBLE
    }

    private fun setupRecyclerView(){
        newsAdapter = NewsAdapter()
        binding.rvBreakingNews.apply {
            adapter = newsAdapter
            layoutManager = LinearLayoutManager(activity)
        }
    }
}
</code>```

News Activity

```<code>class NewsActivity : AppCompatActivity() {
    lateinit var viewModel: NewsViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_news)

        val newsRepository = NewsRepository(ArticleDatabase(this))
        val viewModelProviderFactory = NewsViewModelProviderFactory(newsRepository)
        viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        val newsNavHostFragment = findViewById<View>(R.id.newsNavHostFragment)
       bottomNavigationView.setupWithNavController(newsNavHostFragment.findNavController())
    }
}
</code>```

Body:
Caused by: android.view.InflateException: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Error inflating class fragment                                                                                Caused by: android.view.InflateException: Binary XML file line #25 in com.androiddevs.mvvmnewsapp:layout/activity_news: Error inflating class fragment                                                                                Caused by: kotlin.UninitializedPropertyAccessException: lateinit property viewModel has not been initialized
at com.androiddevs.mvvmnewsapp.ui.NewsActivity.getViewModel(NewsActivity.kt:15)                                                                                at com.androiddevs.mvvmnewsapp.ui.fragments.BreakingNewsFragment.onCreateView(BreakingNewsFragment.kt:29)                                                                           at

These are the codes Involved
My activity News Xml

    <FrameLayout
        android:id="@+id/flFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <fragment
            android:id="@+id/newsNavHostFragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:navGraph="@navigation/news_nav_graph" />
    </FrameLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:menu="@menu/bottom_navigation_menu"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Breaking News Fragment

class BreakingNewsFragment:Fragment() {
    lateinit var binding: FragmentBreakingNewsBinding
    lateinit var viewModel: NewsViewModel
    lateinit var newsAdapter:NewsAdapter
    val TAG = "BreakingNewsFragment"

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBreakingNewsBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupRecyclerView()
        viewModel = (activity as NewsActivity).viewModel
        viewModel.breakingNews.observe(viewLifecycleOwner, Observer { response ->
            when(response){
                is Resource.Success -> {
                    hideProgressBar()
                    response.data?.let { newsResponse ->
                        newsAdapter.differ.submitList(newsResponse.articles)
                    }
                }
                is Resource.Error ->{
                    hideProgressBar()
                    response.message?.let { message ->
                        Log.e(TAG, "An error occured: $message")
                    }
                }
                is Resource.Loading ->{
                    showProgressBar()
                }
            }
        })
    }

    private fun hideProgressBar(){
        binding.paginationProgressBar.visibility = View.INVISIBLE
    }

    private fun showProgressBar(){
        binding.paginationProgressBar.visibility = View.VISIBLE
    }

    private fun setupRecyclerView(){
        newsAdapter = NewsAdapter()
        binding.rvBreakingNews.apply {
            adapter = newsAdapter
            layoutManager = LinearLayoutManager(activity)
        }
    }
}

News Activity

class NewsActivity : AppCompatActivity() {
    lateinit var viewModel: NewsViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_news)

        val newsRepository = NewsRepository(ArticleDatabase(this))
        val viewModelProviderFactory = NewsViewModelProviderFactory(newsRepository)
        viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        val newsNavHostFragment = findViewById<View>(R.id.newsNavHostFragment)
       bottomNavigationView.setupWithNavController(newsNavHostFragment.findNavController())
    }
}


问:
Converting php aes256 decrypt function to typescript gives
I have a PHP aes256 decrypt function I am trying to convert to typescript in ionic 5 but I am faced with the following error using md5:

This expression is not callable.   Type 'any[]' has no call
signatures.

PHP decrypt function:

```<code>function decrypt(string $jsonStr, string $passphrase)
    {
        $json = json_decode($jsonStr, true);
        $salt = hex2bin($json["s"]);
        $iv = hex2bin($json["iv"]);
        $ct = base64_decode($json["ct"]);
        $concatedPassphrase = $passphrase . $salt;
        $md5 = [];
        $md5[0] = md5($concatedPassphrase, true);
        $result = $md5[0];
        for ($i = 1; $i < 3; $i++) {
            $md5[$i] = md5($md5[$i - 1] . $concatedPassphrase, true);
            $result .= $md5[$i];
        }
        $key = substr($result, 0, 32);
        $data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
        return json_decode($data, true);
    }
</code>```

Typescript converted:

```<code>async dcrypt(data: string, passphrase: string){

    const json = JSON.parse(data);
    const salt = decode(json["s"]);
    const iv = decode(json["iv"]);
    const ct = decode(json["ct"]);
    const concatedPassphrase = passphrase + salt;
    const md5 = [];
    md5[0] = md5(concatedPassphrase, true);
    let result = md5[0];
    for (let i = 1; i < 3; i++) {
      md5[i] = md5(md5[i - 1] + concatedPassphrase, true);
      result += md5[i];
    }
    const key = result.substr(0, 32);
    const importedKey = await window.crypto.subtle.importKey(
      'raw',
      new Uint8Array(key),
      {
        name: 'AES-CBC'
      },
      false,
      ['decrypt']
    );
    const data = await window.crypto.subtle.decrypt(
      {
        name: 'AES-CBC',
        iv: new Uint8Array(iv)
      },
      importedKey,
      new Uint8Array(ct)
    );
    return JSON.parse(new TextDecoder().decode(data));

  }
</code>```

Both md5 functions: md5(concatedPassphrase, true) && md5(md5[i - 1] + concatedPassphrase, true) are giving me the following error:

This expression is not callable.   Type 'any[]' has no call
signatures.

How can I resolve this issue using md5?

Body:
I have a PHP aes256 decrypt function I am trying to convert to typescript in ionic 5 but I am faced with the following error using md5:

This expression is not callable.   Type 'any[]' has no call
signatures.

PHP decrypt function:

function decrypt(string $jsonStr, string $passphrase)
    {
        $json = json_decode($jsonStr, true);
        $salt = hex2bin($json["s"]);
        $iv = hex2bin($json["iv"]);
        $ct = base64_decode($json["ct"]);
        $concatedPassphrase = $passphrase . $salt;
        $md5 = [];
        $md5[0] = md5($concatedPassphrase, true);
        $result = $md5[0];
        for ($i = 1; $i < 3; $i++) {
            $md5[$i] = md5($md5[$i - 1] . $concatedPassphrase, true);
            $result .= $md5[$i];
        }
        $key = substr($result, 0, 32);
        $data = openssl_decrypt($ct, 'aes-256-cbc', $key, true, $iv);
        return json_decode($data, true);
    }

Typescript converted:

async dcrypt(data: string, passphrase: string){

    const json = JSON.parse(data);
    const salt = decode(json["s"]);
    const iv = decode(json["iv"]);
    const ct = decode(json["ct"]);
    const concatedPassphrase = passphrase + salt;
    const md5 = [];
    md5[0] = md5(concatedPassphrase, true);
    let result = md5[0];
    for (let i = 1; i < 3; i++) {
      md5[i] = md5(md5[i - 1] + concatedPassphrase, true);
      result += md5[i];
    }
    const key = result.substr(0, 32);
    const importedKey = await window.crypto.subtle.importKey(
      'raw',
      new Uint8Array(key),
      {
        name: 'AES-CBC'
      },
      false,
      ['decrypt']
    );
    const data = await window.crypto.subtle.decrypt(
      {
        name: 'AES-CBC',
        iv: new Uint8Array(iv)
      },
      importedKey,
      new Uint8Array(ct)
    );
    return JSON.parse(new TextDecoder().decode(data));

  }

Both md5 functions: md5(concatedPassphrase, true) && md5(md5[i - 1] + concatedPassphrase, true) are giving me the following error:

This expression is not callable.   Type 'any[]' has no call
signatures.

How can I resolve this issue using md5?


问:
use of designated initializers requires at least '/std:c++20' and cannot mix designated-initializers with non-designated-initializers
I want to install repast4py in windows 10, and I enter 'pip install repast4py' in cmd, but It displays errors
'src/repast4py/coremodule.cpp(342): error C7556: cannot mix designated-initializers with non-designated-initializers' and
'error C7555: use of designated initializers requires at least '/std:c++20',
After that I update my visual studio build tools to 2022, but yet It displays the same error. please help me. thanks

```<code>C:\Users\H.Zibaei>pip install repast4py
Collecting repast4py
  Using cached repast4py-1.0.5b1.tar.gz (79 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting torch
  Using cached torch-1.13.1-cp39-cp39-win_amd64.whl (162.5 MB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Requirement already satisfied: mpi4py in c:\users\h.zibaei\appdata\local\programs\python\python39\lib\site-packages (from repast4py) (3.1.4)
Collecting numba
  Using cached numba-0.56.4-cp39-cp39-win_amd64.whl (2.5 MB)
Collecting networkx>=2.6.2
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Collecting pyyaml
  Using cached PyYAML-6.0-cp39-cp39-win_amd64.whl (151 kB)
Collecting numpy>=1.18.0
  Using cached numpy-1.24.1-cp39-cp39-win_amd64.whl (14.9 MB)
Collecting llvmlite<0.40,>=0.39.0dev0
  Using cached llvmlite-0.39.1-cp39-cp39-win_amd64.whl (23.2 MB)
Collecting numpy>=1.18.0
  Using cached numpy-1.23.5-cp39-cp39-win_amd64.whl (14.7 MB)
Requirement already satisfied: setuptools in c:\users\h.zibaei\appdata\local\programs\python\python39\lib\site-packages (from numba->repast4py) (58.1.0)
Collecting typing-extensions
  Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)
Building wheels for collected packages: repast4py
  Building wheel for repast4py (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for repast4py (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [30 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\context.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\core.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\geometry.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\logging.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\network.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\parameters.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\random.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\schedule.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\space.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\util.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\value_layer.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\__init__.py -> build\lib.win-amd64-cpython-39\repast4py
      running build_ext
      building 'repast4py._core' extension
      creating build\temp.win-amd64-cpython-39
      creating build\temp.win-amd64-cpython-39\Release
      creating build\temp.win-amd64-cpython-39\Release\src
      creating build\temp.win-amd64-cpython-39\Release\src\repast4py
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\H.Zibaei\AppData\Local\Temp\pip-build-env-vr63vhus\overlay\Lib\site-packages\numpy\core\include -IC:\Users\H.Zibaei\AppData\Local\Temp\pip-build-env-vr63vhus\overlay\Lib\site-packages\mpi4py\include -IC:\Users\H.Zibaei\AppData\Local\Programs\Python\Python39\include -IC:\Users\H.Zibaei\AppData\Local\Programs\Python\Python39\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\cppwinrt" /EHsc /Tpsrc/repast4py/coremodule.cpp /Fobuild\temp.win-amd64-cpython-39\Release\src/repast4py/coremodule.obj -std=c++11
      cl : Command line warning D9002 : ignoring unknown option '-std=c++11'
      coremodule.cpp
      src/repast4py/coremodule.cpp(342): error C7556: cannot mix designated-initializers with non-designated-initializers
      src/repast4py/coremodule.cpp(343): error C7555: use of designated initializers requires at least '/std:c++20'
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.31.31103\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for repast4py
Failed to build repast4py
ERROR: Could not build wheels for repast4py, which is required to install pyproject.toml-based projects
</code>```

Update:
python 3.9.12
visual studio 2022
pip 22.3.1
wheel 0.38.4
install pyproject.toml

Body:
I want to install repast4py in windows 10, and I enter 'pip install repast4py' in cmd, but It displays errors
'src/repast4py/coremodule.cpp(342): error C7556: cannot mix designated-initializers with non-designated-initializers' and
'error C7555: use of designated initializers requires at least '/std:c++20',
After that I update my visual studio build tools to 2022, but yet It displays the same error. please help me. thanks

C:\Users\H.Zibaei>pip install repast4py
Collecting repast4py
  Using cached repast4py-1.0.5b1.tar.gz (79 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... done
Collecting torch
  Using cached torch-1.13.1-cp39-cp39-win_amd64.whl (162.5 MB)
Collecting Cython
  Using cached Cython-0.29.32-py2.py3-none-any.whl (986 kB)
Requirement already satisfied: mpi4py in c:\users\h.zibaei\appdata\local\programs\python\python39\lib\site-packages (from repast4py) (3.1.4)
Collecting numba
  Using cached numba-0.56.4-cp39-cp39-win_amd64.whl (2.5 MB)
Collecting networkx>=2.6.2
  Using cached networkx-2.8.8-py3-none-any.whl (2.0 MB)
Collecting pyyaml
  Using cached PyYAML-6.0-cp39-cp39-win_amd64.whl (151 kB)
Collecting numpy>=1.18.0
  Using cached numpy-1.24.1-cp39-cp39-win_amd64.whl (14.9 MB)
Collecting llvmlite<0.40,>=0.39.0dev0
  Using cached llvmlite-0.39.1-cp39-cp39-win_amd64.whl (23.2 MB)
Collecting numpy>=1.18.0
  Using cached numpy-1.23.5-cp39-cp39-win_amd64.whl (14.7 MB)
Requirement already satisfied: setuptools in c:\users\h.zibaei\appdata\local\programs\python\python39\lib\site-packages (from numba->repast4py) (58.1.0)
Collecting typing-extensions
  Using cached typing_extensions-4.4.0-py3-none-any.whl (26 kB)
Building wheels for collected packages: repast4py
  Building wheel for repast4py (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for repast4py (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [30 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-39
      creating build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\context.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\core.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\geometry.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\logging.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\network.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\parameters.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\random.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\schedule.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\space.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\util.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\value_layer.py -> build\lib.win-amd64-cpython-39\repast4py
      copying src\repast4py\__init__.py -> build\lib.win-amd64-cpython-39\repast4py
      running build_ext
      building 'repast4py._core' extension
      creating build\temp.win-amd64-cpython-39
      creating build\temp.win-amd64-cpython-39\Release
      creating build\temp.win-amd64-cpython-39\Release\src
      creating build\temp.win-amd64-cpython-39\Release\src\repast4py
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Users\H.Zibaei\AppData\Local\Temp\pip-build-env-vr63vhus\overlay\Lib\site-packages\numpy\core\include -IC:\Users\H.Zibaei\AppData\Local\Temp\pip-build-env-vr63vhus\overlay\Lib\site-packages\mpi4py\include -IC:\Users\H.Zibaei\AppData\Local\Programs\Python\Python39\include -IC:\Users\H.Zibaei\AppData\Local\Programs\Python\Python39\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.31.31103\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.20348.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.20348.0\\cppwinrt" /EHsc /Tpsrc/repast4py/coremodule.cpp /Fobuild\temp.win-amd64-cpython-39\Release\src/repast4py/coremodule.obj -std=c++11
      cl : Command line warning D9002 : ignoring unknown option '-std=c++11'
      coremodule.cpp
      src/repast4py/coremodule.cpp(342): error C7556: cannot mix designated-initializers with non-designated-initializers
      src/repast4py/coremodule.cpp(343): error C7555: use of designated initializers requires at least '/std:c++20'
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.31.31103\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for repast4py
Failed to build repast4py
ERROR: Could not build wheels for repast4py, which is required to install pyproject.toml-based projects

Update:
python 3.9.12
visual studio 2022
pip 22.3.1
wheel 0.38.4
install pyproject.toml


问:
Undefined is not an object evaluating navigator.clipboard.writeText happens on only one web server, and not on my local machine
I have been uploading some web apps that I made onto a new web server, and got to an issue in testing one. When I click a button that is supposed to copy a string of text to my clipboard, the browser gives me an error:

```<code>TypeError: navigator.clipboard is undefined
</code>```

When I try running the file on my local machine and on another web server, it works just fine. I have tried using multiple browsers and re-uploading the files, but there wasn't a change. It can be found at http://citation.davidrk.tech/ and is found after clicking the "Copy to Clipboard" Button. Any help would be great. I am using bluehost to host my website.

Body:
I have been uploading some web apps that I made onto a new web server, and got to an issue in testing one. When I click a button that is supposed to copy a string of text to my clipboard, the browser gives me an error:

TypeError: navigator.clipboard is undefined

When I try running the file on my local machine and on another web server, it works just fine. I have tried using multiple browsers and re-uploading the files, but there wasn't a change. It can be found at http://citation.davidrk.tech/ and is found after clicking the "Copy to Clipboard" Button. Any help would be great. I am using bluehost to host my website.


问:
Why does Boto3 download a file with another name?
I'm working on a project that works when run manually, but putting the code in a docker container changes my file extension.
The code with which I am downloading the file is:

```<code>def download_file(filename):
    try:
        s3 = boto3.client('s3')
        s3.download_file(os.getenv('BUCKET_NAME'), filename,os.getenv('LOCAL_FILE_NAME'))
        return True, "File downloaded successfully"
    except Exception as e:
         return False, str(e)
</code>```

Within the local variables I define the folder where the file will be stored:

```<code>LOCAL_FILE_NAME = tmp/file_to_process.pdf
</code>```

When doing the test, download the file with the following extension

```<code>tmp/file_to_process.pdf.50Cansdf
tmp/file_to_process.pdf.B0CnBB1d
tmp/file_to_process.pdf.A0CaDB1d
</code>```

Body:
I'm working on a project that works when run manually, but putting the code in a docker container changes my file extension.
The code with which I am downloading the file is:

def download_file(filename):
    try:
        s3 = boto3.client('s3')
        s3.download_file(os.getenv('BUCKET_NAME'), filename,os.getenv('LOCAL_FILE_NAME'))
        return True, "File downloaded successfully"
    except Exception as e:
         return False, str(e)

Within the local variables I define the folder where the file will be stored:

LOCAL_FILE_NAME = tmp/file_to_process.pdf

When doing the test, download the file with the following extension

tmp/file_to_process.pdf.50Cansdf
tmp/file_to_process.pdf.B0CnBB1d
tmp/file_to_process.pdf.A0CaDB1d


问:
How do I make a search filter using a category array? NFT smart contract fullstack
bit of a newbie at js here and I'm creating a search filter for my NFT marketplace platform.

I've successfully been able to create a basic input function to search for the name of the item uploaded but because the category of the item is an array, I'm finding difficulty creating checkbox inputs to filter the search results by category.

Here's the piece my code with the search by name function:

```<code>export function Results() {
  const { fetchNFTs, setError, currentAccount } = useContext(
    NFTMarketplaceContext
  );
  const [nfts, setNfts] = useState([]);
  const [nftsCopy, setNftsCopy] = useState([]);

  useEffect(() => {
    try {
      // if (currentAccount) {
      fetchNFTs().then((items) => {
        setNfts(items.reverse());
        setNftsCopy(items);
        console.log(nfts);
      });
      // }
    } catch (error) {
      setError("Please reload the browser", error);
    }
  }, []);

  const onHandleSearch = (value) => {
    const filteredNFTS = nfts.filter(({ name }) =>
      name.toLowerCase().includes(value.toLowerCase())
    );

    if (filteredNFTS.length === 0) {
      setNfts(nftsCopy);
    } else {
      setNfts(filteredNFTS);
    }
  };

  const onClearSearch = () => {
    if (nfts.length && nftsCopy.length) {
      setNfts(nftsCopy);
    }
  };

return {
  <SearchBar
      onHandleSearch={onHandleSearch}
      onClearSearch={onClearSearch}
    />
}
</code>```

And my search bar:

```<code>import React, { useEffect, useState } from "react";

const SearchBar = ({ onHandleSearch, onClearSearch }) => {
  const [search, setSearch] = useState("");
  const [searchItem, setSearchItem] = useState(search);

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchItem), 1000);
    return () => clearTimeout(timer);
  }, [searchItem]);

  useEffect(() => {
    if (search) {
      onHandleSearch(search);
    } else {
      onClearSearch();
    }
  }, [search]);
  return (
    <div className="SearchBar">
    <div className="section-filters-bar-actions">
      <form className="form">
        <div className="form-item split">
          <div className="form-input small">
            <label for="items-search">Search Items</label>
            <input type="text" id="items-search" style={{width:'370px'}}
            onChange={(e) => setSearchItem(e.target.value)}
            value={searchItem}/>
          </div>
        </div>
      </form>
    </div>
    </div>
  );
}

export default SearchBar;

</code>```

And finally the array in the upload page / function:

```<code>const UloadNFT = ({ uploadToIPFS, createNFT }) => {
  const [price, setPrice] = useState("");
  const [active, setActive] = useState(0);
  const [name, setName] = useState("");
  const [website, setWebsite] = useState("");
  const [description, setDescription] = useState("");
  const [royalties, setRoyalties] = useState("");
  const [fileSize, setFileSize] = useState("");
  const [category, setCategory] = useState(0);
  const [properties, setProperties] = useState("");
  const [image, setImage] = useState(null);

  const router = useRouter();

  const categoryArry = [
    {
      category: "AI Generated",
    },
    {
      category: "Artwork",
    },
    {
      category: "Audio",
    },
    {
      category: "Collectible",
    },
    {
      category: "Customization",
    },
    {
      category: "Digital Land",
    },
    {
      category: "Gaming",
    },
    {
      category: "Utility",
    },
  ];

  return (
    <div className="UloadNFT" style={{height:'1350px'}}>

  <div style={{display:'inline-grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '0rem'}}>
  <div className={Style.upload_box} style={{backgroundColor:'var(--primary-white)',padding:'30px 30px 30px 30px'}}>
    <div className={formStyle.Form_box_input}>
      <label htmlFor="nft">Item Name</label>
      <input
        type="text"
        placeholder="Name your token..."
        className={formStyle.Form_box_input_userName}
        onChange={(e) => setName(e.target.value)}
        style={{border:'1px solid #202020', backgroundColor:'transparent'}}
      />
    </div>

    // category upload input area
    <div className={formStyle.Form_box_input}>
      <label htmlFor="name">Choose Category</label>
      <p className={Style.upload_box_input_para}>
        Choose a specific category for your token
      </p>
      <br></br>
      <div className={Style.upload_box_slider_div}>
        {categoryArry.map((el, i) => (
          <div
            className={`${Style.upload_box_slider} ${
              active == i + 1 ? Style.active : ""
            }`}
            key={i + 1}
            onClick={() => (setActive(i + 1), setCategory(el.category))}
          >
            <p style={{textAlign:'center'}}>{el.category} </p>
          </div>
        ))}
      </div>
    </div>

      <Button
        btnName="Create Token"
        handleClick={async () =>
          createNFT(
            name,
            price,
            image,
            description,
            router,
            category,
            // royalties,
            // fileSize,
            website
            // properties
          )
        }
      />
   </div>
 </div>

</code>```

I know it's a lot here since I'm passing the value through multiple functions but I've tried to narrow it down as much as possible. Also the smart contract is working perfectly fine and holds the category variable. I'm sure I just need to call it properly now but it's an array.

Please help!

I tried to replace { name } and name.toLowerCase() with category just to test it but it said 'category.toLowerCase() is undefined'.

Then I tried category.toString().toLowerCase() but it gave the same result.

Body:
bit of a newbie at js here and I'm creating a search filter for my NFT marketplace platform.

I've successfully been able to create a basic input function to search for the name of the item uploaded but because the category of the item is an array, I'm finding difficulty creating checkbox inputs to filter the search results by category.

Here's the piece my code with the search by name function:

export function Results() {
  const { fetchNFTs, setError, currentAccount } = useContext(
    NFTMarketplaceContext
  );
  const [nfts, setNfts] = useState([]);
  const [nftsCopy, setNftsCopy] = useState([]);

  useEffect(() => {
    try {
      // if (currentAccount) {
      fetchNFTs().then((items) => {
        setNfts(items.reverse());
        setNftsCopy(items);
        console.log(nfts);
      });
      // }
    } catch (error) {
      setError("Please reload the browser", error);
    }
  }, []);

  const onHandleSearch = (value) => {
    const filteredNFTS = nfts.filter(({ name }) =>
      name.toLowerCase().includes(value.toLowerCase())
    );

    if (filteredNFTS.length === 0) {
      setNfts(nftsCopy);
    } else {
      setNfts(filteredNFTS);
    }
  };

  const onClearSearch = () => {
    if (nfts.length && nftsCopy.length) {
      setNfts(nftsCopy);
    }
  };

return {
  <SearchBar
      onHandleSearch={onHandleSearch}
      onClearSearch={onClearSearch}
    />
}

And my search bar:

import React, { useEffect, useState } from "react";

const SearchBar = ({ onHandleSearch, onClearSearch }) => {
  const [search, setSearch] = useState("");
  const [searchItem, setSearchItem] = useState(search);

  useEffect(() => {
    const timer = setTimeout(() => setSearch(searchItem), 1000);
    return () => clearTimeout(timer);
  }, [searchItem]);

  useEffect(() => {
    if (search) {
      onHandleSearch(search);
    } else {
      onClearSearch();
    }
  }, [search]);
  return (

      <form className="form">

            Search Items
            <input type="text" id="items-search" style={{width:'370px'}}
            onChange={(e) => setSearchItem(e.target.value)}
            value={searchItem}/>

      </form>

  );
}

export default SearchBar;

And finally the array in the upload page / function:

const UloadNFT = ({ uploadToIPFS, createNFT }) => {
  const [price, setPrice] = useState("");
  const [active, setActive] = useState(0);
  const [name, setName] = useState("");
  const [website, setWebsite] = useState("");
  const [description, setDescription] = useState("");
  const [royalties, setRoyalties] = useState("");
  const [fileSize, setFileSize] = useState("");
  const [category, setCategory] = useState(0);
  const [properties, setProperties] = useState("");
  const [image, setImage] = useState(null);

  const router = useRouter();

  const categoryArry = [
    {
      category: "AI Generated",
    },
    {
      category: "Artwork",
    },
    {
      category: "Audio",
    },
    {
      category: "Collectible",
    },
    {
      category: "Customization",
    },
    {
      category: "Digital Land",
    },
    {
      category: "Gaming",
    },
    {
      category: "Utility",
    },
  ];

  return (

      Item Name
      <input
        type="text"
        placeholder="Name your token..."
        className={formStyle.Form_box_input_userName}
        onChange={(e) => setName(e.target.value)}
        style={{border:'1px solid #202020', backgroundColor:'transparent'}}
      />

    // category upload input area

      Choose Category

        Choose a specific category for your token

        {categoryArry.map((el, i) => (

 (setActive(i + 1), setCategory(el.category))}
          >

{el.category}

        ))}

      <Button
        btnName="Create Token"
        handleClick={async () =>
          createNFT(
            name,
            price,
            image,
            description,
            router,
            category,
            // royalties,
            // fileSize,
            website
            // properties
          )
        }
      />

I know it's a lot here since I'm passing the value through multiple functions but I've tried to narrow it down as much as possible. Also the smart contract is working perfectly fine and holds the category variable. I'm sure I just need to call it properly now but it's an array.

Please help!

I tried to replace { name } and name.toLowerCase() with category just to test it but it said 'category.toLowerCase() is undefined'.

Then I tried category.toString().toLowerCase() but it gave the same result.


问:
Subentity not saved, using a generic repository
I'm having problems saving a subentity. I have an Invoice object with InvoiceDetails as a subentity. The Invoice is saved, the InvoiceDetails not.

Can anyone say what I forgot or what I'm doing wrong? Many thanks in advance. :-)

I'm using a generic repository, using this method (BaseModel is a class with just an ID).

```<code> public T Add<T>(T entity) where T : BaseModel
        {
            _dbContext.Set<T>().Add(entity);
            _dbContext.SaveChanges();

            return entity;
        }
</code>```

The Invoice and InvoiceDetail look like this.

```<code>public class InvoiceDetail : BaseModel
{
    [Required]
    public string Description { get; set; } = string.Empty;

    [Required]
    public int Quantity { get; set; }

    [Required]
    public decimal Price { get; set; }

    [Required]
    public decimal VAT { get; set; }

    public int InvoiceID { get; set; }

    public virtual Invoice Invoice { get; set; }
</code>```
```<code>public class Invoice : BaseModel
{
    [Required]
    public InvoiceType Type { get; set; }

    [Required]
    public string InvoiceNumber { get; set; }

    [Required]
    public string Info { get; set; }

    [Required]
    public string PaymentTerm { get; set; }

    [Required]
    public DateTime CreationDate { get; set; }

    public string Remarks { get; set; } = string. Empty;

    public int CustomerId { get; set; }

    public virtual Customer Customer { get; set; } = new Customer();

    public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }
</code>```

I'm using FluentApi and I'm using seperated mapping classes.

```<code> public InvoiceMap(EntityTypeBuilder<Invoice> entityBuilder)
        {
            entityBuilder.ToTable("Invoices");

            entityBuilder.HasKey(x => x.Id);

            entityBuilder.Navigation(c => c.InvoiceDetails).AutoInclude();
            entityBuilder.Navigation(c => c.Customer).AutoInclude();

            entityBuilder.Property(x => x.Id).HasColumnOrder(1);

            entityBuilder.HasOne(f => f.Customer)
                         .WithMany(k => k.Invoices)
                         .HasForeignKey(f => f.CustomerId);

            entityBuilder.Property(x => x.CustomerId).HasColumnOrder(2);

            entityBuilder.Property(x => x.InvoiceNumber).IsRequired().HasColumnOrder(3);
            entityBuilder.Property(x => x.Info).HasColumnOrder(4);
            entityBuilder.Property(x => x.PaymentTerm).HasColumnOrder(5);
            entityBuilder.Property(x => x.CreationDate).IsRequired().HasColumnOrder(6);
            entityBuilder.Property(x => x.Remarks).IsRequired().HasColumnOrder(7);

        }
</code>```
```<code> public InvoiceDetailMap(EntityTypeBuilder<InvoiceDetail> entityBuilder)
        {
            entityBuilder.ToTable("InvoiceDetails");

            entityBuilder.HasKey(x => x.Id);

            entityBuilder.Property(x => x.Id).HasColumnOrder(1);

            entityBuilder.HasOne(f => f.Invoice)
                         .WithMany(f => f.InvoiceDetails)
                         .HasForeignKey(f => f.InvoiceID);

            entityBuilder.Property(x => x.InvoiceID).HasColumnOrder(2);

            entityBuilder.Property(x => x.Description).IsRequired().HasColumnOrder(3);
            entityBuilder.Property(x => x.Quantity).IsRequired().HasColumnOrder(4);
            entityBuilder.Property(x => x.Price).IsRequired().HasColumnOrder(5);
            entityBuilder.Property(x => x.VAT).IsRequired().HasColumnOrder(6);

        }
</code>```

I searched on the internet for a solution, but didn't find a solution.

Body:
I'm having problems saving a subentity. I have an Invoice object with InvoiceDetails as a subentity. The Invoice is saved, the InvoiceDetails not.

Can anyone say what I forgot or what I'm doing wrong? Many thanks in advance. :-)

I'm using a generic repository, using this method (BaseModel is a class with just an ID).

 public T Add<T>(T entity) where T : BaseModel
        {
            _dbContext.Set<T>().Add(entity);
            _dbContext.SaveChanges();

            return entity;
        }

The Invoice and InvoiceDetail look like this.

public class InvoiceDetail : BaseModel
{
    [Required]
    public string Description { get; set; } = string.Empty;

    [Required]
    public int Quantity { get; set; }

    [Required]
    public decimal Price { get; set; }

    [Required]
    public decimal VAT { get; set; }

    public int InvoiceID { get; set; }

    public virtual Invoice Invoice { get; set; }

public class Invoice : BaseModel
{
    [Required]
    public InvoiceType Type { get; set; }

    [Required]
    public string InvoiceNumber { get; set; }

    [Required]
    public string Info { get; set; }

    [Required]
    public string PaymentTerm { get; set; }

    [Required]
    public DateTime CreationDate { get; set; }

    public string Remarks { get; set; } = string. Empty;

    public int CustomerId { get; set; }

    public virtual Customer Customer { get; set; } = new Customer();

    public virtual ICollection<InvoiceDetail> InvoiceDetails { get; set; }

I'm using FluentApi and I'm using seperated mapping classes.

 public InvoiceMap(EntityTypeBuilder<Invoice> entityBuilder)
        {
            entityBuilder.ToTable("Invoices");

            entityBuilder.HasKey(x => x.Id);

            entityBuilder.Navigation(c => c.InvoiceDetails).AutoInclude();
            entityBuilder.Navigation(c => c.Customer).AutoInclude();

            entityBuilder.Property(x => x.Id).HasColumnOrder(1);

            entityBuilder.HasOne(f => f.Customer)
                         .WithMany(k => k.Invoices)
                         .HasForeignKey(f => f.CustomerId);

            entityBuilder.Property(x => x.CustomerId).HasColumnOrder(2);

            entityBuilder.Property(x => x.InvoiceNumber).IsRequired().HasColumnOrder(3);
            entityBuilder.Property(x => x.Info).HasColumnOrder(4);
            entityBuilder.Property(x => x.PaymentTerm).HasColumnOrder(5);
            entityBuilder.Property(x => x.CreationDate).IsRequired().HasColumnOrder(6);
            entityBuilder.Property(x => x.Remarks).IsRequired().HasColumnOrder(7);

        }

 public InvoiceDetailMap(EntityTypeBuilder<InvoiceDetail> entityBuilder)
        {
            entityBuilder.ToTable("InvoiceDetails");

            entityBuilder.HasKey(x => x.Id);

            entityBuilder.Property(x => x.Id).HasColumnOrder(1);

            entityBuilder.HasOne(f => f.Invoice)
                         .WithMany(f => f.InvoiceDetails)
                         .HasForeignKey(f => f.InvoiceID);

            entityBuilder.Property(x => x.InvoiceID).HasColumnOrder(2);

            entityBuilder.Property(x => x.Description).IsRequired().HasColumnOrder(3);
            entityBuilder.Property(x => x.Quantity).IsRequired().HasColumnOrder(4);
            entityBuilder.Property(x => x.Price).IsRequired().HasColumnOrder(5);
            entityBuilder.Property(x => x.VAT).IsRequired().HasColumnOrder(6);

        }

I searched on the internet for a solution, but didn't find a solution.


问:
Pyomo: how can I specify one particular Gurobi floating license (token server client license) should be used when I have multiple floating licenses?
I have three gurobi floating licenses for my project on my laptop, and each license contains different TokenServer and Port information. Depending on the situation, I need to specify which license I should use. The Gurobi Python API allows the user to specify which floating license to use when solving an optimization model by using the following way to set up the environment for the model:

"With gurobipy.Env(connectionparams={"TokenServer": "localhost", "TSPORT":port_number}) as env:"

Can anyone please inform me how to implement this in Pyomo? Any help on this issue will be greatly appreciated.

I read Pyomo document, but cannot find similar commands to ones provided by Gurobi Python API