Mike  Kozey

Mike Kozey

1656807600

Seamlessly Generate Extension Methods & json Conversion Classes

Enum Assist

Seamlessly generate extension methods and json conversion classes for your enums!

Motivation

Dart enums can be a bit tedious to work with. Serializing them to/from json, using switch statements based off their values, or using describeEnum or split('.') to get the value's name are a couple of examples where working with enums could be improved.

Writing extensions has been a great way to add extra functionality to classes & enums. Though, you'll find yourself writing the same extensions over and over again. I was getting tired of copying and pasting code and changing a couple of things whenever I created a new enum. So I did what any other sane developer would do, I took a couple of weeks to create an automation tool to save me time. 🤪

So welcome enum_assist into your lifeproject! The fastest way to writing extension methods and json conversion classes for your enums!

Check out the example or the index to see what it can do.

How to use

Install

To use enum_assist, you will need to set up the build_runner (code-generator) for your project. First, add the following packages to your pubspec.yaml:

depenedencies:
    enum_assist_annotation:

dev_dependencies:
    build_runner:
    enum_assist:

What are these packages?

  • enum_assist_annotation, contains all the annotations that enum_assist references to generate code.
    • Why a Dependency: The annotations are a part of your code, so enum_assist_annotation must be part of the dependencies
  • enum_assist, the code generator for all the annotations
    • Why a Dev Dependency?: The generator only generates the code. So its technically not part of your code which means that enum_assist can be part of the dev_dependencies
  • build_runner, a tool that any code-generator package uses to generate code

Generating the Code

Build Runner Commands

  // If your package depends on Flutter
  flutter pub run build_runner build

  // If your package _does not_ depend on Flutter
  dart pub run build_runner build

If you're new to build_runner, I suggest taking a look at these commands & options

File Setup

Each file will need to start with the enum_assist import and the part keyword.

import 'package:enum_assist_annotation/enum_assist_annotation.dart';

part 'example.ge.dart';

Features

Default Extension Methods

The following methods will be generated with every enum annotated with EnumAssist

Name

The name of the enum value.

Greeting.friendly.name; // friendly

Description

Greeting.friendly.description; // A friendly greeting

To Int

Greeting.professional.toInt; // 0
Greeting.friendly.toInt; // 1
Greeting.relaxed.toInt; //2

Readable

Greeting.friendly.readable; // Friendly

Serialized

Specific case formatting can be done with serializedFormat (either EnumAssist or build.yaml)

Greeting.friendly.serialized; // friendly

map/maybeMap

The base of all custom extension methods.
Each enum will generate a .map(...) & .maybeMap(...) method, which is equivalent to pattern matching.

.map() provides callbacks for each enum value. All callbacks are required args and can return any value.

  var greet = Greeting.friendly;

  final whatDoYouSay = greet.map(
      professional: 'Hello Sir',
      friendly: 'Hello',
      relaxed: 'Saaa dude!',
  );

  whatDoYouSay; // Hello

.maybeMap() provides callbacks for each enum value, plus an orElse callback.
orElse is the only required arg.

var greet = Greeting.friendly;

final whatDoYouSay = greet.maybeMap(
    professional: 'Hello Sir',
    orElse: '*blank stare*',
);

whatDoYouSay; // *blank stare*

Return Type

.map<T>() and .maybeMap<T>() use generics to provide the return type of the callback.

  var greet = Greeting.friendly;

  final whatDoYouSay = greet.map<String>(
      professional: 'Hello Sir',
      friendly: 'Hello',
      // relaxed: 123, // compile error: `123` is not a type String
      relaxed: 'Saaa dude!',
  );

  whatDoYouSay.runtimeType; // String

While its not necessary to define the return type, it is recommended to do so.

  var greet = Greeting.friendly;

  final whatDoYouSay = greet.map(
      professional: 'Hello Sir',
      friendly: 'Hello',
      relaxed: 'Saaa dude!',
  );

  whatDoYouSay.runtimeType; // String
  var greet = Greeting.friendly;

  final whatDoYouSay = greet.map(
      professional: 'Hello Sir',
      friendly: null,
      relaxed: 'Saaa dude!',
  );

  whatDoYouSay.runtimeType; // String?
  var greet = Greeting.friendly;

  final whatDoYouSay = greet.map(
      professional: 'Hello Sir',
      friendly: null,
      relaxed: 3,
  );

  whatDoYouSay.runtimeType; // Object?

Custom Extensions

