Adding and removing elements from a set Pyomo - pyomo

I wan't to create a free Set that will be initialized through a mutable parameter that is changed throughout my program.I wan't the set to contain only one value the value of the parameter each time is changed,but i can't add and remove the values from the set.If it was a list it could be done like so:
model.iter=RangeSet(0,1000)
model.ir=[]
model.count1=Param(mutable=True)
def solve_function(model,instance):
instance=model.create_instance()
for i in instance.iter:
if i==value(instance.count):
instance.ir.append(i)
else:
pass
results= opt.solve(instance)
instance.solutions.load_from(results)
.#some code
.
.
.
instance.ir=[]
Can anybody tell me how to do the same thing with a Set() object?

Related

how to creat multiple empty dictionaries from names in a list in python?

I need to create multiple dictionaries from a list. if list is ['dic1','dict2'], i want to creat two different dictionaries such as sample_dic1 and sample_dic2.
if I don't use loops, I'll just type:
sample_dic1=dict();sample_dic2=dict()
my question is how to do it in a loop from a name list.
I tried to put the list in loop while each value of the loop equal to dict().
However, it does not assign the left-hand side to dict().
di_list=['dic1','dict2']
for (a) in di_list:
'sample_{}'.format(a)=dict()
I also Tried this. it doesn't give any error. but doesn't work neigher
temp=dict()
di_list=['dic1','dict2']
for (a) in di_list:
temp[a]='sample_{}'.format(a)
temp[a]=dict()
so I want to creat these two dictrionaries from di_list values. with 'sample_{}'.format(a) I can creat my desired name, But binding it to dict() doesn't work. i.e,. sample_{}'.format(a)=dict()
I think you're mixing two things: variables names and values. Variable names do not have a real effective meaning and if you consistently change their names the program remains the same (in fact, it happens in most languages under the hood anyway).
Here is an option to refer to an arbitrary number of values by name, using a dictionary (name->value):
temp=dict()
di_list=['dic1','dict2']
for (a) in di_list:
temp['sample_{}'.format(a)] = dict()
Now you can verify the values are in fact there:
assert temp['sample_dic1'] == {} # True
assert temp['sample_dict2'] == {} # True

pass kwargs and default values to ordered list

Using python 2.7, I have been researching into using keyword arguments to pass a function that inserts a new tuple into a list.
My goal: have a function that takes one required argument, and n number of arguments that then get inserted into a tuple at specific positions and have a default value if nothing was passed.
Here is what I have so far:
def add_tagging_log_row(key, **time_stamp):
tagging_log_rows.insert(len(tagging_log_rows), (key, time_stamp.get('is_processed'), time_stamp.get('is_processed')))
add_tagging_log_row('zzz', is_processed=datetime.datetime.now(), is_audited=datetime.datetime.now())
Here is a sample of tagging_low_rows list I am building with all values in the tuple populated:
[('key1', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now()), ('key2', datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now(), datetime.datetime.now())]
here is the order of the items in each tuple in the list:
key | is_processed | is_archived | is_error | is_audited
The problem is when calling the function add_tagging_log_row(), I will always pass a 'key' but might or might not pass the other timestamp fields to the tuple when it is inserted into the list. I need these fields to be empty strings ('').
Is using **kwargs the right way to approach this problem?
Yes, using kwargs works. You would need some exception handling inside your function though. kwargs passed in as a dictionary. You can check if a given timestamp exists in the dictionary and use an empty string if it doesn't. Try doing something like this inside the function:
timestamps_order = ['is_processed', 'is_archived', 'is_error', 'is_audited']
required_tuple = tuple([key] + [time_stamp[k] if k in time_stamp else "" for k in timestamps_order])
On a side note - please consider switching to Python 3. Python 2.7 is at the end of life and won't receive any future support. Most libraries have stopped supporting it.

Converting "Textarea" object from iPython wigdet to a list or iterable array

