Check if model contains key derbyjs - derbyjs

Is there a way to check if a property exists on a model?
var self = model.get("users."+userId);
if (! self.name.firstName){
//do something
}

This seems to work; however, you need to check each property one by one, since going to far down the chain might not exist.
so perhaps:
var self = model.get("users."+userId);
if (!self.name && !self.name.firstName){
//do something
}

Related

How to write to an Element in a Set?

With arrays you can use a subscript to access Array Elements directly. You can read or write to them. With Sets I am not sure of a way to write its Elements.
For example, if I access a set element matching a condition I'm only able to read the element. It is passed by copy and I can't therefore write to the original.
For example:
columns.first(
where: {
$0.header.last == Character(String(i))
}
)?.cells.append(value: addValue)
// ERROR: Cannot use mutating member on immutable value: function call returns immutable value
You can't just change things inside a set, because of how a (hash) set works. Changing them would possibly change their hash value, making the set into an invalid state.
Therefore, you would have to take the thing you want to change out of the set, change it, then put it back.
if var thing = columns.first(
where: {
$0.header.last == Character(String(i))
}) {
columns.remove(thing)
thing.cells.append(value: addValue)
columns.insert(thing)
}
If the == operator on Column doesn't care about cells (i.e. adding cells to a column doesn't suddenly make two originally equal columns unequal and vice versa), then you could use update instead:
if var thing = columns.first(
where: {
$0.header.last == Character(String(i))
}) {
thing.cells.append(value: addValue)
columns.update(thing)
}
As you can see, it's quite a lot of work, so maybe sets aren't a suitable data structure to use in this situation. Have you considered using an array instead? :)
private var _columns: [Column]
public var columns : [Column] {
get { _columns }
set { _columns = Array(Set(newValue)) }
// or any other way to remove duplicate as described here: https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift
}
You are getting the error because columns might be a set of struct. So columns.first will give you an immutable value. If you were to use a class, you will get a mutable result from columns.first and your code will work as expected.
Otherwise, you will have to do as explained by #Sweeper in his answer.

How to understand that a Core Data Entity key is sortable?

I have created a generic function to check the validity of sort descriptors:
func _areValid(sortDescriptors: [NSSortDescriptor], of type: Object.Type) -> Bool {
var inputKeys: Set<String> = []
sortDescriptors.forEach { if let key = $0.key { inputKeys.insert(key) } }
if inputKeys.isSubset(of: Set(type.entity().attributesByName.keys)) { return true }
else { return false }
}
It allows verifying that keys in the NSSortDescriptor really are the Entity keys. The problem is that a key can exist, but can be unsortable. For example, UUID. How can I check it? Thank you.
I think you'll have to check the attributeType field on each attribute, and only allow specific types. There's no way that I know of to get from the attribute type to a sortability check without just listing the types that are permitted.
For a UUID attribute, the attribute type is UUIDAttributeType. This corresponds to a property of type UUID. But there's nothing about UUIDAttributeType or the UUID struct definition that makes this clear. It only comes up in documentation. You can look up attribute types but there's no built-in way to check whether some attribute type value corresponds to something you can use in a sort descriptor.
At some point when you look up the attributesByName, you'll need to look at each attribute and return false for UUIAttributeType and anything else you don't want to allow. It's not ideal but I think it's the only way.
As an aside I'd be extremely interested to know what you're doing that makes this check necessary.

Working with Scala Option

I have been changing a lot of my Scala code recently to avoid instantiating variables with null and instead using Option. For example, I previously had:
var cxn: RepositoryConnection = null
cxn = repo.getConnection()
//do something with the connection, then close it
cxn.close()
Now, my code looks more like this.
var cxn = None : Option[RepositoryConnection]
cxn = Some(repo.getConnection())
//do something with the connection, then close it
Now the problem I have is when I want to call a method associated with the RepositoryConnection type. I try:
cxn.close()
and see this error:
value close is not a member of Option[org.openrdf.repository.RepositoryConnection]
Now, when I was using null, this operation worked just fine, because cxn was a RepositoryConnection object, not an Option[RepositoryConnection]. Is there an easy way to call the close() method now that I am using Option?
You have a few options. (Sorry about the pun.) The most straight forward is probably...
cxn.map(_.close())
But perhaps you need to do something else if cxn is None. Then you could do something like...
cxn.fold(logger.reportStatus())(_.close())
Since your variable is Option[Something], you can not call instanceOfSomethingOpt.methodOfInstance()
Instead do instanceOfSomethingOpt.map(realInstance => realInstance.methodOfInstance())
In your case, it'd be
cxn.map(realConnection => realConnection.close())
//or to make it shorter
cxn.map(_.close())
You should really give a look at Option api.
cxn.map(_.close())
is one way, in case close() returns something you might beed.
cxn.foreach(_.close())
is another way, if close() is not doing much (side-effect).
val cxn = Some(repo.getConnection())
for (c <- cxn) yield {
//do something with the connection
c.close()
}
Alternatively you can wrap the getConnection with Either or Try depending on how you want to handle errors see http://blog.xebia.com/try-option-or-either/