enum_assist allows you to create your own extension methods for your enum

There are two ways to create your own extension methods.
You start by creating a class that extends MapExtension or MaybeExtension.

IMPORTANT: All properties (other than value) need to be defined within the super constructor!


Map Extension

class SaidByExt extends MapExtension<String> {
  const SaidByExt(String value)
    : super(
        value,
        methodName: 'saidBy',
        docComment: 'Greeting that is said by...',
        allowNulls: false, // default
      );
}

Add it to the the extensions property

@EnumAssist()
enum Greeting {
  @EnumValue(extensions: [SaidByExt('Executives')])
  professional,
  @EnumValue(extensions: [SaidByExt('Co-workers')])
  friendly,
  @EnumValue(extensions: [SaidByExt('Friends')])
  relaxed,
}

Generated code:

/// Greeting that is said by...
String get saidBy {
  return map<String>(
    professional: 'Executives',
    friendly: 'Co-workers',
    relaxed: 'Friends',
  );
}

Maybe Extension

Expected return values:

  • defaultValue:
    • When the extension value is not defined
    • When the extension value is null AND allowNulls is false
  • null
    • When the extension value is null AND allowNulls is true
class HowFrequentExt extends MaybeExtension<int?> {
  const HowFrequentExt(int? value)
    : super(
        value,
        methodName: 'howFrequent',
        docComment: '1-10, How often this greeting is used.\n\n`null` if never used',
        defaultValue: 0,
        allowNulls: true,
      );
}

Add it to the the extensions property

@EnumAssist()
enum Greeting {
  @EnumValue(extensions: [])
  professional,
  @EnumValue(extensions: [HowFrequentExt(3)])
  friendly,
  @EnumValue(extensions: [HowFrequentExt(8)])
  relaxed,
  @EnumValue(extensions: [HowFrequentExt(null)])
  rude,
}

Generated Code:

/// 1-10, How often this greeting is used
///
/// `null` if never used
int? get howFrequent {
  return maybeMap<int?>(
    // returns default value
    //? if theres an argument provided, it does nothing.
    orElse: HowFrequentExt(3).defaultValue,
    professional: HowFrequentExt(3).defaultValue,
    friendly: 3,
    relaxed: 8,
    rude: null,
  );
}

Notice This:
For the generated code to access the defaultValue, it must create an instance of the extension class. If there is a required argument, the arg must be passed to avoid exceptions. Therefore, the required arg will be provided & ignored to return default value.

Note: If an extension is omitted (like professional), the default value will be used.
null will only be returned if declared with a null value. (like rude)

Json Converter

Serializing enums almost always requires a switch statement.
Mistakes can easily be made when converting from a String (or other types) to an enum.

The Json converter class is a great way to handle your enums' serialization.

The name of json converter class will be ${NAME_OF_ENUM}Conv

For a detailed example, go to toJson/fromJson

// Generated Json Converter class
final conv = GreetingConv();

conv.toJson(Greeting.professional); // professional
conv.fromJson('professional'); // Greeting.professional

Build Configuration

Customize the settings for each enum, or for all enums inside your build.yaml file.

targets:
  $default:
    builders:
      enum_assist:
        enabled: true
        options:
          # possible values:
          # - true
          # - false
          # default: true
          create_json_conv: true
          create_name: true
          create_description: true
          create_to_int: true
          create_readable: true
          create_serialized: true

          # possible values:
          # - camel
          # - capital
          # - constant
          # - dot
          # - header
          # - kebab
          # - no
          # - none
          # - pascal
          # - path
          # - sentence
          # - snake
          # - swap
          # default: none
          serialized_format: none

          # possible values:
          # - true
          # - false
          # default: true
          use_doc_comment_as_description: true

          # possible values:
          # - true
          # - false
          # default: false
          use_int_value_for_serialization: false

Some Examples!

Examples

Map Example

Lets create a .response method for the enum Greeting enum.
This method will return a String with the response to the greeting.

We first need to create our extension class.

class ResponseExt extends MapExtension<String> {
  const ResponseExt(String value)
    : super(
        value,
        methodName: 'response',
        docComment: 'The response to a greeting',
      );
}

Note:
The MapExtension class also has an allowNulls argument, which defaults to false.
This can be set to true to change the return type nullable.

Next, we need to add our extension to the enum.
This can be done by annotating the enum's values with EnumValue, And then adding the extension to the extensions field.