I have created several Textarea widgets in Jupyter/Python in order to capture some string inputs.
In the highlighted in yellow that you can see below, the idea is that the user puts a list of numbers here (copied from Excel) and later I need to convert this text into a list or an array that contains these numbers (an iterable object). I have no idea how to do this. See:
When I print the type of this object that is called "plus" I get this:
print(type(plus))
<class 'ipywidgets.widgets.widget_string.Textarea'>
But, I am expecting to have something like this:
plus = [454, 555]
Can I bounce some ideas off you to get this?
Thanks a lot!!!
If you have an ipywidget in general, you can observe its change and get its value as following.
foo = widgets.Textarea()
# to get the value
foo.value
# to do something on value change
def bar(change):
print(change.new)
foo.observe(bar, names=['value'])
You will then have to format the string you get from the products value, but that shouldn't be too difficult.
Hope this helps

grails controller: access to parameter that has a list of elements

I need to access to items stored in a parameter that represents selected elements in a multiselect. I pass selected items from gsp to controller with the following code into the remoteFunction:
params: '\'receiptItemsSelected=\' + jQuery(this).val()'
Now, following the code found in discussion here, I use the closure to get each value, but if I perform a multiselect, the size of receiptItemsSelected is always 1, but value is, for example, 1,2. To get values as a list I've done the following in the controller
params.list("receiptItemsSelected")
but it does not give me two elements if I select two items in the multiselect, but always one element.
The question is: if I select two elements, how can I get each element and use it in the controller? And how can I have that elemnts as Long and not as String?
Thanks
If you're parameters are being passed with string representation of a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1,2,3
You have to split the value using normal Groovy string manipulation and perform the type conversion yourself:
def receiptsAsLongs = params.receiptItemsSelected.split(',')*.toLong()
If your parameters are passed with the convention of repeated parameters makes a list, e.g.:
http://yoursite.com/?receiptItemsSelected=1&receiptItemsSelected=2
Then grails can convert this to a list for you using params.list(), but you must do the final String to Long conversion:
def receiptsAsLongs = params.list('receiptItemsSelected')*.toLong()
params.list() is intended for multi-valued parameters, i.e. it will work if you have
receiptItemsSelected=1&receiptItemsSelected=2
You may have more luck using serialize() rather than val() to build the request body.

filter output of subprocess.check_output

I'm trying to match values of a list to a regex pattern. If the particular value within the list matches, I'll append it to a different list of dicts. If the above mentioned value does not match, I want to remove the value from the list.
import subprocess
def list_installed():
rawlist = subprocess.check_output(['yum', 'list', 'installed']).splitlines()
#print rawlist
for each_item in rawlist:
if "[\w86]" or \
"noarch" in each_item:
print each_item #additional stuff here to append list of dicts
#i haven't done the appending part yet
#the list of dict's will be returned at end of this funct
else:
remove(each_item)
list_installed()
The end goal is to eventually be able to do something similar to:
nifty_module.tellme(installed_packages[3]['version'])
nifty_module.dosomething(installed_packages[6])
Note to gnu/linux users going wtf:
This will eventually grow into a larger sysadmin frontend.
Despite the lack of an actual question in your post, I'll make a couple of comments.
You have a problem here:
if "[\w86]" or "noarch" in each_item:
It's not interpreted the way you think of it and it always evaluates to True. You probably need
if "[\w86]" in each_item or "noarch" in each_item:
Also, I'm not sure what you are doing, but in case you expect that Python will do regex matching here: it won't. If you need that, look at re module.
remove(each_item)
I don't know how it's implemented, but it probably won't work if you expect it to remove the element from rawlist: remove won't be able to actually access the list defined inside list_installed. I'd advise to use rawlist.remove(each_item) instead, but not in this case, because you are iterating over rawlist. You need to re-think the procedure a little (create another list and append needed elements to it instead of removing, for example).