how to initialize a method parameter with null

I have a custom method that accepts two parameters. I am using this method with several different data sets, of which some only need to have one array passed and other two.. I am wondering if its possible to pass one null if needed?
//method
- (IBAction)startSortingTheArray:(NSArray *)arrayData:(NSArray *)arrayDataB
{
//..
}
Yes, you should be able to pass one null if needed, as long as your implementation is coded to expect it that way. For example:
- (void)startSortingTheArray:(NSArray *)arrayData arrayB:(NSArray *)arrayDataB
{
if (arrayData != nil) {
// process arrayData
}
if (arrayDataB != nil) {
// process arrayDataB
}
}
To make your interface more clean, you could also provide an alternate signature of the method and do something like:
- (void)startSortingTheArray:(NSArray *)arrayData
{
[self startSortingTheArray:arrayData arrayB:nil];
}
Note that I changed the return type from what you initially posted. You had it declared as an IBAction which should take sender as its argument, not an array as you were passing it. I assume you meant for this to be applied to another function and not really to an interface builder action.
Yes you could do that. Then in your startSortingTheArray handle such cases... (i.e. code such a way that you dont assume both arrayData & arrayDataB are present).
Another suggestion I would like to make is if the parameters are getting too many & you have this scenario of some params being present & some not. Then use 1 object as parameter. This object is encapsulated & all the data points are properties of this object. That way your code is much clear & cleaner, easy to maintain blah, blah...
if you are using this method in interface builder e.g attaching it to UIButton then its not possible.
but in if your are calling this method in other methods then yes
[self startSortingTheArray:nil arrayB:nil];
- (IBAction)startSortingTheArray:(NSArray *)arrayData:(NSArray *)arrayDataB
{
if(arrayData == nil){
// do something
}
if(arrayDataB == nil){
// do something
}
if(arryaData == nil && arrayData == nil){
// do something
}
//..
}

Zend Framework: is there a way to access the element name from within a custom validator?

I'm writing a custom validator that will validate against multiple other form element values. In my form, I call my custom validator like this:
$textFieldOne = new Zend_Form_Element_Text('textFieldOne');
$textFieldOne->setAllowEmpty(false)
->addValidator('OnlyOneHasValue', false, array(array('textFieldTwo', 'textFieldThree')));
My validator will check that only one of those three fields (textFieldOne, textFieldTwo, textFieldThree) has a value. I want to prevent a future developer from accidentally passing the same field twice.
$textFieldOne->addValidator('OnlyOneHasValue', false, array(array('textFieldOne', 'textFieldTwo', 'textFieldThree')));
So far, my validator works perfectly, except when I pass the same field name as the field that has the valiator set on it.
In my validator, you can see that I am checking that the value (of the element with the validator set on it). I'm also checking the values of the other fields that were passed to the validator.
public function isValid($value, $context = null) {
$this->_setValue($value);
$this->_context = $context;
if ($this->valueIsNotEmpty()) {
if ($this->numberOfFieldsWithAValue() == 0) {
return true;
}
$this->_error(self::MULTIPLE_VALUES);
return false;
}
if ($this->numberOfFieldsWithAValue() == 0) {
$this->_error(self::ALL_EMPTY);
return false;
}
if ($this->numberOfFieldsWithAValue() == 1) {
return true;
}
if ($this->numberOfFieldsWithAValue() > 1) {
$this->_error(self::MULTIPLE_VALUES);
return false;
}
}
private function valueIsNotEmpty() {
return Zend_Validate::is($this->_value, 'NotEmpty');
}
private function numberOfFieldsWithAValue() {
$fieldsWithValue = 0;
foreach ($this->_fieldsToMatch as $fieldName) {
if (isset($this->_context[$fieldName]) && Zend_Validate::is($this->_context[$fieldName], 'NotEmpty')) {
$fieldsWithValue++;
}
}
return $fieldsWithValue;
}
My solution is to either...
A. Let the developer figure out there is a certain way to do it.
B. Ignore $value, forcing you to pass all the elements (which isn't much different than the first option).
or C. (if possible) Find the name of the element that called my validator in the first place and ignore it from the list of $fieldsWithValue.
I don't think there is a way to apply a validator on a form without attaching it to an element, but that would be even better, if it were an option.
How can I solve this problem?
Normaly i'd advise against such things, but, in this case I believe a static member in your class would actually provide a good solution to this problem.
With a static member, you can set it to the value in the first time the isValid is called, and check against it in subsequent calls, thus giving you a mechanism for this.
You may want to set this up to use some array in the configuration options, so that you can namespace and allow multiple instances of the validator to exist happily alongside each other for different sets.
The only problem that you really have to decide how to overcome, is where you wish to display the error, as yes the form itself does not take validators. if you want all the duplicates after the first to display an error, it is not so much of a problem.