Two column unique constraint ActiveAndroid - activeandroid

How can I add two column unique constraint in ActiveAndroid?
I tried to add 2.sql and increase DB version, but it doesnt seem to be updated correctly (probably because I reinstall the app?). Anyway, is there are way to add some annotation on which I can apply two column unique constraint in ActiveAndroid ?
<meta-data android:name="AA_DB_NAME" android:value="Diggecard.db" />
<meta-data android:name="AA_DB_VERSION" android:value="2" />

Use the uniqueGroups property in the #Column annotation.
Make sure both columns have the same group name and they both must define the constraint.
#Column(uniqueGroups = {"groupName"}, onUniqueConflicts = {ConflictAction.FAIL})
#Column(uniqueGroups = {"groupName"}, onUniqueConflicts = {ConflictAction.FAIL})
There is actually a sample included here, in the source.

Related

How can I get Rails 5 to play nicely with a primary key that has a period in it?

I'm working with a database I have no control over, and cannot make alterations to. This database has a table called warehouse_items. Each warehouse item is uniquely identified by a primary key indicating the item id.
Unfortunately, that primary key attribute is named WAREHOUSE_ITEM.ID
(Note the obnoxious period between "item" and "id")
When I try to run a basic query, such as:
WarehouseItem.find('wh3453')
I get an Undefined Table error.
Fortunately, when looking at what Rails is attempting to do, the problem becomes obvious:
: SELECT "warehouse_items".* FROM "warehouse_items" WHERE "WAREHOUSE_ITEM"."ID" = $1 LIMIT $2
Because of the period in the attribute name, Rails is treating "WAREHOUSE_ITEM.ID" as a table/attribute combination, rather than an attribute name with a period in it.
When I run the following PSQL query by hand, I get exactly what I need:
SELECT "warehouse_items".* FROM "warehouse_items" WHERE "warehouse_items"."WAREHOUSE_ITEM.ID" = 'wh3453'
Why is Rails screwing this up, and how can I fix it?
EDIT:
Also worth noting: I've tried using self.primary_key to override the primary key to no avail.
I've tried both a string and a symbol, as in:
self.primary_key="WAREHOUSE_ITEM.ID"
and
self.primary_key=:"WAREHOUSE_ITEM.ID"
Neither one has worked...
Thanks for all the help, everyone!
A suggestion in the comments to use find_by_sql does work! However, I stumbled onto a different solution that works even better.
First, I aliased the annoying attribute name to something simple: id
alias_attribute :id, :"WAREHOUSE_ITEM.ID"
Notice that it's still a symbol, which is important for the next step.
I then overwrite the primary_key method with a custom function:
def self.primary_key
return "id"
end
Now, when I do WarehouseItem.find('wh3453'), Rails defaults to checking id, which is aliased to the correct symbol and it works as intended!!!

How to define constraint about consecutive periods in optaplanner

In my optaplanner project i have periods with fixed duration.
For some of them there is a medium constraint that they should be scheduled in a row, occupying for example 5 directly adjacent timeslots.
I want to use Java constraints streams but dont manage to define this constraint using the timeslot-pattern.
I know that this constraint can be defined using the time-grain-pattern as suggested by https://stackoverflow.com/a/30702865. I have done this and it works. But I want to compare timeslot-pattern to time-grain-pattern because the have different behaviour when it comes to escape local maxima. The problem with time-grain-pattern is that those 5 periods could also be sheduled in every possible partition of 5 (eg. as 2 + 2 + 1).
Has anyone a hint on how to define the constraint using timeslot-pattern?
You may want to try using the newly added ifExists() building block. Without knowing your actual domain model, I imagine the constraint to look like this:
private Constraint twoConsecutivePeriods(ConstraintFactory constraintFactory) {
return constraintFactory.from(Period.class)
.ifExists(Period.class, equal(Period::getDay, period -> period.getDay() + 1))
.penalize("2 consecutive periods", period -> ...);
}
Consequently, ifNotExists() may be used to achieve the opposite. We have examples of both in Traveling Tournament OptaPlanner example.
Please note that this API is only available since OptaPlanner 7.33.0.Final onward.
I solved the problem using ConstraintCollectors.toList() as follows:
factory.from(Period.class).groupBy(Period::getCourse, ConstraintCollectors.toList())
.penalize(id, score, (course,list)->dayDistributionPenalize(course,list));
and
public int dayDistributionPenalize(Course course, List<Period> list) {
var penalize = 0;
var dayCodes = dayCodesFromPeriodList(list);
for (var dayCode : dayCodes)
if (!getAllowedDayCodes(course).contains(dayCode))
penalize++;
return penalize;
}
Where getAllowedDayCodes() returns for example 0111110000, 0230000000 or 0005000000 etc. from a hash-map if a course has to have 5 consecutive periods.