Note:
Because the .map(...) requires all args to be defined, we must add the ResponseExt extension to ALL enum fields.
Failure to do so will result in an error when generating the code.

@EnumAssist()
enum Greeting {
  @EnumValue(
    extensions: [
      ResponseExt('Hello, how do you do?'),
    ],
  )
  professional,

  @EnumValue(
    extensions: [
      ResponseExt('Hey! Hows it going?'),
    ],
  )
  friendly,

  @EnumValue(
    extensions: [
      ResponseExt('Whats up my dude!?'),
    ],
  )
  relaxed,
}

After the build_runner has run, you can now access the .response method on the Greeting enum.

var greet = Greeting.friendly;

greet.response; // Hey! Hows it going?

Greeting.relaxed.response; // Whats up my dude!?

MaybeMap Example

Lets create a .isCool method for the Greeting enum.
This method will return true only if the enum value is friendly or relaxed. Or else it will return false.

We first need to create our extension class.

class IsCoolExt extends MaybeExtension<bool> {
  const IsCoolExt(bool value)
    : super(
        value,
        methodName: 'isCool',
        defaultValue: false,
        docComment: 'Is this a cool greeting?',
      );
}

Note:
The MaybeExtension class also has an allowNulls argument, which defaults to false.
This can be set to true if you want the return type to be nullable.

Note:
The constructor could take a named argument with a default value to reduce the amount of code needed.

const IsCoolExt([bool value = true])

Next, we need to add our extension to the enum.
This can be done by adding the EnumValue annotation to any enum field. And then adding the extension to the extensions list.

@EnumAssist()
enum Greeting {
  professional,

  @EnumValue(
    extensions: [
      IsCoolExt(true),
    ],
  )
  friendly,

  @EnumValue(
    extensions: [
      IsCoolExt(true),
    ],
  )
  relaxed,
}

Notice This:
We did not annotate professional with EnumValue or IsCoolExt.
This is because .maybeMap(...) doesn't require all callbacks to be defined.

The generator will use the defaultValue from IsCoolExt as the return value.

After the build_runner has run, you can now access the .isCool method on the Greeting enum.

var greet = Greeting.friendly;
greet.isCool; // true

Greeting.professional.isCool; // false

toJson & fromJson

Serializing enums almost always requires a switch statement.
Mistakes can easily be made when converting from a string to an enum.

Json Converter Classes are a great way to handle this.

Let's create an enum for the two examples below, Using json_serializable & Manually Serializing.

@EnumAssist()
enum SuperHeroes {
  @EnumValue(serializedValue: 'Capitan America')
  capitanAmerica,

  @EnumValue(serializedValue: 'Black Widow')
  blackWidow,

  @EnumValue(serializedValue: 'Dr. Strange')
  drStrange,
}

Using json_serializable

json_serializable will automatically serialize enums to json by using describeEnum. This is great if your enum's values are exactly the same as the json values. But that is not always the case, just like our SuperHeroes enum.

Let's use our generated class SuperHeroesConv fix that problem!

Here is our example class, annotated with JsonSerializable

@JsonSerializable()
class Character {
  const Character(
    this.secretIdentity,
    this.hero,
    this.powerLevel,
  );

  final String secretIdentity;
  final SuperHeroes hero;

  factory Character.fromJson(Map<String, dynamic> json) =>
      _$CharacterFromJson(json);
}

By default, json_serializable will serialize our hero field using the literal enum value as a String.

final steve = Character('Steve Rogers', SuperHeroes.capitanAmerica);

final json = steve.toJson();

print(json['hero']); //capitanAmerica

To tell json_serializable to convert the hero field with the values provided by EnumValue.serializedValue, you'll need to annotated the field in your class

  final String secretIdentity;

  @SuperHeroesConv()
  final SuperHeroes hero;

Note: If hero were nullable, you would need to annotate the field with a nullable converter

  final String secretIdentity;

  @SuperHeroesConv.nullable
  final SuperHeroes hero;

After you run the build_runner, the json value for the hero field will now be

final steve = Character('Steve Rogers', SuperHeroes.capitanAmerica);

final json = steve.toJson();

print(json['hero']); // Capitan America

Manually Serializing

Here is an example of what your class could look like

class Character {
  const Character(
    this.secretIdentity,
    this.hero,
  );

  final String secretIdentity;
  final SuperHeroes hero;

  Map<String, dynamic> toJson() {
    return {
      'secretIdentity': secretIdentity,
      'hero': superHeroToJson(hero),
    };
  }

