Default string values for union types in Yang Schema - schema

Why can't the leaf wibble be assigned a default value "-"in the following schema (comments not in schema, added to post for clarity)
module type
{
namespace "example.com";
prefix "foo";
typedef optional-value {
type union {
type uint8 {
range "0 .. 99";
}
type string {
pattern "^-$";
}
}
}
container bar {
leaf wibble {
type optional-value;
default "-"; ### NOT OKAY
}
leaf wobble {
type optional-value;
default 42; ### OKAY
}
}
}
yanglint (version 0.16.105) does not validate the above schema and returns the error message:
err : Invalid value "-" in "wibble" element. (/type:wibble)
err : Module "type" parsing failed.
Done some more experimenting and it appears that strings with patterns cannot be assigned default values
module tmp
{
namespace "example.com";
prefix "foo";
container bar {
leaf wibble {
type string {
pattern "^x$";
}
default "x"; ### NOT OKAY
}
leaf wobble {
type string;
default "y"; ### OKAY
}
}
}
yanglint output:
err : Value "x" does not satisfy the constraint "^x$" (range, length, or pattern). (/tmp:wibble)
err : Module "tmp" parsing failed.

In YANG one uses the regex flavor from XML Schema which doesn't require ^$ to anchor expressions so that they math the entire value. All XSD expressions are implicitly anchored. You could try to remove these characters from your patterns and give it another try.

Related

Shopify bulk query results parsing