IBM Optimization Studio OPL, why constraint is not respected?

Here is a description of the optimization problem I need to solve, but with a small twist. I need to add two constraints:
The first constraint: From each group we want to choose only one product, which means that we can't allow two products from the same group to be in the same basket(i.e. Product11 and Product12 should never be in the same basket )
The second constraint: In the user basket we only want products from the categories that the user is interested in. i.e if user is interested in the category 'Protein' he should never find in his basket a product from the category 'Carbs' nor 'Fat'.
Accordingly I have changed the OPL code products.mod:
{string} categories=...;
{string} groups[categories]=...;
{string} allGroups=union (c in categories) groups[c];
{string} products[allGroups]=...;
{string} allProducts=union (g in allGroups) products[g];
float prices[allProducts]=...;
int Uc[categories]=...;
float Ug[allGroups]=...;
float budget=...;
dvar boolean z[allProducts]; // product out or in ?
dexpr int xg[g in allGroups]=(sum(p in products[g]) z[p]);
dexpr int xc[c in categories]=(1<=sum(g in groups[c]) xg[g]);
maximize
sum(c in categories) Uc[c]*xc[c]+
sum(c in categories) sum(g in groups[c]) Uc[c]*Ug[g]*xg[g];
subject to
{
ctBudget:// first constraint
sum(p in allProducts) z[p]*prices[p]<=budget;
ctGroups: // second constraint
forall( g in allGroups )
xg[g]==1;
ctCategories: // third constraint
forall( c in categories )
Uc[c]==xc[c];
}
{string} solution={p | p in allProducts : z[p]==1};
execute
{
writeln("xg=",xc);
writeln("xg=",xg);
writeln("Solution=",solution);
}
Here the code for products.data
categories={"Carbs","Protein","Fat"};
groups=[{"Meat","Milk"},{"Pasta","Bread"},{"Oil","Butter"}];
products=[
{"Product11","Product12"},{"Product21","Product22","Product23"},
{"Product31","Product32"},{"Product41","Product42"},
{"Product51"},{"Product61","Product62"}];
prices=[1,1,3,3,2,1,2,1,3,1,2,1];
Uc=[1,0,0];
Ug=[0.8,0.2,0.1,1,0.01,0.6];
budget=2;
The results given by IBM Studio are the following: {Product12,Product31}; while the result I want is either {Product11} or {Product12}.
I have also noticed this in the conflicts tab:
And this in the relaxation tab:
So I have five questions:
I don't see any conflicts between the constraints, because if we choose the product "Product12" (or Product11") we respect all the constraint and the budget would be <= 2 because price["Product12"]==1.
I don't understand why does the optimizer chose to not respect the last constraint, and to maximize the objective function instead.
If the optimizer did not use any relaxation, would this lead to an infeasible model (no solution to the problem)? I don't understand why? For me choosing only "Product12" (or "Product11") is a perfect solution with no need to any relaxation.
How to oblige the optimizer to not relax the last constraint? (Note that changing the settings file, products.ops to relax only labeled constraints as in the documentation did not help, as I want to relax only one constraint )
In the documentation about relaxing infeasible models I found this:
Be aware, however, that infeasibility may be the consequence of an error in the modeling of another constraint.
Is this my case?
Thank you in advance for the help
on no.1+2 = you have some things which are not defined in the model... can you say if AllGroups and groups exist separately or the 2 are the same then what is the data for those? Also you use "products" and "AllProducts", the same Q as for "groups". Would you paste here a full .mod and .dat which you have run and produced the relaxed result you showed...? Once I can at least reproduce the problem you show, I can start looking at the "why's" :-)
on no.3 = yes, it supposed to
on no.4 = the way you could arrive to a non-relaxed model is that you remove the naming for the constraints. I.e. EVERY constraint which is named is considered to be relaxed if w/o relaxation there could be no solution. Every non-named constraint is "hard", i.e. it HAS to be respected, can not be relaxed. Simply remove or comment out these lines:
ctBudget:// first constraint, ctGroups: // second constraint, ctCategories: // third constraintif you want all constraint to be respected as they are with the given data...

