Is there a way to have a big list for autocompletion discord.py? - discord

For this autocompletion code -
async def drink_autocompletion(
interaction: discord.Interaction,
current: str
) -> typing.List[app_commands.Choice[str]]:
data = []
for drink_choice in ['beer', 'milk', 'tea', 'coffee', 'juice']:
if current.lower() in drink_choice.lower():
data.append(app_commands.Choice(name=drink_choice, value=drink_choice))
return data
is there a way so you could replace the 'beer', 'milk', 'tea', 'coffee', 'juice' with another file full of items? For example you could have another document will more items could you import it and put it there instead of having a huge list?

Yeah, I don't see why that wouldn't be possible. You just need to return a list of some sort, how you get it there is irrelevant. You can import whatever you want, perform database queries, make API calls, open files, access attributes of class instances, ... Save your list however & wherever you want.
Just keep in mind that this gets triggered every time someone types a character, so if it's really big you may want to just cache it upon startup.

Related

update data in Array of Structs with data in other Array of Struct

Let's say I have struct :
struct Planet {
var id : UUID
var name: String
...
}
I have an array of such structs which is constructed from data fetched from a database. I use this for a form in a browser where the user can:
edit the fields (eg change the name of Planet)
create one or more new Planets
at this time the user may not delete a Planet but it would be great if the solution would support that too
When the form is submitted I get an array with those structures (the order is also not the same as the original). What is the best/most efficient way to do update the data in the original array with the data from the second.
My current idea is:
map the original array to a dictionary with key= id, value= aPlanetStructure
loop over the second array (with the edited data) and if that 'key' can be retrieved in the dictionary (=data from first array)-> update the struct there, if not create an additional planet in the first array.
I'm not sure if this is a good approach, it seems like there could be a more efficient way (but I can't think of it). It would also not support deleting a Planet
In general, if you can separate out the elements of the array by action, you'll make your life easier.
For example:
var created= [Planet]()
var updated= [Planet]()
var deleted = [Planet]()
In your UI layer, when an edit is made, add the edited planet to the
updated array, when a planet is deleted, add it to the deleted array, etc.
Submit all 3 arrays with your form.
Loop over the results of each and pass too your create, update, and delete methods that access your database.
That will require restructuring your form code a bit, but... in general it's easier in your UI layer to tell whether someone is doing a create, an update, or a delete, than it is to mush them all together and try to figure it out after the fact by doing comparisons.

FireStore and maps/arrays, document-list to array in Kotlin

I've finally started to understand a lot of info regarding FireStore, but I'm wondering if I can get some assistance.
If I had a setup similar to or like this:
          races
                Android
                      name: Android
                      size: medium
                       stats          <---- this is the map
                                str: 10
                                sex: 12.... (more values)
