1648976580
go-enum
An enum generator for go
go-enum will take a commented type declaration like this:
// ENUM(jpeg, jpg, png, tiff, gif)
type ImageType int
and generate a file with the iota definition along various optional niceties that you may need:
const (
// ImageTypeJpeg is a ImageType of type Jpeg.
ImageTypeJpeg ImageType = iota
// ImageTypeJpg is a ImageType of type Jpg.
ImageTypeJpg
// ImageTypePng is a ImageType of type Png.
ImageTypePng
// ImageTypeTiff is a ImageType of type Tiff.
ImageTypeTiff
// ImageTypeGif is a ImageType of type Gif.
ImageTypeGif
)
// String implements the Stringer interface.
func (x ImageType) String() string
// ParseImageType attempts to convert a string to a ImageType.
func ParseImageType(name string) (ImageType, error)
// MarshalText implements the text marshaller method.
func (x ImageType) MarshalText() ([]byte, error)
// UnmarshalText implements the text unmarshaller method.
func (x *ImageType) UnmarshalText(text []byte) error
Fear not the fact that the MarshalText
and UnmarshalText
are generated rather than JSON methods... they will still be utilized by the default JSON encoding methods.
If you find that the options given are not adequate for your use case, there is an option to add a custom template (-t
flag) to the processing engine so that your custom code can be created!
The goal of go-enum is to create an easy to use enum generator that will take a decorated type declaration like type EnumName int
and create the associated constant values and funcs that will make life a little easier for adding new values. It's not perfect, but I think it's useful.
I took the output of the Stringer command as the String()
method, and added a way to parse a string value.
You can now download a release directly from github and use that for generating your enums! (Thanks to GoReleaser)
I did not specify any overrides on the release binary names, so uname -s
and uname -m
should provide the correct version of the binary for your distro.
curl -fsSL "https://github.com/abice/go-enum/releases/download/$(GO_ENUM_VERSION)/go-enum_$(uname -s)_$(uname -m)" -o go-enum
//go:generate go-enum -f=$GOFILE --marshal
go generate ./...
If you prefer makefile stuff, you can always do something like this:
STANDARD_ENUMS = example/animal_enum.go \
example/color_enum.go
NULLABLE_ENUMS = example/sql_enum.go
$(STANDARD_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --ptr
$(NULLABLE_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --sqlnullint --ptr
enums: $(STANDARD_ENUMS) $(NULLABLE_ENUMS)
# The generator statement for go enum files. Files that invalidate the
# enum file: source file, the binary itself, and this file (in case you want to generate with different flags)
%_enum.go: %.go $(GOENUM) Makefile
$(GOENUM) -f $*.go $(GO_ENUM_FLAGS)
go-enum --help
NAME:
go-enum - An enum generator for go
USAGE:
go-enum [global options] [arguments...]
VERSION:
x.y.z
GLOBAL OPTIONS:
--file value, -f value The file(s) to generate enums. Use more than one flag for more files.
--noprefix Prevents the constants generated from having the Enum as a prefix. (default: false)
--lower Adds lowercase variants of the enum strings for lookup. (default: false)
--nocase Adds case insensitive parsing to the enumeration (forces lower flag). (default: false)
--marshal Adds text (and inherently json) marshalling functions. (default: false)
--sql Adds SQL database scan and value functions. (default: false)
--flag Adds golang flag functions. (default: false)
--prefix value Replaces the prefix with a user one.
--names Generates a 'Names() []string' function, and adds the possible enum values in the error response during parsing (default: false)
--nocamel Removes the snake_case to CamelCase name changing (default: false)
--ptr Adds a pointer method to get a pointer from const values (default: false)
--sqlnullint Adds a Null{{ENUM}} type for marshalling a nullable int value to sql (default: false)
--sqlnullstr Adds a Null{{ENUM}} type for marshalling a nullable string value to sql. If sqlnullint is specified too, it will be Null{{ENUM}}Str (default: false)
--template value, -t value Additional template file(s) to generate enums. Use more than one flag for more files. Templates will be executed in alphabetical order.
--alias value, -a value Adds or replaces aliases for a non alphanumeric value that needs to be accounted for. [Format should be "key:value,key2:value2", or specify multiple entries, or both!]
--help, -h show help (default: false)
--version, -v print the version (default: false)
The parser looks for comments on your type defs and parse the enum declarations from it. The parser will look for ENUM(
and continue to look for comma separated values until it finds a )
. You can put values on the same line, or on multiple lines.
If you need to have a specific value jump in the enum, you can now specify that by adding =numericValue
to the enum declaration. Keep in mind, this resets the data for all following values. So if you specify 50
in the middle of an enum, each value after that will be 51, 52, 53...
You can use comments inside enum that start with //
The comment must be at the end of the same line as the comment value, only then it will be added as a comment to the generated constant.
// Commented is an enumeration of commented values
/*
ENUM(
value1 // Commented value 1
value2
value3 // Commented value 3
)
*/
type Commented int
The generated comments in code will look something like:
...
const (
// CommentedValue1 is a Commented of type Value1
// Commented value 1
CommentedValue1 Commented = iota
// CommentedValue2 is a Commented of type Value2
CommentedValue2
// CommentedValue3 is a Commented of type Value3
// Commented value 3
CommentedValue3
)
...
There are a few examples in the example
directory. I've included one here for easy access, but can't guarantee it's up to date.
// Color is an enumeration of colors that are allowed.
/* ENUM(
Black, White, Red
Green = 33 // Green starts with 33
*/
// Blue
// grey=
// yellow
// blue-green
// red-orange
// yellow_green
// red-orange-blue
// )
type Color int32
The generated code will look something like:
// Code generated by go-enum DO NOT EDIT.
// Version: example
// Revision: example
// Build Date: example
// Built By: example
package example
import (
"fmt"
"strings"
)
const (
// ColorBlack is a Color of type Black.
ColorBlack Color = iota
// ColorWhite is a Color of type White.
ColorWhite
// ColorRed is a Color of type Red.
ColorRed
// ColorGreen is a Color of type Green.
// Green starts with 33
ColorGreen Color = iota + 30
// ColorBlue is a Color of type Blue.
ColorBlue
// ColorGrey is a Color of type Grey.
ColorGrey
// ColorYellow is a Color of type Yellow.
ColorYellow
// ColorBlueGreen is a Color of type Blue-Green.
ColorBlueGreen
// ColorRedOrange is a Color of type Red-Orange.
ColorRedOrange
// ColorYellowGreen is a Color of type Yellow_green.
ColorYellowGreen
// ColorRedOrangeBlue is a Color of type Red-Orange-Blue.
ColorRedOrangeBlue
)
const _ColorName = "BlackWhiteRedGreenBluegreyyellowblue-greenred-orangeyellow_greenred-orange-blue"
var _ColorMap = map[Color]string{
ColorBlack: _ColorName[0:5],
ColorWhite: _ColorName[5:10],
ColorRed: _ColorName[10:13],
ColorGreen: _ColorName[13:18],
ColorBlue: _ColorName[18:22],
ColorGrey: _ColorName[22:26],
ColorYellow: _ColorName[26:32],
ColorBlueGreen: _ColorName[32:42],
ColorRedOrange: _ColorName[42:52],
ColorYellowGreen: _ColorName[52:64],
ColorRedOrangeBlue: _ColorName[64:79],
}
// String implements the Stringer interface.
func (x Color) String() string {
if str, ok := _ColorMap[x]; ok {
return str
}
return fmt.Sprintf("Color(%d)", x)
}
var _ColorValue = map[string]Color{
_ColorName[0:5]: ColorBlack,
strings.ToLower(_ColorName[0:5]): ColorBlack,
_ColorName[5:10]: ColorWhite,
strings.ToLower(_ColorName[5:10]): ColorWhite,
_ColorName[10:13]: ColorRed,
strings.ToLower(_ColorName[10:13]): ColorRed,
_ColorName[13:18]: ColorGreen,
strings.ToLower(_ColorName[13:18]): ColorGreen,
_ColorName[18:22]: ColorBlue,
strings.ToLower(_ColorName[18:22]): ColorBlue,
_ColorName[22:26]: ColorGrey,
strings.ToLower(_ColorName[22:26]): ColorGrey,
_ColorName[26:32]: ColorYellow,
strings.ToLower(_ColorName[26:32]): ColorYellow,
_ColorName[32:42]: ColorBlueGreen,
strings.ToLower(_ColorName[32:42]): ColorBlueGreen,
_ColorName[42:52]: ColorRedOrange,
strings.ToLower(_ColorName[42:52]): ColorRedOrange,
_ColorName[52:64]: ColorYellowGreen,
strings.ToLower(_ColorName[52:64]): ColorYellowGreen,
_ColorName[64:79]: ColorRedOrangeBlue,
strings.ToLower(_ColorName[64:79]): ColorRedOrangeBlue,
}
// ParseColor attempts to convert a string to a Color
func ParseColor(name string) (Color, error) {
if x, ok := _ColorValue[name]; ok {
return x, nil
}
return Color(0), fmt.Errorf("%s is not a valid Color", name)
}
func (x Color) Ptr() *Color {
return &x
}
// MarshalText implements the text marshaller method
func (x Color) MarshalText() ([]byte, error) {
return []byte(x.String()), nil
}
// UnmarshalText implements the text unmarshaller method
func (x *Color) UnmarshalText(text []byte) error {
name := string(text)
tmp, err := ParseColor(name)
if err != nil {
return err
}
*x = tmp
return nil
}
Author: Abice
Source Code: https://github.com/abice/go-enum
License: MIT License
1599854400
Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.
As Go promise for maintaining backward compatibility. After upgrading to the latest Go 1.15 version, almost all existing Golang applications or programs continue to compile and run as older Golang version.
#go #golang #go 1.15 #go features #go improvement #go package #go new features
1648976580
go-enum
An enum generator for go
go-enum will take a commented type declaration like this:
// ENUM(jpeg, jpg, png, tiff, gif)
type ImageType int
and generate a file with the iota definition along various optional niceties that you may need:
const (
// ImageTypeJpeg is a ImageType of type Jpeg.
ImageTypeJpeg ImageType = iota
// ImageTypeJpg is a ImageType of type Jpg.
ImageTypeJpg
// ImageTypePng is a ImageType of type Png.
ImageTypePng
// ImageTypeTiff is a ImageType of type Tiff.
ImageTypeTiff
// ImageTypeGif is a ImageType of type Gif.
ImageTypeGif
)
// String implements the Stringer interface.
func (x ImageType) String() string
// ParseImageType attempts to convert a string to a ImageType.
func ParseImageType(name string) (ImageType, error)
// MarshalText implements the text marshaller method.
func (x ImageType) MarshalText() ([]byte, error)
// UnmarshalText implements the text unmarshaller method.
func (x *ImageType) UnmarshalText(text []byte) error
Fear not the fact that the MarshalText
and UnmarshalText
are generated rather than JSON methods... they will still be utilized by the default JSON encoding methods.
If you find that the options given are not adequate for your use case, there is an option to add a custom template (-t
flag) to the processing engine so that your custom code can be created!
The goal of go-enum is to create an easy to use enum generator that will take a decorated type declaration like type EnumName int
and create the associated constant values and funcs that will make life a little easier for adding new values. It's not perfect, but I think it's useful.
I took the output of the Stringer command as the String()
method, and added a way to parse a string value.
You can now download a release directly from github and use that for generating your enums! (Thanks to GoReleaser)
I did not specify any overrides on the release binary names, so uname -s
and uname -m
should provide the correct version of the binary for your distro.
curl -fsSL "https://github.com/abice/go-enum/releases/download/$(GO_ENUM_VERSION)/go-enum_$(uname -s)_$(uname -m)" -o go-enum
//go:generate go-enum -f=$GOFILE --marshal
go generate ./...
If you prefer makefile stuff, you can always do something like this:
STANDARD_ENUMS = example/animal_enum.go \
example/color_enum.go
NULLABLE_ENUMS = example/sql_enum.go
$(STANDARD_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --ptr
$(NULLABLE_ENUMS): GO_ENUM_FLAGS=--nocase --marshal --names --sqlnullint --ptr
enums: $(STANDARD_ENUMS) $(NULLABLE_ENUMS)
# The generator statement for go enum files. Files that invalidate the
# enum file: source file, the binary itself, and this file (in case you want to generate with different flags)
%_enum.go: %.go $(GOENUM) Makefile
$(GOENUM) -f $*.go $(GO_ENUM_FLAGS)
go-enum --help
NAME:
go-enum - An enum generator for go
USAGE:
go-enum [global options] [arguments...]
VERSION:
x.y.z
GLOBAL OPTIONS:
--file value, -f value The file(s) to generate enums. Use more than one flag for more files.
--noprefix Prevents the constants generated from having the Enum as a prefix. (default: false)
--lower Adds lowercase variants of the enum strings for lookup. (default: false)
--nocase Adds case insensitive parsing to the enumeration (forces lower flag). (default: false)
--marshal Adds text (and inherently json) marshalling functions. (default: false)
--sql Adds SQL database scan and value functions. (default: false)
--flag Adds golang flag functions. (default: false)
--prefix value Replaces the prefix with a user one.
--names Generates a 'Names() []string' function, and adds the possible enum values in the error response during parsing (default: false)
--nocamel Removes the snake_case to CamelCase name changing (default: false)
--ptr Adds a pointer method to get a pointer from const values (default: false)
--sqlnullint Adds a Null{{ENUM}} type for marshalling a nullable int value to sql (default: false)
--sqlnullstr Adds a Null{{ENUM}} type for marshalling a nullable string value to sql. If sqlnullint is specified too, it will be Null{{ENUM}}Str (default: false)
--template value, -t value Additional template file(s) to generate enums. Use more than one flag for more files. Templates will be executed in alphabetical order.
--alias value, -a value Adds or replaces aliases for a non alphanumeric value that needs to be accounted for. [Format should be "key:value,key2:value2", or specify multiple entries, or both!]
--help, -h show help (default: false)
--version, -v print the version (default: false)
The parser looks for comments on your type defs and parse the enum declarations from it. The parser will look for ENUM(
and continue to look for comma separated values until it finds a )
. You can put values on the same line, or on multiple lines.
If you need to have a specific value jump in the enum, you can now specify that by adding =numericValue
to the enum declaration. Keep in mind, this resets the data for all following values. So if you specify 50
in the middle of an enum, each value after that will be 51, 52, 53...
You can use comments inside enum that start with //
The comment must be at the end of the same line as the comment value, only then it will be added as a comment to the generated constant.
// Commented is an enumeration of commented values
/*
ENUM(
value1 // Commented value 1
value2
value3 // Commented value 3
)
*/
type Commented int
The generated comments in code will look something like:
...
const (
// CommentedValue1 is a Commented of type Value1
// Commented value 1
CommentedValue1 Commented = iota
// CommentedValue2 is a Commented of type Value2
CommentedValue2
// CommentedValue3 is a Commented of type Value3
// Commented value 3
CommentedValue3
)
...
There are a few examples in the example
directory. I've included one here for easy access, but can't guarantee it's up to date.
// Color is an enumeration of colors that are allowed.
/* ENUM(
Black, White, Red
Green = 33 // Green starts with 33
*/
// Blue
// grey=
// yellow
// blue-green
// red-orange
// yellow_green
// red-orange-blue
// )
type Color int32
The generated code will look something like:
// Code generated by go-enum DO NOT EDIT.
// Version: example
// Revision: example
// Build Date: example
// Built By: example
package example
import (
"fmt"
"strings"
)
const (
// ColorBlack is a Color of type Black.
ColorBlack Color = iota
// ColorWhite is a Color of type White.
ColorWhite
// ColorRed is a Color of type Red.
ColorRed
// ColorGreen is a Color of type Green.
// Green starts with 33
ColorGreen Color = iota + 30
// ColorBlue is a Color of type Blue.
ColorBlue
// ColorGrey is a Color of type Grey.
ColorGrey
// ColorYellow is a Color of type Yellow.
ColorYellow
// ColorBlueGreen is a Color of type Blue-Green.
ColorBlueGreen
// ColorRedOrange is a Color of type Red-Orange.
ColorRedOrange
// ColorYellowGreen is a Color of type Yellow_green.
ColorYellowGreen
// ColorRedOrangeBlue is a Color of type Red-Orange-Blue.
ColorRedOrangeBlue
)
const _ColorName = "BlackWhiteRedGreenBluegreyyellowblue-greenred-orangeyellow_greenred-orange-blue"
var _ColorMap = map[Color]string{
ColorBlack: _ColorName[0:5],
ColorWhite: _ColorName[5:10],
ColorRed: _ColorName[10:13],
ColorGreen: _ColorName[13:18],
ColorBlue: _ColorName[18:22],
ColorGrey: _ColorName[22:26],
ColorYellow: _ColorName[26:32],
ColorBlueGreen: _ColorName[32:42],
ColorRedOrange: _ColorName[42:52],
ColorYellowGreen: _ColorName[52:64],
ColorRedOrangeBlue: _ColorName[64:79],
}
// String implements the Stringer interface.
func (x Color) String() string {
if str, ok := _ColorMap[x]; ok {
return str
}
return fmt.Sprintf("Color(%d)", x)
}
var _ColorValue = map[string]Color{
_ColorName[0:5]: ColorBlack,
strings.ToLower(_ColorName[0:5]): ColorBlack,
_ColorName[5:10]: ColorWhite,
strings.ToLower(_ColorName[5:10]): ColorWhite,
_ColorName[10:13]: ColorRed,
strings.ToLower(_ColorName[10:13]): ColorRed,
_ColorName[13:18]: ColorGreen,
strings.ToLower(_ColorName[13:18]): ColorGreen,
_ColorName[18:22]: ColorBlue,
strings.ToLower(_ColorName[18:22]): ColorBlue,
_ColorName[22:26]: ColorGrey,
strings.ToLower(_ColorName[22:26]): ColorGrey,
_ColorName[26:32]: ColorYellow,
strings.ToLower(_ColorName[26:32]): ColorYellow,
_ColorName[32:42]: ColorBlueGreen,
strings.ToLower(_ColorName[32:42]): ColorBlueGreen,
_ColorName[42:52]: ColorRedOrange,
strings.ToLower(_ColorName[42:52]): ColorRedOrange,
_ColorName[52:64]: ColorYellowGreen,
strings.ToLower(_ColorName[52:64]): ColorYellowGreen,
_ColorName[64:79]: ColorRedOrangeBlue,
strings.ToLower(_ColorName[64:79]): ColorRedOrangeBlue,
}
// ParseColor attempts to convert a string to a Color
func ParseColor(name string) (Color, error) {
if x, ok := _ColorValue[name]; ok {
return x, nil
}
return Color(0), fmt.Errorf("%s is not a valid Color", name)
}
func (x Color) Ptr() *Color {
return &x
}
// MarshalText implements the text marshaller method
func (x Color) MarshalText() ([]byte, error) {
return []byte(x.String()), nil
}
// UnmarshalText implements the text unmarshaller method
func (x *Color) UnmarshalText(text []byte) error {
name := string(text)
tmp, err := ParseColor(name)
if err != nil {
return err
}
*x = tmp
return nil
}
Author: Abice
Source Code: https://github.com/abice/go-enum
License: MIT License
1591340335
APA Referencing Generator
Many students use APA style as the key citation style in their assignment in university or college. Although, many people find it quite difficult to write the reference of the source. You ought to miss the names and dates of authors. Hence, APA referencing generator is important for reducing the burden of students. They can now feel quite easy to do the assignments on time.
The functioning of APA referencing generator
If you are struggling hard to write the APA referencing then you can take the help of APA referencing generator. It will create an excellent list. You are required to enter the information about the source. Just ensure that the text is credible and original. If you will copy references then it is a copyright violation.
You can use a referencing generator in just a click. It will generate the right references for all the sources. You are required to organize in alphabetical order. The generator will make sure that you will get good grades.
How to use APA referencing generator?
Select what is required to be cited such as journal, book, film, and others. You can choose the type of required citations list and enter all the required fields. The fields are dates, author name, title, editor name, and editions, name of publishers, chapter number, page numbers, and title of journals. You can click for reference to be generated and you will get the desired result.
Chicago Referencing Generator
Do you require the citation style? You can rely on Chicago Referencing Generator and will ensure that you will get the right citation in just a click. The generator is created to provide solutions to students to cite their research paper in Chicago style. It has proved to be the quickest and best citation generator on the market. The generator helps to sort the homework issues in few seconds. It also saves a lot of time and energy.
This tool helps researchers, professional writers, and students to manage and generate text citation essays. It will help to write Chicago style in a fast and easy way. It also provides details and directions for formatting and cites resources.
So, you must stop wasting the time and can go for Chicago Referencing Generator or APA referencing generator. These citation generators will help to solve the problem of citation issues. You can easily create citations by using endnotes and footnotes.
So, you can generate bibliographies, references, in-text citations, and title pages. These are fully automatic referencing style. You are just required to enter certain details about the citation and you will get the citation in the proper and required format.
So, if you are feeling any problem in doing assignment then you can take the help of assignment help.
If you require help for Assignment then livewebtutors is the right place for you. If you see our prices, you will observe that they are actually very affordable. Also, you can always expect a discount. Our team is capable and versatile enough to offer you exactly what you need, the best services for the prices you can afford.
read more:- Are you struggling to write a bibliography? Use Harvard referencing generator
#apa referencing generator #harvard referencing generator #chicago referencing generator #mla referencing generator #deakin referencing generator #oxford referencing generator
1658977500
Calyx provides a simple API for generating text with declarative recursive grammars.
gem install calyx
gem 'calyx'
The best way to get started quickly is to install the gem and run the examples locally.
Requires Roda and Rack to be available.
gem install roda
Demonstrates how to use Calyx to construct SVG graphics. Any Gradient generates a rectangle with a linear gradient of random colours.
Run as a web server and preview the output in a browser (http://localhost:9292
):
ruby examples/any_gradient.rb
Or generate SVG files via a command line pipe:
ruby examples/any_gradient > gradient1.xml
Requires the Twitter client gem and API access configured for a specific Twitter handle.
gem install twitter
Demonstrates how to use Calyx to make a minimal Twitter bot that periodically posts unique tweets. See @tiny_woodland on Twitter and the writeup here.
TWITTER_CONSUMER_KEY=XXX-XXX
TWITTER_CONSUMER_SECRET=XXX-XXX
TWITTER_ACCESS_TOKEN=XXX-XXX
TWITTER_CONSUMER_SECRET=XXX-XXX
ruby examples/tiny_woodland_bot.rb
Faker is a popular library for generating fake names and associated sample data like internet addresses, company names and locations.
This example demonstrates how to use Calyx to reproduce the same functionality using custom lists defined in a YAML configuration file.
ruby examples/faker.rb
Require the library and inherit from Calyx::Grammar
to construct a set of rules to generate a text.
require 'calyx'
class HelloWorld < Calyx::Grammar
start 'Hello world.'
end
To generate the text itself, initialize the object and call the generate
method.
hello = HelloWorld.new
hello.generate
# > "Hello world."
Obviously, this hardcoded sentence isn’t very interesting by itself. Possible variations can be added to the text by adding additional rules which provide a named set of text strings. The rule delimiter syntax ({}
) can be used to substitute the generated content of other rules.
class HelloWorld < Calyx::Grammar
start '{greeting} world.'
greeting 'Hello', 'Hi', 'Hey', 'Yo'
end
Each time #generate
runs, it evaluates the tree and randomly selects variations of rules to construct a resulting string.
hello = HelloWorld.new
hello.generate
# > "Hi world."
hello.generate
# > "Hello world."
hello.generate
# > "Yo world."
By convention, the start
rule specifies the default starting point for generating the final text. You can start from any other named rule by passing it explicitly to the generate method.
class HelloWorld < Calyx::Grammar
hello 'Hello world.'
end
hello = HelloWorld.new
hello.generate(:hello)
As an alternative to subclassing, you can also construct rules unique to an instance by passing a block when initializing the class:
hello = Calyx::Grammar.new do
start '{greeting} world.'
greeting 'Hello', 'Hi', 'Hey', 'Yo'
end
hello.generate
Basic rule substitution uses single curly brackets as delimiters for template expressions:
fruit = Calyx::Grammar.new do
start '{colour} {fruit}'
colour 'red', 'green', 'yellow'
fruit 'apple', 'pear', 'tomato'
end
6.times { fruit.generate }
# => "yellow pear"
# => "red apple"
# => "green tomato"
# => "red pear"
# => "yellow tomato"
# => "green apple"
Rules are recursive. They can be arbitrarily nested and connected to generate larger and more complex texts.
class HelloWorld < Calyx::Grammar
start '{greeting} {world_phrase}.'
greeting 'Hello', 'Hi', 'Hey', 'Yo'
world_phrase '{happy_adj} world', '{sad_adj} world', 'world'
happy_adj 'wonderful', 'amazing', 'bright', 'beautiful'
sad_adj 'cruel', 'miserable'
end
Nesting and hierarchy can be manipulated to balance consistency with novelty. The exact same word atoms can be combined in a variety of ways to produce strikingly different resulting texts.
module HelloWorld
class Sentiment < Calyx::Grammar
start '{happy_phrase}', '{sad_phrase}'
happy_phrase '{happy_greeting} {happy_adj} world.'
happy_greeting 'Hello', 'Hi', 'Hey', 'Yo'
happy_adj 'wonderful', 'amazing', 'bright', 'beautiful'
sad_phrase '{sad_greeting} {sad_adj} world.'
sad_greeting 'Goodbye', 'So long', 'Farewell'
sad_adj 'cruel', 'miserable'
end
class Mixed < Calyx::Grammar
start '{greeting} {adj} world.'
greeting 'Hello', 'Hi', 'Hey', 'Yo', 'Goodbye', 'So long', 'Farewell'
adj 'wonderful', 'amazing', 'bright', 'beautiful', 'cruel', 'miserable'
end
end
By default, the outcomes of generated rules are selected with Ruby’s built-in pseudorandom number generator (as seen in methods like Kernel.rand
and Array.sample
). To seed the random number generator, pass in an integer seed value as the first argument to the constructor:
grammar = Calyx::Grammar.new(seed: 12345) do
# rules...
end
Alternatively, you can pass a preconfigured instance of Ruby’s stdlib Random
class:
random = Random.new(12345)
grammar = Calyx::Grammar.new(rng: random) do
# rules...
end
When a random seed isn’t supplied, Time.new.to_i
is used as the default seed, which makes each run of the generator relatively unique.
Choices can be weighted so that some rules have a greater probability of expanding than others.
Weights are defined by passing a hash instead of a list of rules where the keys are strings or symbols representing the grammar rules and the values are weights.
Weights can be represented as floats, integers or ranges.
The following definitions produce an equivalent weighting of choices:
Calyx::Grammar.new do
start 'heads' => 1, 'tails' => 1
end
Calyx::Grammar.new do
start 'heads' => 0.5, 'tails' => 0.5
end
Calyx::Grammar.new do
start 'heads' => 1..5, 'tails' => 6..10
end
Calyx::Grammar.new do
start 'heads' => 50, 'tails' => 50
end
There’s a lot of interesting things you can do with this. For example, you can model the triangular distribution produced by rolling 2d6:
Calyx::Grammar.new do
start(
'2' => 1,
'3' => 2,
'4' => 3,
'5' => 4,
'6' => 5,
'7' => 6,
'8' => 5,
'9' => 4,
'10' => 3,
'11' => 2,
'12' => 1
)
end
Or reproduce Gary Gygax’s famous generation table from the original Dungeon Master’s Guide (page 171):
Calyx::Grammar.new do
start(
:empty => 0.6,
:monster => 0.1,
:monster_treasure => 0.15,
:special => 0.05,
:trick_trap => 0.05,
:treasure => 0.05
)
empty 'Empty'
monster 'Monster Only'
monster_treasure 'Monster and Treasure'
special 'Special'
trick_trap 'Trick/Trap.'
treasure 'Treasure'
end
Dot-notation is supported in template expressions, allowing you to call any available method on the String
object returned from a rule. Formatting methods can be chained arbitrarily and will execute in the same way as they would in native Ruby code.
greeting = Calyx::Grammar.new do
start '{hello.capitalize} there.', 'Why, {hello} there.'
hello 'hello', 'hi'
end
4.times { greeting.generate }
# => "Hello there."
# => "Hi there."
# => "Why, hello there."
# => "Why, hi there."
You can also extend the grammar with custom modifiers that provide useful formatting functions.
Filters accept an input string and return the transformed output:
greeting = Calyx::Grammar.new do
filter :shoutycaps do |input|
input.upcase
end
start '{hello.shoutycaps} there.', 'Why, {hello.shoutycaps} there.'
hello 'hello', 'hi'
end
4.times { greeting.generate }
# => "HELLO there."
# => "HI there."
# => "Why, HELLO there."
# => "Why, HI there."
The mapping shortcut allows you to specify a map of regex patterns pointing to their resulting substitution strings:
green_bottle = Calyx::Grammar.new do
mapping :pluralize, /(.+)/ => '\\1s'
start 'One green {bottle}.', 'Two green {bottle.pluralize}.'
bottle 'bottle'
end
2.times { green_bottle.generate }
# => "One green bottle."
# => "Two green bottles."
In order to use more intricate rewriting and formatting methods in a modifier chain, you can add methods to a module and embed it in a grammar using the modifier
classmethod.
Modifier methods accept a single argument representing the input string from the previous step in the expression chain and must return a string, representing the modified output.
module FullStop
def full_stop(input)
input << '.'
end
end
hello = Calyx::Grammar.new do
modifier FullStop
start '{hello.capitalize.full_stop}'
hello 'hello'
end
hello.generate
# => "Hello."
To share custom modifiers across multiple grammars, you can include the module in Calyx::Modifiers
. This will make the methods available to all subsequent instances:
module FullStop
def full_stop(input)
input << '.'
end
end
class Calyx::Modifiers
include FullStop
end
Alternatively, you can combine methods from existing Gems that monkeypatch String
:
require 'indefinite_article'
module FullStop
def full_stop
self << '.'
end
end
class String
include FullStop
end
noun_articles = Calyx::Grammar.new do
start '{fruit.with_indefinite_article.capitalize.full_stop}'
fruit 'apple', 'orange', 'banana', 'pear'
end
4.times { noun_articles.generate }
# => "An apple."
# => "An orange."
# => "A banana."
# => "A pear."
Rule expansions can be ‘memoized’ so that multiple references to the same rule return the same value. This is useful for picking a noun from a list and reusing it in multiple places within a text.
The @
sigil is used to mark memoized rules. This evaluates the rule and stores it in memory the first time it’s referenced. All subsequent references to the memoized rule use the same stored value.
# Without memoization
grammar = Calyx::Grammar.new do
start '{name} <{name.downcase}>'
name 'Daenerys', 'Tyrion', 'Jon'
end
3.times { grammar.generate }
# => Daenerys <jon>
# => Tyrion <daenerys>
# => Jon <tyrion>
# With memoization
grammar = Calyx::Grammar.new do
start '{@name} <{@name.downcase}>'
name 'Daenerys', 'Tyrion', 'Jon'
end
3.times { grammar.generate }
# => Tyrion <tyrion>
# => Daenerys <daenerys>
# => Jon <jon>
Note that the memoization symbol can only be used on the right hand side of a production rule.
Rule expansions can be marked as ‘unique’, meaning that multiple references to the same rule always return a different value. This is useful for situations where the same result appearing twice would appear awkward and messy.
Unique rules are marked by the $
sigil.
grammar = Calyx::Grammar.new do
start "{$medal}, {$medal}, {$medal}"
medal 'Gold', 'Silver', 'Bronze'
end
grammar.generate
# => Silver, Bronze, Gold
Template expansions can be dynamically constructed at runtime by passing a context map of rules to the #generate
method:
class AppGreeting < Calyx::Grammar
start 'Hi {username}!', 'Welcome back {username}...', 'Hola {username}'
end
context = {
username: UserModel.username
}
greeting = AppGreeting.new
greeting.generate(context)
In addition to defining grammars in pure Ruby, you can load them from external JSON and YAML files:
hello = Calyx::Grammar.load('hello.yml')
hello.generate
The format requires a flat map with keys representing the left-hand side named symbols and the values representing the right hand side substitution rules.
In JSON:
{
"start": "{greeting} world.",
"greeting": ["Hello", "Hi", "Hey", "Yo"]
}
In YAML:
---
start: "{greeting} world."
greeting:
- Hello
- Hi
- Hey
- Yo
Calling #evaluate
on the grammar instance will give you access to the raw generated tree structure before it gets flattened into a string.
The tree is encoded as an array of nested arrays, with the leading symbols labeling the choices and rules selected, and the trailing terminal leaves encoding string values.
This may not make a lot of sense unless you’re familiar with the concept of s-expressions. It’s a fairly speculative feature at this stage, but it leads to some interesting possibilities.
grammar = Calyx::Grammar.new do
start 'Riddle me ree.'
end
grammar.evaluate
# => [:start, [:choice, [:concat, [[:atom, "Riddle me ree."]]]]]
Rough plan for stabilising the API and features for a 1.0
release.
Version | Features planned |
---|---|
0.6 | |
0.7 | |
0.8 | |
0.9 |
|
0.10 | |
0.11 | |
0.12 | |
0.13 | |
0.14 | |
0.15 | |
0.16 | |
0.17 |
|
Author: Maetl
Source Code: https://github.com/maetl/calyx
License: MIT license
1620992479
In this digital world, online businesses aspire to catch the attention of users in a modern and smarter way. To achieve it, they need to traverse through new approaches. Here comes to spotlight is the user-generated content or UGC.
What is user-generated content?
“ It is the content by users for users.”
Generally, the UGC is the unbiased content created and published by the brand users, social media followers, fans, and influencers that highlight their experiences with the products or services. User-generated content has superseded other marketing trends and fallen into the advertising feeds of brands. Today, more than 86 percent of companies use user-generated content as part of their marketing strategy.
In this article, we have explained the ten best ideas to create wonderful user-generated content for your brand. Let’s start without any further ado.
Generally, social media platforms help the brand to generate content for your users. Any user content that promotes your brand on the social media platform is the user-generated content for your business. When users create and share content on social media, they get 28% higher engagement than a standard company post.
Furthermore, you can embed your social media feed on your website also. you can use the Social Stream Designer WordPress plugin that will integrate various social media feeds from different social media platforms like Facebook, Twitter, Instagram, and many more. With this plugin, you can create a responsive wall on your WordPress website or blog in a few minutes. In addition to this, the plugin also provides more than 40 customization options to make your social stream feeds more attractive.
In general, surveys can be used to figure out attitudes, reactions, to evaluate customer satisfaction, estimate their opinions about different problems. Another benefit of customer surveys is that collecting outcomes can be quick. Within a few minutes, you can design and load a customer feedback survey and send it to your customers for their response. From the customer survey data, you can find your strengths, weaknesses, and get the right way to improve them to gain more customers.
Additionally, it is the best way to convert your brand leads to valuable customers. The key to running a successful contest is to make sure that the reward is fair enough to motivate your participation. If the product is relevant to your participant, then chances are they were looking for it in the first place, and giving it to them for free just made you move forward ahead of your competitors. They will most likely purchase more if your product or service satisfies them.
Furthermore, running contests also improve the customer-brand relationship and allows more people to participate in it. It will drive a real result for your online business. If your WordPress website has Google Analytics, then track contest page visits, referral traffic, other website traffic, and many more.
The business reviews help your consumers to make a buying decision without any hurdle. While you may decide to remove all the negative reviews about your business, those are still valuable user-generated content that provides honest opinions from real users. Customer feedback can help you with what needs to be improved with your products or services. This thing is not only beneficial to the next customer but your business as a whole.
Reviews are powerful as the platform they are built upon. That is the reason it is important to gather reviews from third-party review websites like Google review, Facebook review, and many more, or direct reviews on a website. It is the most vital form of feedback that can help brands grow globally and motivate audience interactions.
However, you can also invite your customers to share their unique or successful testimonials. It is a great way to display your products while inspiring others to purchase from your website.
Moreover, Instagram videos create around 3x more comments rather than Instagram photo posts. Instagram videos generally include short videos posted by real customers on Instagram with the tag of a particular brand. Brands can repost the stories as user-generated content to engage more audiences and create valid promotions on social media.
Similarly, imagine you are browsing a YouTube channel, and you look at a brand being supported by some authentic customers through a small video. So, it will catch your attention. With the videos, they can tell you about the branded products, especially the unboxing videos displaying all the inside products and how well it works for them. That type of video is enough to create a sense of desire in the consumers.
#how to get more user generated content #importance of user generated content #user generated content #user generated content advantages #user generated content best practices #user generated content pros and cons