Query on yang deviation - debugging

I am new to yang deviations. I wrote a deviation like below but I am not sure if the deviation is effective. Is it possible to print a text(value of xpath) in must statement for debugging purposes? Please help.
deviation "/ns:direction" {
description "Deviation to restrict if the direction is left.";
deviate add
{
must "(<function to print current()>) " {
error-message "Direction is not left.";
description "Direction is not left." ;
}
}
}

A typical way to check whether your deviation works would be to feed your module set to a YANG schema aware validator and simply validate an instance document which ensures that your expression evaluates in a desired way. If you tailor the document so that your particular constraint fails, you'd expect the "Direction is not left." error message during validation of said document. I guess you could call that a YANG instance document test case for your YANG schema.
module b {
yang-version 1.1;
namespace "b:uri";
prefix b;
container top {
leaf direction {
type enumeration {
enum left;
enum right;
}
}
}
}
module c {
yang-version 1.1;
namespace "c:uri";
prefix "c";
import b {
prefix b;
}
deviation "/b:top/b:direction" {
deviate add {
must ". = 'left'" {
error-message "Direction is not left.";
description "Direction is not left." ;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<b:top xmlns:b="b:uri">
<b:direction>right</b:direction>
</b:top>
</config>
Error at (4:5): failed assert at "/nc:config/b:top/b:direction": Direction is not left.
Must statements are assertions about instantiated data nodes so the only way to "debug" those is to throw them against an instance document, configuration + operational state of a device, datastore contents, etc.
It should not matter if the actual constraint is introduced in the original module or later via a deviation. Deviations are just quick and dirty patches of an existing model. You won't find any in modules published by the IETF. You usually resort to them if certain hardware cannot support the requirements of a published model (hard resource limits) or if you implement a big model in several stages, tagging some things as "not-supported" (yet). There are several caveats to them; the order in which they are applied matters for example, you should avoid deviating the same object in several places, you should only define them in specialized modules that only contain deviations (deviation modules), you should consider them to be temporary, etc.

Related

Can I update a message field from enum to string, and keep its name?

The Code
Consider the following protobuf message declaration:
syntax = "proto3";
enum Airport {
TLV = 0;
JFK = 1;
...
}
message Flight {
...
Airport origin_airport = 11;
...
}
The Problem
Due to some business requirements, we have to set the Airport to be a free string rather than choosing from a closed enumerated list. I know that I can add and remove fields at will, as long as I don't reuse the same number. However, I'm not sure if I can use the same name, a-la:
message Flight {
...
reserved 11; // The old enum field number
string origin_airport = 18; // Unused so far
...
}
My Question
Upon updaing a protobuf3 field type, can the field name be preserved, as long as its number changes?
If you aren't using the JSON variant, then names aren't used at all in the payload, so yes technically it is perfectly legal to reuse names; however: this might lead to unnecessary problems with existing code - depending on existing code and language / framework specific rules, and could cause confusion. Since that is avoidable, I would advocate using a name like origin_airport_code, or similar.
(The point I'm making here: any code that used the old field probably needs attention; I can see some scenarios where the existing code might still compile after the change, but mean something different, and therefore introduce a bug that would have been avoided if you'd changed the name and forced every usage to be visited)

How to add Coding extension in FHIR resources

I'd like to add extension Coding to DSTU2 ClaimResponse.item.adjudication.code which has binding strength as Extensible. I have three formats and which one is proper, or if none of them, what is suggested format? Thanks.
a. Use FHIR code "system" with a new code value
"adjudication":[
{
"code":{
"system":"http://hl7.org/fhir/ValueSet/adjudication",
"code":"allowed"
},
"amount":{
"value":21,
"system":"urn:std:iso:4217",
"code":"USD"
}
}
]
b. Use custom code "system" with a new code value
"adjudication":[
{
"code":{
"system":"http://myhealth.com/ClaimResponse/adjudication#allowed",
"code":"allowed"
},
"amount":{
"value":21,
"system":"urn:std:iso:4217",
"code":"USD"
}
}
]
c. Use extension
"adjudication":[
{
"code":{
"extension":[
{
"url":"http://myhealth.com/ClaimResponse/adjudication#allowed",
"valueCode":"allowed"
}
]
},
"amount":{
"value":234,
"system":"urn:std:iso:4217",
"code":"USD"
}
}
]
Option b is the closest, but the system URL looks a little funky. Something like this would be better: "system":"http://myhealth.com/CodeSystem/adjudication-code"
The system should ideally be a URL that resolves to the code system definition (though it doesn't have to) and should apply to a set of codes, not the single code you're conveying. (While it's possible to have one-code code systems, it's more than a little unusual.)
Option a is wrong because we never send the value set URL as the Coding.system. Option c is unnecessary - with an extensible binding, you're free to use any codes that aren't already covered by the defined value set.
All that said, it's not clear that "allowed" makes sense as a value for "code" given the other options in the extensible value set. You might also look at the draft STU 3 version which eliminates "code" altogether. See if that design will meet your needs better, and if not, provide feedback when it goes to ballot this August.

Stanford OpenIE: How to output dependency path instead of plain text patterns?

I am looking through the Java source code and wondering if it's easy to modify the system such that the predicate portion of each triple is the dependency path between the two entities instead of the surface form.
Since the natural logic module operates on the dependency trees I suppose there shall be an easy tweak to this demand.
I trace the code in edu.stanford.nlp.naturalli/OpenIE.java to:
// Get the extractions
boolean empty = true;
synchronized (OUTPUT) {
for (CoreMap sentence : ann.get(CoreAnnotations.SentencesAnnotation.class)) {
for (RelationTriple extraction : sentence.get(NaturalLogicAnnotations.RelationTriplesAnnotation.class)) {
// Print the extractions
OUTPUT.println(tripleToString(extraction, docid, sentence));
empty = false;
}
}
}
Please point me to the implementation of the following step:
sentence.get(NaturalLogicAnnotations.RelationTriplesAnnotation.class)
Thanks!
Each relation triple actually does store the dependency structure from which it was generated. Take a look at the asDependencyTree() function in RelationTriple.
Note that this tree is not necessarily a subtree of the original sentence -- e.g., it may be that a subject was moved around to produce a relation triple. If you're looking for a dependency path in the original sentence, you can look up tokens by their IndexAnnotation and compute a dependency path from that.

Avoiding duplicate code when performing operation on different object properties

I have recently run into a problem which has had me thinking in circles. Assume that I have an object of type O with properties O.A and O.B. Also assume that I have a collection of instances of type O, where O.A and O.B are defined for each instance.
Now assume that I need to perform some operation (like sorting) on a collection of O instances using either O.A or O.B, but not both at any given time. My original solution is as follows.
Example -- just for demonstration, not production code:
public class O {
int A;
int B;
}
public static class Utils {
public static void SortByA (O[] collection) {
// Sort the objects in the collection using O.A as the key. Note: this is custom sorting logic, so it is not simply a one-line call to a built-in sort method.
}
public static void SortByB (O[] collection) {
// Sort the objects in the collection using O.B as the key. Same logic as above.
}
}
What I would love to do is this...
public static void SortAgnostic (O[] collection, FieldRepresentation x /* some non-bool, non-int variable representing whether to chose O.A or O.B as the sorting key */) {
// Sort by whatever "x" represents...
}
... but creating a new, highly-specific type that I will have to maintain just to avoid duplicating a few lines of code seems unnecessary to me. Perhaps I am incorrect on that (and I am sure someone will correct me if that statement is wrong :D), but that is my current thought nonetheless.
Question: What is the best way to implement this method? The logic that I have to implement is difficult to break down into smaller methods, as it is already fairly optimized. At the root of the issue is the fact that I need to perform the same operation using different properties of an object. I would like to stay away from using codes/flags/etc. in the method signature if possible so that the solution can be as robust as possible.
Note: When answering this question, please approach it from an algorithmic point of view. I am aware that some language-specific features may be suitable alternatives, but I have encountered this problem before and would like to understand it from a relatively language-agnostic viewpoint. Also, please do not constrain responses to sorting solutions only, as I have only chosen it as an example. The real question is how to avoid code duplication when performing an identical operation on two different properties of an object.
"The real question is how to avoid code duplication when performing an identical operation on two different properties of an object."
This is a very good question as this situation arises all the time. I think, one of the best ways to deal with this situation is to use the following pattern.
public class O {
int A;
int B;
}
public doOperationX1() {
doOperationX(something to indicate which property to use);
}
public doOperationX2() {
doOperationX(something to indicate which property to use);
}
private doOperationX(input ) {
// actual work is done here
}
In this pattern, the actual implementation is performed in a private method, which is called by public methods, with some extra information. For example, in this case, it can be
doOperationX(A), or doOperationX(B), or something like that.
My Reasoning: In my opinion this pattern is optimal as it achieves two main requirements:
It keeps the public interface descriptive and clear, as it keeps operations separate, and avoids flags etc that you also mentioned in your post. This is good for the client.
From the implementation perspective, it prevents duplication, as it is in one place. This is good for the development.
A simple way to approach this I think is to internalize the behavior of choosing the sort field to the class O itself. This way the solution can be language-agnostic.
The implementation in Java could be using an Abstract class for O, where the purpose of the abstract method getSortField() would be to return the field to sort by. All that the invocation logic would need to do is to implement the abstract method to return the desired field.
O o = new O() {
public int getSortField() {
return A;
}
};
The problem might be reduced to obtaining the value of the specified field from the given object so it can be use for sorting purposes, or,
TField getValue(TEntity entity, string fieldName)
{
// Return value of field "A" from entity,
// implementation depends on language of choice, possibly with
// some sort of reflection support
}
This method can be used to substitute comparisons within the sorting algorithm,
if (getValue(o[i], "A")) > getValue(o[j], "A"))
{
swap(i, j);
}
The field name can then be parametrized, as,
public static void SortAgnostic (O[] collection, string fieldName)
{
if (getValue(collection[i], fieldName)) > getValue(collection[j], fieldName))
{
swap(i, j);
}
...
}
which you can use like SortAgnostic(collection, "A").
Some languages allow you to express the field in a more elegant way,
public static void SortAgnostic (O[] collection, Expression fieldExpression)
{
if (getValue(collection[i], fieldExpression)) >
getValue(collection[j], fieldExpression))
{
swap(i, j);
}
...
}
which you can use like SortAgnostic(collection, entity => entity.A).
And yet another option can be passing a pointer to a function which will return the value of the field needed,
public static void SortAgnostic (O[] collection, Function getValue)
{
if (getValue(collection[i])) > getValue(collection[j]))
{
swap(i, j);
}
...
}
which given a function,
TField getValueOfA(TEntity entity)
{
return entity.A;
}
and passing it like SortAgnostic(collection, getValueOfA).
"... but creating a new, highly-specific type that I will have to maintain just to avoid duplicating a few lines of code seems unnecessary to me"
That is why you should use available tools like frameworks or other typo of code libraries that provide you requested solution.
When some mechanism is common that mean it can be moved to higher level of abstraction. When you can not find proper solution try to create own one. Think about the result of operation as not part of class functionality. The sorting is only a feature, that why it should not be part of your class from the beginning. Try to keep class as simple as possible.
Do not worry premature about the sense of having something small just because it is small. Focus on the final usage of it. If you use very often one type of sorting just create a definition of it to reuse it. You do not have to necessary create a utill class and then call it. Sometimes the base functionality enclosed in utill class is fair enough.
I assume that you use Java:
In your case the wheal was already implemented in person of Collection#sort(List, Comparator).
To full fill it you could create a Enum type that implement Comparator interface with predefined sorting types.

Fuzzy/approximate checking of solutions from algorithms

We have people who run code for simulations, testing etc. on some supercomputers that we have. What would be nice is, if as part of a build process we can check that not only that the code compiles but that the ouput matches some pattern which will indicate we are getting meaningful results.
i.e. the researcher may know that the value of x must be within some bounds. If not, then a logical error has been made in the code (assuming it compiles and their is no compile time error).
Are there any pre-written packages for this kind of thing. The code is written in FORTRAN, C, C++ etc.
Any specific or general advice would be appreciated.
I expect most unit testing frameworks could do this; supply a toy test data set and see that the answer is sane in various different ways.
A good way to ensure that the resulting value of any computation (whether final or intermediate) meets certain constraints, is to use an object oriented programming language like C++, and define data-types that internally enforce the conditions that you are checking for. You can then use those data-types as the return value of any computation to ensure that said conditions are met for the value returned.
Let's look at a simple example. Assume that you have a member function inside of an Airplane class as a part of a flight control system that estimates the mass of the airplane instance as a function of the number passengers and the amount of fuel that plane has at that moment. One way to declare the Airplane class and an airplaneMass() member function is the following:
class Airplane {
public:
...
int airplaneMass() const; // note the plain int return type
...
private:
...
};
However, a better way to implement the above, would be to define a type AirplaneMass that can be used as the function's return type instead of int. AirplaneMass can internally ensure (in it's constructor and any overloaded operators) that the value it encapsulates meets certain constraints. An example implementation of the AirplaneMass datatype could be the following:
class AirplaneMass {
public:
// AirplaneMass constructor
AirplaneMass(int m) {
if (m < MIN || m > MAX) {
// throw exception or log constraint violation
}
// if the value of m meets the constraints,
// assign it to the internal value.
mass_ = m;
}
...
/* range checking should also be done in the implementation
of overloaded operators. For instance, you may want to
make sure that the resultant of the ++ operation for
any instance of AirplaneMass also lies within the
specified constraints. */
private:
int mass_;
};
Thereafter, you can redeclare class Airplane and its airplaneMass() member function as follows:
class Airplane {
public:
...
AirplaneMass airplaneMass() const;
// note the more specific AirplaneMass return type
...
private:
...
};
The above will ensure that the value returned by airplaneMass() is between MIN and MAX. Otherwise, an exception will be thrown, or the error condition will be logged.
I had to do that for conversions this month. I don't know if that might help you, but it appeared quite simple a solution to me.
First, I defined a tolerance level. (Java-ish example code...)
private static final double TOLERANCE = 0.000000000001D;
Then I defined a new "areEqual" method which checks if the difference between both values is lower than the tolerance level or not.
private static boolean areEqual(double a, double b) {
return (abs(a - b) < TOLERANCE);
}
If I get a false somewhere, it means the check has probably failed. I can adjust the tolerance to see if it's just a precision problem or really a bad result. Works quite well in my situation.

Resources