How would I parse this? I am looking to make specific TextViews apply values found in the database so that I can simply update the database and my app will populate those values so that hard coding and code updating won't be nearly as troublesome in the future.
I currently use something like this:
val androidRef = db.collection("races").document("Android")
androidRef.get().addOnSuccessListener { document ->
if (document != null) {
oneOfTheTextViews.text = document.getString("str")
} else {
}
The issue is currently I can only seem to access from collection (races) / document (android) / then a single field (I have "str" set as a single field, not part of a map or array)
What would the best practice be to do this? Should I not nest them at all? And if I can reference said nesting/mapping/array, what functions need to be called? (To be clear, I am not asking only whether or not it is possible - the reference guides and documents allude to such - but what property/class/method/etc needs to be called in order to access only one of those values or point to one of those values?).
Second question: Is there a way to get a list of document names? If I have several races, and simply want to make a spinner or recycler view based on document names as part of a collection, can I read that to the app?
What would the best practice be to do this?
If you want to get the value of your str property which is nested within your stats map, please change the following line of code:
oneOfTheTextViews.text = document.getString("str")
to
oneOfTheTextViews.text = document.getString("stats.str")
If your str property is a number and not a String, then instead of the above line of code please use this one:
oneOfTheTextViews.text = document.getLong("stats.str")
Should I not nest them at all?
No, you can nest as many properties as you want within a Map.
Is there a way to get a list of document names?
Yes, simply iterate the collection and get the document ids using getId() function.

Redux + Reselect: Preventing selector recalculation when GPS data updates

Recently, I've been working on a very large application using React+Redux with Reselect to memoize data and prevent unnecessary re-renders, and I've hit a specific problem that I can't seem to get past.
In Redux state, I am storing a very large amount of data as an object indexed by id. These objects all have a property on them (let's call it gps) that updates with realtime gps coordinates.
This data is being used in two ways. The first is on a map, where the GPS data is relevant. The second is in the UI, where the GPS data is not relevant. Any time the GPS data is updated on any of the objects, that object is streamed in and replaced in the Redux store, which updates the reference of that object in my selector.
Example Redux Store:
data: {
dogs: {
1: {id: 1, name: "name1", gps: [123, 234]},
2: {id: 2, name: "name2", gps: [123, 234]},
3: {id: 3, name: "name3", gps: [123, 234]},
4: {id: 4, name: "name4", gps: [123, 234]}
}
}
The data in, for example, state.dogs[1].gps might updated 3 to 5 times per second. This can occur in any of the objects in state.data.dogs.
Selectors are written as follows:
const dogDataSelector = state => state.data.dogs;
const animalsSelector = createSelector(
dogDataSelector,
(dogs) => {
return Object.keys(dogs).map(id => {
return dogs[id];
})
}
)
Now, this code works correctly when I want all the dogs, as they update, GPS included.
What I can't seem to figure out would be how to write a selector specifically for the UI that excludes the GPS updates. 99 times out of 100, when a dog updates, it is the GPS updating. The UI doesn't care about the GPS at all, but due to that, the selector sends new data forward which causes the UI to rerender.
I know it is possible to write a new stream that only pushes changes from the DB if the id or name of a dog changes, but this is a solution I am hoping to stay away from, as it will cause a lot of the same data to be stored multiple times in the store.
I have tried the following:
creating a selector that returns a pared-down version of the dogs, with only the id and the name, stored in an object by keys. This selector is used as an input-selector later, but still causes unnecessary selector returns.
creating a selector that only returns an array of dog ids, and passing this to the UI. A deep equality check is used to prevent re-renders, and the array of ids is used to pluck specific dog objects from state. This is not an ideal solution and seems bad.
If anyone needs any more information or clarification, don't hesitate to ask.
Update: One of the main reasons this is an issue is that any GPS update to any dog will cause the dogDataSelector to return a new reference. This will, in turn, cause animalsSelector fire an update and return a new value.
The standard approach for immutable data updates requires that if a nested field is updated, all of its ancestors in the tree should be copied and updated as well. In your example, an update to dog[3].gps would require new references for the gps array, dog[3], dogs, and data. Because of that, with this data structure, any updates to a gps field must result in new references all the way up the chain, and so the UI would see the new references and assume it needs to re-render.
A couple possible suggestions:
Write a selector that looks up a dog entry by its ID, strip out the gps field, and then do some kind of shallow equality check against the prior value to see if any if the non-gps fields have actually changed, so that a new "dog entry minus gps" object is only returned when one of those fields is different.
Store the GPS values in a separate lookup table keyed by ID, rather than nested inside the dog entries themselves, so that updates to a GPS array don't result in new dog entry references.
NOTE: THIS WON'T WORK FOR REASONS DETAILED IN THE COMMENTS
If you don't need the gps data, then surely you can just strip it off, and reselect will ignore it
Something like:
const dogDataSelector = state => state.data.dogs;
const animalsSelector = createSelector(
dogDataSelector,
(dogs) => {
return Object.keys(dogs).map(id => {
return dogs[id];
})
},
(dogsArray) => dogsArray.map(({id, name}) => ({id, name}))
)

react: Modifying a dictionary inside of a list

I have a state object like
this.state = {
newPerson: '',
people: [{name:'Eric', update: false} , {name:'Rick', update:false}, {name:'Yoni', update:false}]
};
I want to map over the list and be able to modify N object (ie - set status to be true).
I was thinking that I could map over the list of dictionaries by checking to see if the name matches N object's name, then "pop out" / delete the dictionary, modify it and then re-add it.
Is there a better way to do this? Especially following react's "functional" programming style by not modifying a object in space.
You can just map over your people list and modify (merge) only the one that matches the requirement (eg name in your example - it won't affect the original array). But the best way would be indexing your objects in collection and then using map function - you can have duplicated names at some point.
I know it's redux docs, but can help you with your problem - https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

How to pass a two dimensional list/array between groovy scripts in soap ui?

Problem statement: We need a way to pass a two dimensional list (or array) from one groovy script to other scripts ( to assert values from multiple DB2 tables in other scripts].
Some Background:
Step1: Based on our input xml payload we are capturing the list of nodes (and child elements) in a two dimensional list [][]. [Done]
Step2: Now we want to use the values from each of this list to assert with respect to values in DB2 tables [Also done, however keeping both step1 and step2 in same groovy script].
What we want is to to be able to pass the 2dimensional list from step1 in step2. Specially important since we have multiple tables and we dont want to either add all table steps in one big groovy script Or to duplicate step1 code in each Db2 validataion script.
We read about setting each element value from list at test case level and then reconstructing the array back but we are hesitating to use that method due to (varying &) huge size of list elements (in thousands). Question is: Are there any clean ways to achieve this?
Thanks!
As you are aware of the limitation of the earlier solution, which would only work (sharing of object between the groovy scripts) if the test case is run and does not work if individual steps are run.
Here I want to provide an approach which over comes that by using groovy's meta programming.
In script 1, have the below code:
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase
WsdlTestCase.metaClass.myList = [1,2,3,4,5]
In script 2, have the below code:
log.info "From script 2: ${context.testCase.myList}"
assert [1,2,3,4,5] == context.testCase.myList
The above even works if individual steps are run.
Hope this is helpful.
EDIT: come to understand that user required to update the list repeatedly and with metaClass user couldn't update the list. Here is the alternative:
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase
WsdlTestCase.metaClass.myObject = new Expando(myList: [1,2,3,4,5])
log.info "list initialized: ${context.testCase.myObject.myList}"
WsdlTestCase.metaClass.myObject = new Expando(myList: [1,2,3,4,5,6,7])
log.info "list updated: ${context.testCase.myObject.myList}"
You can use context
That's real working Groovy Script steps.
step1:
def array = ['Kyiv', 'Boryspil', 'Kharkiv', "L'Viv", "Odesa"]
context.setProperty('cities', array)
log.info( 'script1: '+array )
step2:
def array = context.getProperty('cities')
log.info( 'script2: '+array )
assert array.size()>0
Note:
If you run just one step, then there will be absolutely
independent context.
But if you run the whole testcase then there will be context shared
for the whole testcase.
You can use Run from here context menu in your test case window to run from exact step.

Resources