  factory Character.fromJson(Map<String, dynamic> json) {
    return Character(
      json['secretIdentity'] as String,
      superHeroFromJson(json['hero'] as String),
    );
  }
}

String superHeroToJson(SuperHeroes hero) {
  switch (hero) {
    case SuperHeroes.capitanAmerica:
      return 'Capitan America';
    case SuperHeroes.blackWidow:
      return 'Black Widow';
    case SuperHeroes.drStrange:
      return 'Dr. Strange';
  }
}

SuperHeroes superHeroFromJson(String hero) {
  switch (hero) {
    case 'Capitan America':
      return SuperHeroes.capitanAmerica;
    case 'Black Widow':
      return SuperHeroes.blackWidow;
    case 'Dr. Strange':
      return SuperHeroes.drStrange;
    default:
      throw Exception('Could not find superhero for $hero');
  }
}

It's a lot of work to just convert an enum to json!
Thankfully, the generated class SuperHeroConv can do all of the work here

Our toJson and fromJson methods will now look like this

class Character {
  const Character(
    this.secretIdentity,
    this.hero,
  );

  final String secretIdentity;
  final SuperHeroes hero;

  static const _conv = SuperHeroesConv();

  Map<String, dynamic> toJson() {
    return {
      'secretIdentity': secretIdentity,
      'hero': _conv.toJson(hero),

      // you could also use the `serialized` method here
      // which is the same as _conv.toJson(hero)
      //
      // 'hero': hero.serialized,
    };
  }

  factory Character.fromJson(Map<String, dynamic> json) {
    return Character(
      json['secretIdentity'] as String,
      _conv.fromJson(json['hero'] as String),
    );
  }
}

Here's what the hero's value would look like

final steve = Character('Steve Rogers', SuperHeroes.capitanAmerica);

final json = steve.toJson();

print(json['hero']); // Capitan America

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add enum_assist

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  enum_assist: ^0.1.0+1

Alternatively, your editor might support dart pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:enum_assist/enum_assist.dart';

example/lib/enum_assist_example.dart

import 'package:enum_assist_annotation/enum_assist_annotation.dart';

part 'enum_assist_example.ge.dart';

@EnumAssist(
  createJsonConv: true, // default
  serializedFormat: SerializedFormat.none, // default
  useDocCommentAsDescription: true, // default
)
enum Example {
  @EnumValue(
    readable: 'One', // default
    description: 'one description', // default (uses doc comment)
    extensions: [], // default
    serializedValue: 'one', // default
    useDocCommentAsDescription: true, // default
  )

  /// one description
  one,

  @EnumValue(
    readable: 'Two', // default
    description:
        null, // default (uses nothing because [useDocCommentAsDescription] is false)
    extensions: [], // default
    serializedValue: 'two', // default
    useDocCommentAsDescription: false, // overridden
  )
  // two description
  two,

  @EnumValue(
    readable: 'Threeeeee', // overridden
    description: 'three is the best', // overridden
    extensions: [], // default
    serializedValue: '3', // overridden
    useDocCommentAsDescription: false, // overridden
  )

  /// three description
  three,
}

Author: mrgnhnt96
Source Code: https://github.com/mrgnhnt96/enum_assist/
License: MIT

#flutter #dart #enums 

What is GEEK

Buddha Community

Seamlessly Generate Extension Methods & json Conversion Classes
Lawrence  Lesch

Lawrence Lesch

1662107520

Superdom: Better and Simpler ES6 DOM Manipulation

Superdom

You have dom. It has all the DOM virtually within it. Use that power:

// Fetch all the page links
let links = dom.a.href;

// Links open in a new tab
dom.a.target = '_blank';

Only for modern browsers

Getting started

Simply use the CDN via unpkg.com:

<script src="https://unpkg.com/superdom@1"></script>

Or use npm or bower:

npm|bower install superdom --save

Select

It always returns an array with the matched elements. Get all the elements that match the selector:

// Simple element selector into an array
let allLinks = dom.a;

// Loop straight on the selection
dom.a.forEach(link => { ... });

// Combined selector
let importantLinks = dom['a.important'];

There are also some predetermined elements, such as id, class and attr:

// Select HTML Elements by id:
let main = dom.id.main;

// by class:
let buttons = dom.class.button;

// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];

Generate

Use it as a function or a tagged template literal to generate DOM fragments:

// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;

// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');

Delete elements

Delete a piece of the DOM