I am working on a shopify integration, and I am trying to perform some bulk queries which return data in jsonl format.
I read carefully the documentation, and I understood which is the principle behind this format, but there is one thing I don't understand: the following is a portion of my jsonl file representing the first item in the result
{"id":"gid:\/\/shopify\/Product\/6755349070004","options":[{"id":"gid:\/\/shopify\/ProductOption\/8677003133108","name":"Città","position":1}],"title":"Product title","productType":"Concerto Live"}
{"id":"gid:\/\/shopify\/ProductVariant\/40163436363956","price":"100.00","title":"MIlano","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
{"id":"gid:\/\/shopify\/ProductVariant\/40163436396724","price":"100.00","title":"Roma","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
{"id":"gid:\/\/shopify\/ProductVariant\/40163436429492","price":"100.00","title":"Firenze","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
{"id":"gid:\/\/shopify\/Collection\/272323707060","description":"Product variant description","title":"CONCERTI","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
{"id":"gid:\/\/shopify\/Collection\/272323739828","description":"Product variant description","title":"LIVE","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
{"id":"gid:\/\/shopify\/Collection\/273036607668","description":"Product variant description","title":"Product variant description","__parentId":"gid:\/\/shopify\/Product\/6755349070004"}
and it's obtained by the following query
mutation {
bulkOperationRunQuery(
query: """
{
items: products{
pageInfo {
hasNextPage
}
edges {
cursor
node {
id
variants(first: 10) {
edges {
node {
id
price
title
}
}
}
options(first: 5) {
id
name
position
}
title
collections(first: 8) {
edges {
node {
id
metafields(first: 5) {
edges {
node {
id
key
namespace
value
}
}
}
description
title
}
}
}
productType
images(first: 2) {
edges {
node {
src
}
}
}
}
}
}
}
"""
) {
bulkOperation {
id
status
}
userErrors {
field
message
}
}
}
So The first line it the "main" product object, the lines 2,3 and 4 are the variants, then we have the collections and then the image: the problem is that, besides the parent's id, there is no way to know which parent's property a child line refers to. If I want to build back a json from this, how can I know for example that the second line is an item of the array in products.variants?
You can use either:
the id format (gid://shopify/Product/6755349070004 is a product)
the __typename property that exists on all GraphQL objects

How to add custom serialization/deserialization for protobuf?

I have my message definition like
message ID {
string value = 1;
}
message User {
ID id = 1;
google.protobuf.StringValue name = 2;
}
Now if I serialize an instance of User to json, I get something like this
{
"id": {
"value" : "myid"
}
"name" : "Josh"
}
As you can see for the WKT types the value is unnested. However, for my custom message type User the value is nested. How do I make the output look like
{
"id": "myid"
"name" : "Josh"
}
I mean how do I serialize, deserialize to custom type.
One option I could think of is update this function https://github.com/protocolbuffers/protobuf/blob/master/python/google/protobuf/json_format.py#L199
This means, have a copy of json_format.py and extend _IsWrapperMessage to my custom types

Why would you use a proto rule in a Perl 6 grammar?

Here are two grammars. One uses a proto token and one doesn't. They both get the same done. These are basically the examples in S05 under "Variable (non-)interpolation". In this simple example, they are both able to do the same things.
Which situations justify all the extra typing? The proto tokens have distinct methods in the action class, and maybe there's a small benefit there. However, you have to type some extra stuff to get that benefit.
Is there some feature of proto that makes other parts of the grammar easier?
grammar NoProto {
token variable { <sigil> <identifier> }
token identifier { <ident>+ }
token sigil { < $ # % & :: > }
}
grammar YesProto {
token variable { <sigil> <identifier> }
token identifier { <ident>+ }
proto token sigil { * }
token sigil:sym<$> { <sym> }
token sigil:sym<#> { <sym> }
token sigil:sym<%> { <sym> }
token sigil:sym<&> { <sym> }
token sigil:sym<::> { <sym> }
}
class Proto::Actions {
method variable ($/) {
say "found variable: " ~ $/;
}
method identifier ($/) {
say "found identifier: " ~ $/;
}
method sigil ($/) {
say "found sigil: " ~ $/;
}
method sigil:sym<$> ($/) {
say "found sym sigil: " ~ $/;
}
}
my $variable = '$butterfuly';
say "------No proto parsing";
my $no_proto_match = NoProto.parse(
$variable,
:rule<variable>,
:actions(Proto::Actions),
);
say "------Yes proto parsing";
my $yes_proto_match = YesProto.parse(
$variable,
:rule<variable>,
:actions(Proto::Actions),
);
The output shows that proto calls a different method in the action class:
------No proto parsing
found sigil: $
found identifier: butterfuly
found variable: $butterfuly
------Yes proto parsing
found sym sigil: $
found identifier: butterfuly
found variable: $butterfuly
Technically, a proto will be made for you if you don't specify it yourself. It basically creates the multi-method dispatch handler for that particular token (just as it does with sub and method). Which you usually don't need to care about.
Why would you specify a proto? I can think of a number of reasons:
because you want the tokens to share some traits
because you want to execute some code before or after the dispatch
Yes, the { * } may contain executable code. The bare Whatever indicates the dispatching to the appropriate candidate. Showing this in a simpler situation with sub:
proto a(|) { say "before"; {*}; say "after" }
multi a(Int) { say "Int" }
multi a(Str) { say "Str" }
a 42; a "42"
shows:
before
Int
after
before
Str
after
Hope this helps :-)
Having the method it calls in an actions class can be useful for separating out the logic. It's basically the same sort of idea as multimethods except for grammars.
( I wrote this for evaluating answers to a Code Golf )
grammar Mathemania {
token TOP { <cmd-list> }
token cmd-list { <cmd>+ }
token cmd { <op> <argument>? }
proto token op { * }
token op:sym<exp> { e } # notice that the name doesn't have to match
token op:sym<factorial> { f }
token op:sym<root> { r }
token op:sym<ceil> { c }
token op:sym<floor> { l }
token argument { '(' ~ ')' <cmd-list> }
}
class Calculate {
method TOP ($/) { make $<cmd-list>.made }
method argument ($/) { make $<cmd-list>.made }
method cmd-list ($/) {
my $result = 2;
$result = .made.($result).narrow for #<cmd>;
make $result;
}
method cmd ($/) {
if $<argument> {
make $<op>.made.assuming( *, $<argument>.made );
} else {
make $<op>.made;
}
}
method op:sym<exp> ($/) { make -> \n, \e = 2 { n ** e } }
method op:sym<factorial> ($/) { make -> \n, \k = 2 { [*] n, n - k + 1 ...^ 0 } }
method op:sym<root> ($/) { make -> \n, \r = 2 { n ** (1/r) } }
method op:sym<ceil> ($/) { make &ceiling }
method op:sym<floor> ($/) { make &floor }
}
It also makes it so that a subclassing grammar can add its tokens along side of those that already exist, and a subclassing actions class can do the same. ( try it )
grammar Mathmania-Plus is Mathemania {
token op:sym<negate> { n }
token op:sym<abs> { a }
}
class Calculate-Plus is Calculate {
method op:sym<negate> ($/) { make &prefix:<-> }
method op:sym<abs> ($/) { make &abs }
}
One benefit of splitting your alternatives into a proto and multis is that you can extend it more reliably. You can add multis to the existing proto in a grammar that inherits from the grammar that declares the proto, and you don't need to list all the possible alternatives (which you'd have to do in case a of a single rule).
This means that you can even have multiple independent extensions to the same grammar, for example by mixing in several rules that supply multis for different symbols to match.
This is basically the mechanism that Perl 6 itself uses when you define a custom operator: there are rules for matching the different kinds of operators (like infix, prefix, postfix, ...), and declaring a new operator derives a new grammar from the currently active one, with a multi candidate added for the new operator. A script can import operators from several modules that don't know of each other thanks to the extensibility of proto token mechanism.

How to get the value of an annotated variable?

So, I'm writing a method that will get annotated variables (doubles) and store them in a map. The variables are elements of an object. The name of the variable should be the key and its value - the parameter.
public void putInMap() {
Field[] fields = this.getClass().getDeclaredFields();
for (Field v: fields) {
if (v.isAnnotationPresent(Annotation.class))
map.put(v.getName(), *value here* );
}
}
My question is how to get the value of the variable (which is now a Field) so that I could put it in my map?
Try:
for (Field v : fields) {
if (v.isAnnotationPresent(Annotation.class)) {
v.setAccessible(true);
map.put(v.getName(), v.get(this));
}
}

How to Retrieve the Primary Key When Saving a New Object in Anorm

I'm using Scala Play! framework with Anorm to persist the data model to the database. I followed the example code here :
case class Bar(id: Pk[Long], name: String)
object Bar {
val simple = {
get[Pk[Long]]("id") ~
get[String]("name") map {
case id~name => Bar(id, name)
}
}
def findAll(): Seq[Bar] = {
DB.withConnection { implicit connection =>
SQL("select * from bar").as(Bar.simple *)
}
}
def create(bar: Bar): Unit = {
DB.withConnection { implicit connection =>
SQL("insert into bar(name) values ({name})").on(
'name -> bar.name
).executeUpdate()
}
}
}
Trying to expand on it, I want to retrieve the primary key just created and store it in the case class.
How can I retrieve the primary key?
Use the executeInsert method instead of executeUpdate. Noted here, the foremer method returns Option[T] where T is the type of the primary key.
You can extract the value with a match statement:
DB.withConnection { implicit connection =>
SQL(...).executeInsert()
} match {
case Some(long) => long // The Primary Key
case None => ...
}