populate the content of two files into a final file using pentaho(different fields)

I have two files.
file A has, 3 columns
Sno,name,age,key,checkvalue
file B has 3 columns
Sno,title,age
I want to merge these two into final file C which has
Sno,name,age,key,checkvalue
I tried renaming "title" to "name" and then I used "Add constants" to add the other two field.
but, when i try to merge these, I get the below error
"
The name of field number 3 is not the same as in the first row received: you're mixing rows with different layout. Field [age String] does not have the same name as field [age String].
"
How to solve this issue.
After getting the input from file B. You use a select values and remove title column. Then you use a Add constants step and add new columns name,key,checkvalue and make Set empty string? to Y. Finally do the join accordingly. So it won't fail since both the files have same number of columns. Hope this helps.
Actually, there was an issue with the fields ... field mismatch. I used "Rename" option and it got fixed.

Getting DatabaseError: multiple default values specified for column

I can't figure out what to do to avoid this error whenever I try to make a migration using South in one of my Django projects:
ERROR:
Running migrations for askbot:
Migrating forwards to 0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl.
askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl
FATAL ERROR - The following SQL query failed: ALTER TABLE "tagplus" ADD COLUMN "id" serial NOT >NULL PRIMARY KEY DEFAULT -1;
The error was: multiple default values specified for column "id" of table "tagplus"
Error in migration: >askbot:0006_auto__del_field_tagplus_tag_ptr__add_field_tagplus_id__add_field_tagpl
DatabaseError: multiple default values specified for column "id" of table "tagplus"
MIGRATION FILE 0006 CODE (Partial):
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'TagPlus.tag_ptr'
db.delete_column(u'tagplus', u'tag_ptr_id')
# Adding field 'TagPlus.id'
db.add_column(u'tagplus', u'id',
self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True),
keep_default=False)
# Adding field 'TagPlus.name'
db.add_column(u'tagplus', 'name',
self.gf('django.db.models.fields.CharField')(default=0, unique=True, max_length=255),
keep_default=False)
Thanks!
EDIT:
I Guess the error has something to do with this choice I was prompted while creating the migration file.
? The field 'TagPlus.tag_ptr' does not have a default specified, yet is NOT NULL.
? Since you are removing this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now.
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception; you can edit the migration to fix it later
? Please select a choice:
I selected 'specify one-off value' and I set this value to 0
You are anyways saying keep_default=False. So remove that default=0 from your code
db.add_column(u'tagplus', u'id',
self.gf('django.db.models.fields.AutoField')(primary_key=True),
keep_default=False)
Per SQL it should be (remove the NOT NULL)
ALTER TABLE tagplus ADD COLUMN id serial PRIMARY KEY
See this document which explains the reason behind this error http://www.postgresql.org/docs/8.3/interactive/datatype-numeric.html#DATATYPE-SERIAL
There are two things to note:
Django will use 'id' as the default primary key if you haven't manually set one before, see here.
Postgres does not really have a 'serial' type. To resolve this issue, try to replace:
# Adding field 'TagPlus.id'
db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)
with:
# Adding field 'TagPlus.id'
if 'postgres' in db.backend_name.lower():
db.execute("CREATE SEQUENCE tagplus_id_seq")
db.execute("SELECT setval('tagplus_id_seq', (SELECT MAX(id) FROM tagplus))")
db.execute("ALTER TABLE tagplus ADD COLUMN id SET DEFAULT nextval('tagplus_id_seq'::regclass)")
db.execute("ALTER SEQUENCE tagplus_id_seq OWNED BY tagplus.id")
else:
db.add_column(u'tagplus', u'id', self.gf('django.db.models.fields.AutoField')(default=0, primary_key=True), keep_default=False)