// Delete all of the elements with the class .google
delete dom.class.google;   // Is this an ad-block rule?

Attributes

You can easily manipulate attributes right from the dom node. There are some aliases that share the syntax of the attributes such as html and text (aliases for innerHTML and textContent). There are others that travel through the dom such as parent (alias for parentNode) and children. Finally, class behaves differently as explained below.

Get attributes

The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):

// Retrieve all the urls from the page
let urls = dom.a.href;     // #attr-list
  // ['https://google.com', 'https://facebook.com/', ...]

// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html;     // #attr-alias
  // ['Level 2 header', 'Another level 2 header', ...]

// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank;    // #attr-value
  // true/false

You also use these:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// Set target="_blank" to all links
dom.a.target = '_blank';     // #attr-set
dom.class.tableofcontents.html = `
  <ul class="tableofcontents">
    ${dom.h2.map(h2 => `
      <li>
        <a href="#${h2.id}">
          ${h2.innerHTML}
        </a>
      </li>
    `).join('')}
  </ul>
`;

Remove an attribute

To delete an attribute use the delete keyword:

// Remove all urls from the page
delete dom.a.href;

// Remove all ids
delete dom.a.id;

Classes

It provides an easy way to manipulate the classes.

Get classes

To retrieve whether a particular class is present or not:

// Get an array with true/false for a single class
let isTest = dom.a.class.test;     // #class-one

For a general method to retrieve all classes you can do:

// Get a list of the classes of each matched element
let arrays = dom.a.class;     // #class-arrays
  // [['important'], ['button', 'cta'], ...]

// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat;     // #class-flat
  // ['important', 'button', 'cta', ...]

// And if you just want an string with space-separated classes:
let text = dom.a.class._text;     // #class-text
  // 'important button cta ...'

Add a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false

Manipulate

Did we say it returns a simple array?

dom.a.forEach(link => link.innerHTML = 'I am a link');

But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:

// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';

Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:

// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';

// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');

Note: this won't work dom.a.html += ' ^_^'; for more than 1 match (for reasons)

Or get into genetics to manipulate the attributes:

dom.a.attr.target = '_blank';

// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';

Events

You can also handle and trigger events:

// Handle click events for all <a>
dom.a.on.click = e => ...;

// Trigger click event for all <a>
dom.a.trigger.click;

Testing

We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: https://github.com/franciscop/superdom 
License: MIT license

#javascript #es6 #dom 

Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Yashi Tyagi

1617449307

CA Classes - Best CA Classes Online

Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.

check here : ca classes

#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online

amelia jones

1591340335

How To Take Help Of Referencing Generator

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

Royce  Reinger

Royce Reinger

1658977500

A Ruby Library for Generating Text with Recursive Template Grammars

Calyx

Calyx provides a simple API for generating text with declarative recursive grammars.

Install

Command Line

gem install calyx

Gemfile

gem 'calyx'

Examples

The best way to get started quickly is to install the gem and run the examples locally.

Any Gradient

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

Tiny Woodland Bot

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

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

Usage

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)

Block Constructors

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

Template Expressions

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"

Nesting and Substitution

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

Random Sampling

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.

Weighted Choices

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.

  • Floats must be in the interval 0..1 and the given weights for a production must sum to 1.
  • Ranges must be contiguous and cover the entire interval from 1 to the maximum value of the largest range.
  • Integers (Fixnums) will produce a distribution based on the sum of all given numbers, with each number being a fraction of that sum.

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

String Modifiers

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

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."

Mappings

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."

Modifier Mixins

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

Monkeypatching String

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."

Memoized Rules

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.

Unique Rules

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

Dynamically Constructing Rules

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)

External File Formats

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

Accessing the Raw Generated Tree

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."]]]]]

Roadmap

Rough plan for stabilising the API and features for a 1.0 release.

VersionFeatures planned
0.6block constructor
0.7support for template context map passed to generate
0.8method missing metaclass API
0.9return grammar tree from #evaluate, with flattened string from #generate being separate
0.10inject custom string functions for parameterised rules, transforms and mappings
0.11support YAML format (and JSON?)
0.12API documentation
0.13Support for unique rules
0.14Support for Ruby 2.4
0.15Options config and ‘strict mode’ error handling
0.16Improve representation of weighted probability selection
0.17Return result object from #generate calls

Credits

Author & Maintainer

Contributors

Author: Maetl
Source Code: https://github.com/maetl/calyx 
License: MIT license

#ruby #text