Lawrence  Lesch

Lawrence Lesch

1664386980

Command-line Spritesheet Generator Supporting Starling / Sparrow

Spritesheet.js is command-line spritesheet (a.k.a. Texture Atlas) generator written in node.js.

Supported spritesheet formats

  • Starling / Sparrow
  • JSON (i.e. PIXI.js)
  • Easel.js
  • cocos2d (i.e. version 2.x)
  • cocos2d-v3 (i.e. version 3.x)
  • CSS (new!)

Usage

Command Line

$ spritesheet-js assets/*.png

Options:

$ spritesheet-js
Usage: spritesheet-js [options] <files>

Options:
-f, --format  format of spritesheet (starling, sparrow, json, pixi.js, easel.js, cocos2d)                                                          [default: "json"]
-n, --name    name of generated spritesheet                                                                                                        [default: "spritesheet"]
-p, --path    path to export directory                                                                                                             [default: "."]
--fullpath    include path in file name                                                                                                            [default: false]
--prefix      prefix for image paths (css format only)                                                                                             [default: ""]
--trim        removes transparent whitespaces around images                                                                                        [default: false]
--square      texture should be s square                                                                                                           [default: false]
--powerOfTwo  texture width and height should be power of two                                                                                      [default: false]
--validate    check algorithm returned data                                                                                                        [default: false]
--algorithm   packing algorithm: growing-binpacking (default), binpacking (requires passing --width and --height options), vertical or horizontal  [default: "growing-binpacking"]
--width       width for binpacking                                                                                                                 [default: undefined]
--height      height for binpacking                                                                                                                [default: undefined]
--padding     padding between images in spritesheet                                                                                                [default: 0]
--scale       percentage scale                                                                                                                     [default: "100%"]
--fuzz        percentage fuzz factor (usually value of 1% is a good choice)                                                                        [default: ""]

Node.js

var spritesheet = require('spritesheet-js');

spritesheet('assets/*.png', {format: 'json'}, function (err) {
if (err) throw err;

console.log('spritesheet successfully generated');
});

Trimming / Cropping

Spritesheet.js can remove transparent whitespace around images. Thanks to that you can pack more assets into one spritesheet and it makes rendering a little bit faster.

NOTE: Some libraries such as Easel.js dont't support this feature. Trimming / Cropping

Installation

  1. Install ImageMagick
    • On versions 7.x and higher you must install the optional Legacy Tools
  2. npm install spritesheet-js -g

Test

mocha test

Thanks Przemysław Piekarski for logo design and assets in examples.

Download Details:

Author: Krzysztof-o
Source Code: https://github.com/krzysztof-o/spritesheet.js/ 
License: MIT license

#javascript #generator #node 

Command-line Spritesheet Generator Supporting Starling / Sparrow
Nigel  Uys

Nigel Uys

1663264440

10 Popular Libraries for tools That Generate Go Code

In today's post we will learn about 10 Popular Libraries for tools That Generate Go Code.

How do I generate a Go code?

Ensure that the main program from the codegen_builder.go file and the templates are in the same directory. Then run go run codegen_builder.go in your terminal. Now the program will generate code with the help of the templates and output it in the ./tmp directory.

Table of contents:

  • Copygen - Generate type-to-type and type-based code without reflection.
  • Generis - Code generation tool providing generics, free-form macros, conditional compilation and HTML templating.
  • Go-enum - Code generation for enums from code comments.
  • Go-linq - .NET LINQ-like query methods for Go.
  • Go-xray - Helpers for making the use of reflection easier.
  • Goderive - Derives functions from input types.
  • Jennifer - Generate arbitrary Go code without templates.
  • Goverter - Generate converters by defining an interface.
  • GoWrap - Generate decorators for Go interfaces using simple templates.
  • Interfaces - Command line tool for generating interface definitions.

1 - Copygen: Generate type-to-type and type-based code without reflection.

Copygen is a command-line code generator that generates type-to-type and field-to-field code without adding any reflection or dependencies to your project. Manual-copy code generated by Copygen is 391x faster than jinzhu/copier, and adds no allocation to your program. Copygen is the most customizable type-based generator to-date and features a rich yet simple setup. Copygen supports every Go type including basic, array, slice, map, chan, interface, and func types.

This example uses three type-structs to generate the ModelsToDomain() function using a Command Line Interface.

Types

The following types are defined in a program.

./domain/domain.go

// Package domain contains business logic models.
package domain

// Account represents a user account.
type Account struct {
	ID     int
	UserID string
	Name   string
	Other  string // The other field is not used.
}

./models/model.go

// Package models contains data storage models (i.e database).
package models

// Account represents the data model for account.
type Account struct {
	ID       int
	Name     string
	Password string
	Email    string
}

// A User represents the data model for a user.
type User struct {
	UserID   int
	Name     string
	UserData string
}

The models.Account and models.User fields will be copied to domain.Account fields.

Setup

Setting up Copygen is a 2-step process involving a YML and GO file.

setup.yml

# Define where the code will be generated.
generated:
  setup: ./setup.go
  output: ../copygen.go

  # Define the optional custom templates used to generate the file (.go, .tmpl supported).
  template: ./generate.go

# Define custom options (which are passed to generator options) for customization.
custom:
  option: The possibilities are endless.

The main example ignores the template fields.

setup.go

Create an interface in the specified setup file with a type Copygen interface. In each function, specify the types you want to copy from as parameters, and the type you want to copy to as return values. This interface is inspired by goverter.

/* Specify the name of the generated file's package. */
package copygen

/* Copygen defines the functions that will be generated. */
type Copygen interface {
  // custom see table below for options
  ModelsToDomain(*models.Account, *models.User) *domain.Account
}

Copygen uses no allocation with pointers because Go is pass-by-value. Specifying a pointer results in the object's fields being assigned directly; as opposed to a copy of the object's fields.

View on Github

2 - Generis: Code generation tool providing generics, free-form macros, conditional compilation and HTML templating.

Generis

Versatile Go code generator.

Description

Generis is a lightweight code preprocessor adding the following features to the Go language :

  • Generics.
  • Free-form macros.
  • Conditional compilation.
  • HTML templating.
  • Allman style conversion.

Sample

package main;

// -- IMPORTS

import (
    "html"
    "io"
    "log"
    "net/http"
    "net/url"
    "strconv"
    );

// -- DEFINITIONS

#define DebugMode
#as true

// ~~

#define HttpPort
#as 8080

// ~~

#define WriteLine( {{text}} )
#as log.Println( {{text}} )

// ~~

#define local {{variable}} : {{type}};
#as var {{variable}} {{type}};

// ~~

#define DeclareStack( {{type}}, {{name}} )
#as
    // -- TYPES

    type {{name}}Stack struct
    {
        ElementArray []{{type}};
    }

    // -- INQUIRIES

    func ( stack * {{name}}Stack ) IsEmpty(
        ) bool
    {
        return len( stack.ElementArray ) == 0;
    }

    // -- OPERATIONS

    func ( stack * {{name}}Stack ) Push(
        element {{type}}
        )
    {
        stack.ElementArray = append( stack.ElementArray, element );
    }

    // ~~

    func ( stack * {{name}}Stack ) Pop(
        ) {{type}}
    {
        local
            element : {{type}};

        element = stack.ElementArray[ len( stack.ElementArray ) - 1 ];

        stack.ElementArray = stack.ElementArray[ : len( stack.ElementArray ) - 1 ];

        return element;
    }
#end

// ~~

#define DeclareStack( {{type}} )
#as DeclareStack( {{type}}, {{type:PascalCase}} )

// -- TYPES

DeclareStack( string )
DeclareStack( int32 )

// -- FUNCTIONS

func HandleRootPage(
    response_writer http.ResponseWriter,
    request * http.Request
    )
{
    local
        boolean : bool;
    local
        natural : uint;
    local
        integer : int;
    local
        real : float64;
    local
        escaped_html_text,
        escaped_url_text,
        text : string;
    local
        integer_stack : Int32Stack;

    boolean = true;
    natural = 10;
    integer = 20;
    real = 30.0;
    text = "text";
    escaped_url_text = "&escaped text?";
    escaped_html_text = "<escaped text/>";

    integer_stack.Push( 10 );
    integer_stack.Push( 20 );
    integer_stack.Push( 30 );

    #write response_writer
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8">
                <title><%= request.URL.Path %></title>
            </head>
            <body>
                <% if ( boolean ) { %>
                    <%= "URL : " + request.URL.Path %>
                    <br/>
                    <%@ natural %>
                    <%# integer %>
                    <%& real %>
                    <br/>
                    <%~ text %>
                    <%^ escaped_url_text %>
                    <%= escaped_html_text %>
                    <%= "<%% ignored %%>" %>
                    <%% ignored %%>
                <% } %>
                <br/>
                Stack :
                <br/>
                <% for !integer_stack.IsEmpty() { %>
                    <%# integer_stack.Pop() %>
                <% } %>
            </body>
        </html>
    #end
}

// ~~

func main()
{
    http.HandleFunc( "/", HandleRootPage );

    #if DebugMode
        WriteLine( "Listening on http://localhost:HttpPort" );
    #end

    log.Fatal(
        http.ListenAndServe( ":HttpPort", nil )
        );
}

View on Github

3 - Go-enum: Code generation for enums from code comments.

go-enum. An enum generator for go

How it works

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!

Goal

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.

Installation

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

View on Github

4 - Go-linq: .NET LINQ-like query methods for Go.

go-linq. A powerful language integrated query (LINQ) library for Go.

  • Written in vanilla Go, no dependencies!
  • Complete lazy evaluation with iterator pattern
  • Safe for concurrent use
  • Supports generic functions to make your code cleaner and free of type assertions
  • Supports arrays, slices, maps, strings, channels and custom collections

Installation

When used with Go modules, use the following import path:

go get github.com/ahmetb/go-linq/v3

Older versions of Go using different dependency management tools can use the following import path to prevent breaking API changes:

go get gopkg.in/ahmetb/go-linq.v3

Quickstart

Usage is as easy as chaining methods like:

From(slice) .Where(predicate) .Select(selector) .Union(data)

Example 1: Find all owners of cars manufactured after 2015

import . "github.com/ahmetb/go-linq/v3"

type Car struct {
    year int
    owner, model string
}

...


var owners []string

From(cars).Where(func(c interface{}) bool {
	return c.(Car).year >= 2015
}).Select(func(c interface{}) interface{} {
	return c.(Car).owner
}).ToSlice(&owners)

Or, you can use generic functions, like WhereT and SelectT to simplify your code (at a performance penalty):

var owners []string

From(cars).WhereT(func(c Car) bool {
	return c.year >= 2015
}).SelectT(func(c Car) string {
	return c.owner
}).ToSlice(&owners)

View on Github

5 - Go-xray: Helpers for making the use of reflection easier.

This is a Golang library with reflection related functions which I use in my different projects.

KeyValue

This type is used to construct a key-value pair. You can use it as follows:

package main

import (
    "fmt"

    "https://github.com/pieterclaerhout/go-xray"
)

func main() {

    pair := &xray.KeyValue{
        Key:   "key",
        Value: "value",
    }

    fmt.Println(pair.String())
    // Ouptut: key=value

}

If both Key and Value are empty, an empty string is returned.

Name

Name allows you to get the name of an object.

package main

import (
    "fmt"

    "https://github.com/pieterclaerhout/go-xray"
)

func main() {

    v := &test{}

    fmt.Println(xray.Name(v))
    // Ouptut: test

    n := nil

    fmt.Println(xray.Name(n))
    // Ouptut: <nil>
    
}

View on Github

6 - Goderive: Derives functions from input types.

goderive derives mundane golang functions that you do not want to maintain and keeps them up to date.

Examples

In the following code the deriveEqual function will be spotted as a function that was not implemented (or was previously derived) and has a prefix deriveEqual.

package main

type MyStruct struct {
	Int64     int64
	StringPtr *string
}

func (this *MyStruct) Equal(that *MyStruct) bool {
	return deriveEqual(this, that)
}

goderive will then generate the following code in a derived.gen.go file in the same package:

func deriveEqual(this, that *MyStruct) bool {
	return (this == nil && that == nil) ||
		this != nil && that != nil &&
			this.Int64 == that.Int64 &&
			((this.StringPtr == nil && that.StringPtr == nil) ||
        (this.StringPtr != nil && that.StringPtr != nil && *(this.StringPtr) == *(that.StringPtr)))
}

View on Github

7 - Jennifer: Generate arbitrary Go code without templates.

Jennifer is a code generator for Go.

package main

import (
    "fmt"

    . "github.com/dave/jennifer/jen"
)

func main() {
	f := NewFile("main")
	f.Func().Id("main").Params().Block(
		Qual("fmt", "Println").Call(Lit("Hello, world")),
	)
	fmt.Printf("%#v", f)
}

Output:

package main

import "fmt"

func main() {
	fmt.Println("Hello, world")
}

Install

go get -u github.com/dave/jennifer/jen

Need help?

If you get stuck, have a question, would like a code review, or just want a chat: I'm happy to help! Feel free to open an issue, email me or mention @dave in your PR.

View on Github

8 - Goverter: Generate converters by defining an interface.

goverter is a tool for creating type-safe converters. All you have to do is create an interface and execute goverter. The project is meant as alternative to jinzhu/copier that doesn't use reflection.

Features

  • Automatic conversion of builtin types (house example), this includes:
    • slices, maps, named types, primitive types, pointers
    • structs with same fields
  • Extend parts of the conversion with your own implementation: Docs
  • Optional return of an error: Docs
  • Awesome error messages: mismatch type test
  • No reflection in the generated code

Usage

Create a go modules project if you haven't done so already

$ go mod init module-name

Add goverter as dependency to your project

$ go get github.com/jmattheis/goverter

Create your converter interface and mark it with a comment containing goverter:converter

input.go

package example

// goverter:converter
type Converter interface {
  Convert(source []Input) []Output
}

type Input struct {
  Name string
  Age int
}
type Output struct {
  Name string
  Age int
}

Run goverter:

$ go run github.com/jmattheis/goverter/cmd/goverter [package-name-in-full or relative-path-starts-with-a-dot]
# example
$ go run github.com/jmattheis/goverter/cmd/goverter github.com/jmattheis/goverter/example/simple
$ go run github.com/jmattheis/goverter/cmd/goverter ./example/simple

Note that relative path must start with a dot to indicate it is not a golang package. Omiting the dot (e.g. example/simple) may not work.

goverter created a file at ./generated/generated.go, it may look like this:

package generated

import simple "github.com/jmattheis/goverter/example/simple"

type ConverterImpl struct{}

func (c *ConverterImpl) Convert(source []simple.Input) []simple.Output {
  simpleOutputList := make([]simple.Output, len(source))
  for i := 0; i < len(source); i++ {
    simpleOutputList[i] = c.simpleInputToSimpleOutput(source[i])
  }
  return simpleOutputList
}
func (c *ConverterImpl) simpleInputToSimpleOutput(source simple.Input) simple.Output {
  var simpleOutput simple.Output
  simpleOutput.Name = source.Name
  simpleOutput.Age = source.Age
  return simpleOutput
}

View on Github

9 - GoWrap: Generate decorators for Go interfaces using simple templates.

GoWrap is a command line tool that generates decorators for Go interface types using simple templates. With GoWrap you can easily add metrics, tracing, fallbacks, pools, and many other features into your existing code in a few seconds.

Installation

go get -u github.com/hexdigest/gowrap/cmd/gowrap

Usage of gowrap

Usage: gowrap gen -p package -i interfaceName -t template -o output_file.go
  -g	don't put //go:generate instruction into the generated code
  -i string
    	the source interface name, i.e. "Reader"
  -o string
    	the output file name
  -p string
    	the source package import path, i.e. "io", "github.com/hexdigest/gowrap" or
    	a relative import path like "./generator"
  -t template
    	the template to use, it can be an HTTPS URL a local file or a
    	reference to one of the templates in the gowrap repository
  -v value
    	a key-value pair to parametrize the template,
    	arguments without an equal sign are treated as a bool values,
    	i.e. -v DecoratorName=MyDecorator -v disableChecks

This will generate an implementation of the io.Reader interface wrapped with prometheus metrics

  $ gowrap gen -p io -i Reader -t prometheus -o reader_with_metrics.go

This will generate a fallback decorator for the Connector interface that can be found in the ./connector subpackage:

  $ gowrap gen -p ./connector -i Connector -t fallback -o ./connector/with_metrics.go

Run gowrap help for more options

View on Github

10 - Interfaces: Command line tool for generating interface definitions.

Code generation tools for Go's interfaces.

Tools available in this repository:

Generates an interface for a named type.

Installation

~ $ go install github.com/rjeczalik/interfaces/cmd/interfacer@latest

Usage

~ $ interfacer -help
Usage of interfacer:
  -all
        Include also unexported methods.
  -as string
        Generated interface name. (default "main.Interface")
  -for string
        Type to generate an interface for.
  -o string
        Output file. (default "-")

View on Github

Thank you for following this article.

Related videos:

Write Less Code, Generate More

#go #golang #generator 

10 Popular Libraries for tools That Generate Go Code

Retrofit inspired HTTP Client Generator for Dart

Backfit

Backfit is a Retrofit inspired HTTP Client and API Service generator for Dart. This package works with its companion package called backfit.

Installation

Add the following to pubspec.yaml


dependencies:
  backfit: <latest_version>

dev_dependencies:
  backfit_generator: <latest_version>
  build_runner: <latest_version>

Usage

First create a BackFit client


import 'package:backfit/backfit.dart';

final client = BackfitClient(
    baseUrl: 'https://jsonplaceholder.typicode.com',
    interceptors: [HttpLogger()]);

Then create an interface annotated with BackfitService annotation, it takes base end point as an optional parameter.

posts_service.dart


import 'package:backfit/backfit.dart';

part 'posts_service.backfit.dart';

@BackfitService()
abstract class Posts {}

As per your API requirement create a model with serialization support. In this example, I am using freezed and json_serializable for it, however these are not necessary. You just need a toJson() method and fromJson factory or static method inside the model class

my_post.dart


import 'package:freezed_annotation/freezed_annotation.dart';

part 'my_post.freezed.dart';
part 'my_post.g.dart';

@freezed
class MyPost with _$MyPost {
  const factory MyPost({
    required int userId,
    required int id,
    required String title,
    required String body,
  }) = _MyPost;

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

Now go back to the api_service interface and add an abstract method defining the return type, endpoint and signature.

posts_service.dart


import 'package:backfit/backfit.dart';
import 'my_post.dart';

part 'posts_service.backfit.dart';

@BackfitService()
abstract class Posts {
  @Get('posts')
  Future<Response<List<MyPost>>> postsByUserId(@Query('userId') String userId); 
}

Note that the Response class mentioned here is from Backfit and not http and as such takes in your Model class as a type parameter for auto parsing.

Now if you are using flutter run -

  flutter pub run build_runner [build|watch] [OPTIONAL --delete-conflicting-outputs]

Or if you are working with dart only run -

  pub run build_runner [build|watch] [OPTIONAL --delete-conflicting-outputs]

This generates the following code -

posts_service.backfit.dart


// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'posts_service.dart';

// **************************************************************************
// BackfitGenerator
// **************************************************************************

class PostsService extends Posts with _$Posts {
  PostsService() {
    _client = BackfitClient();
  }

  PostsService.withClient(BackfitClient client) {
    _client = client;
  }
}

mixin _$Posts implements Posts {
  BackfitClient? _client;

  @override
  Future<Response<List<MyPost>>> postsByUserId(String userId) async {
    final res = await _client!
        .get(Uri.parse('${_client!.baseUrl}/posts/posts?userId=$userId'));

    return Response(
      data: res.body.isNotEmpty
          ? (json.decode(res.body) as List)
              .map((it) => MyPost.fromJson(it))
              .toList()
          : null,
      statusCode: res.statusCode,
      reasonPhrase: res.reasonPhrase,
      headers: HttpHeaders.fromMap(res.headers),
    );
  }
}

What's Next? Consume the Api Service wherever you want like this -


//in some injector 
final postsService = PostsService.withClient(client);


//inside a consumer
postsService.postsByUserId('1').catchError((e) {
  print(e.toString());
});

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add backfit

With Flutter:

 $ flutter pub add backfit

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

dependencies:
  backfit: ^0.0.2+8

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

Import it

Now in your Dart code, you can use:

import 'package:backfit/backfit.dart'; 

Download Details:

Author: astralstriker

Source Code: https://github.com/astralstriker/backfit

#dart #generator 

Retrofit inspired HTTP Client Generator for Dart
Mike  Kozey

Mike Kozey

1661883660

A Generator That Assists in Creating Typed Routes and Parameters

sunny_fluro_generator

Code generation tools to go along with the fluro router

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add sunny_fluro_generator

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

dependencies:
  sunny_fluro_generator: ^1.14.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:sunny_fluro_generator/build.dart';
import 'package:sunny_fluro_generator/field_annotation_generator.dart';
import 'package:sunny_fluro_generator/fluro_generator.dart';
import 'package:sunny_fluro_generator/read_metadata.dart';
import 'package:sunny_fluro_generator/route_generator.dart';
import 'package:sunny_fluro_generator/route_params_generator.dart';
import 'package:sunny_fluro_generator/routes_generator.dart';

example/README.md

example

A sample project using FlutterGen.

Getting Started

cd ../flutter_gen
make setup
make build-runner

Original article source at: https://pub.dev/packages/sunny_fluro_generator 

#flutter #dart #generator 

A Generator That Assists in Creating Typed Routes and Parameters
Rocio  O'Keefe

Rocio O'Keefe

1661530860

Knt_isolate Generator Is an Isolator Generator using Source_gen

TODO: Put a short description of the package here that helps potential users know whether this package might be useful for them.

Features

TODO: List what your package can do. Maybe include images, gifs, or videos.

Getting started

TODO: List prerequisites and provide or point to information on how to start using the package.

Usage

TODO: Include short and useful examples for package users. Add longer examples to /example folder.

const like = 'sample';

Additional information

TODO: Tell users more about the package: where to find more information, how to contribute to the package, how to file issues, what response they can expect from the package authors, and more.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add knt_isolate_generator

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

dependencies:
  knt_isolate_generator: ^1.0.0

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:knt_isolate_generator/knt_isolate_generator.dart';

Original article source at: https://pub.dev/packages/knt_isolate_generator

 #flutter #dart #generator 

Knt_isolate Generator Is an Isolator Generator using Source_gen
Hunter  Krajcik

Hunter Krajcik

1661301420

Borsh: Implementation Of The Borsh Serialization Scheme

Borsh serialization for dart

A code generator for borsh serialization. To use this you need the borsh_annotation.

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add borsh

With Flutter:

 $ flutter pub add borsh

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

dependencies:
  borsh: ^0.3.1

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

Import it

Now in your Dart code, you can use:

import 'package:borsh/borsh.dart';

Download Details:

Author: Cryptoplease
Source Code: https://github.com/cryptoplease/cryptoplease-dart 
License: MIT

#flutter #dart #generator 

Borsh: Implementation Of The Borsh Serialization Scheme
Hunter  Krajcik

Hunter Krajcik

1661297580

Annotation Used to Make A Dart Object Borsh Serializable

Annotations for the borsh generator


Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add borsh_annotation

With Flutter:

 $ flutter pub add borsh_annotation

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

dependencies:
  borsh_annotation: ^0.3.1+1

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

Import it

Now in your Dart code, you can use:

import 'package:borsh_annotation/borsh_annotation.dart';

See borsh generator.

Download Details:

Author: cryptoplease
Source Code: https://github.com/cryptoplease/cryptoplease-dart 
License: MIT

#flutter #dart #generator 

Annotation Used to Make A Dart Object Borsh Serializable
Dexter  Goodwin

Dexter Goodwin

1661219700

Generify: A Reusable Project Generator

generify 

A reusable project generator that copies file recursively, while replacing keywords from passed data.

Example

'use strict'

const generify = require('generify')
const source = './template'
const dest = '/tmp/generify-test'
const data = { hello: 'hello world' }

// without notification
generify(source, dest, data, function (err) {
  if (err) {
    console.log(err)
  } else {
    console.log('ok!')
  }
})

// with notification
generify(source, dest, data, onData, done)

function onData (file) {
  console.log('writing file')
}

function done (err) {
  if (err) {
    console.log(err)
  } else {
    console.log('ok!')
  }
}

This will replace all the __hello__ patterns found in all files with the 'hello world' string.

If the supplied data has a key transforms, with a hash of tranformation functions, then the found tokens will be used to run a corresponding transform on the supplied data. Example:

const data = {
  transforms: { foo: (data, context) => data.toUpperCase() },
  foo: 'foo'
}

// __foo__ => foo_transform(data = 'foo') => 'FOO'

The context object contains properties: source (input file path), dest (output file path), key (the matched key).

Files and Directories

files and directories located in the template folder may also be replaced. File and folder names wrapped with @ delimiters will be replaced.

Example

Given a template with:

/template/@foo@/@bar@.txt

and data:

const data = {
  foo: 'hello',
  bar: 'world'
}

The outputted file will be:

<dest>/hello/world.txt

__ handling

If a file begins with __ that will be automatically converted into a .. This is useful for generating .gitignore files.

If the supplied data has a key copyAsNamed, with an array of names, then the filenames in that list will not be processed through this rule. Each file name in the list should not include a path, e.g. ['__do-not-replace-underscores.js'].

Executable

generify also offers an executable that can be called with:

Usage: generify template destination [json file]

Where the json file contains the data to be replaced.

Acknowledgements

This project was kindly sponsored by nearForm.

Download Details:

Author: mcollina
Source Code: https://github.com/mcollina/generify 
License: MIT license

#javascript #generator 

Generify: A Reusable Project Generator
Hunter  Krajcik

Hunter Krajcik

1661184130

DF_builder: Small Package to Generate Code in A Simple Way

PART OF QUEEN PACKAGES 👑

Dart File Builder = DFB

Motivation

generating dart code with build_runner will not work if you are trying to convert json to dart since it requires dart code in the first place .

so i made this simple dart generator , mainly it meant for json to dart conversion to provide easy and simple way to create TR file for nations package also can be use for other use cases

Usage

  • start with DartFileBuilder
  • add what you need from ClassBuilder ClassGetter ClassProp
  • convert it to string using DartFileBuilder.toString()

Builders

DartFileBuilder

  • can add comments
  • can add exports
  • can add imports

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add df_builder

With Flutter:

 $ flutter pub add df_builder

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

dependencies:
  df_builder: ^0.0.4

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

Import it

Now in your Dart code, you can use:

import 'package:df_builder/df_builder.dart';

example/df_builder_example.dart

void main() {
  /// check out the package tests for more examples
}

Download Details:

Author: FlutterQueen
Source Code: https://github.com/FlutterQueen/df_builder 
License: MIT license

#flutter #dart #json #generator 

DF_builder: Small Package to Generate Code in A Simple Way
Reid  Rohan

Reid Rohan

1660641480

Eleventy: A Simpler Static Site Generator. An Alternative to Jekyll

eleventy 🕚⚡️🎈🐀

A simpler static site generator. An alternative to Jekyll. Written in JavaScript. Transforms a directory of templates (of varying types) into HTML.

Works with HTML, Markdown, JavaScript, Liquid, Nunjucks, Handlebars, Mustache, EJS, Haml, and Pug.

Installation

npm install @11ty/eleventy --save-dev

Read our Getting Started guide.

Tests

npm run test

Community Roadmap

Plugins

See the official docs on plugins.

Documentation

Download Details:

Author: 11ty
Source Code: https://github.com/11ty/eleventy 
License: MIT license

#javascript #templates #generator 

Eleventy: A Simpler Static Site Generator. An Alternative to Jekyll
Dexter  Goodwin

Dexter Goodwin

1660461900

Documentation Generator for TypeScript Declaration Files inspired

typejuice

Documentation generator for TypeScript Declaration Files inspired by godoc.

This repo contains two packages:

  • typejuice: the JavaScript API library
  • vite-plugin-typejuice: the Vite plugin for it.

Hat tip to Guido D'Orsi for the name idea (vitepress, typejuice).

npm i typejuice --save

Introduction

TypeScript Declaration Files have become a common addition to libraries, even those written in standard JavaScript, as a means of enhancing autocomplete behaviour of the exposed APIs.

There's a lot of overlap between documentation and these declaration files. This project attempts to bridge the gap by providing godoc-like comment extraction from .d.ts files while also inferring on types and signatures so you don't have to maintain the same information in two different places. It's a radically stripped down, minimalist analogue to typedoc.

Examples

Instead of using tags like @param, just have one function parameter per line

TypeScript Declaration File

declare class Client extends Dispatcher {
  // Extends: `undici.Dispatcher`
  // A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
  // Requests are not guaranteed to be dispatched in order of invocation.
  constructor(
    // Should only include the **protocol, hostname, and port**.
    url: string | URL,
    options?: Client.Options
  );

Generated Markdown

constructor

Multi-line comments on interface props

TypeScript Declaration File

declare namespace Client {
  export interface Options {
    // The timeout after which a request will time out, in milliseconds. 
    // Monitors time between receiving body data. Use `0` to disable it entirely.
    // Defaults to 30e3 (number), 30s in milliseconds
    bodyTimeout?: number | null;

    // The amount of time the parser will wait to receive the complete HTTP 
    // headers (Node 14 and above only). 
    // Defaults to 30e3 (number), 30s in milliseconds
    headersTimeout?: number | null;

Generated Markdown

interface

Supported Syntax

  • Top-level function and class declarations
  • Single-file namespace declarations
  • Constructor declarations – Primitive types such as string, number, boolean
  • Primitive values such as null and undefined
  • Union Types

TODO

  • Intersection Types
  • Type Aliases
  • Utility Types
  • Element type arrays or generic array types (type[], Array<type>)

Basic Usage

import TypeJuice from 'typejuice'

const tj = new TypeJuice('./sample.d.ts')

console.log(tj.toMarkdown())

Vite integration

In vite.config.js:

import { dirname } from 'path'
import { fileURLToPath } from 'url'
import TypeJuice from 'vite-plugin-typejuice'

export default {
  plugins: [
    TypeJuice({
      // Defaults to process.cwd()
      typeRoot: resolve(dirname(fileURLToPath(import.meta.url)), 'types'),
      // Defaults to only 'md'
      extensions: ['md'],
    })
  ],
}

In your Markdown files:

<<< typejuice:client.d.ts

This will insert the autogenerated markdown for client.d.ts under typeRoot.

Meta

Sponsored by NearForm.

Download Details:

Author: Galvez
Source Code: https://github.com/galvez/typejuice 

#javascript #typescript #generator 

Documentation Generator for TypeScript Declaration Files inspired

StaticWebPages.jl: A Black-box Generator for Static Websites

StaticWebPages.jl

A user-friendly static website generator written in Julia. No programming nor webdev skills required!!! Entirely Open-Source (GPLv2 licence)!

Although this generator originally targets academicians, it works out well for personal webpage and any static usage (front-end only) A more advanced static framework in Julia is available (cf Franklin.jl). For a full-stack web framework, please look at the great Genie.jl.

This generator is for you if

  • you want something simple to update and manage
  • responsive design (looks good on most devices)
  • want light load on the server and/or low bandwidth use
  • have no time/interest in making your own website by "hand"
  • new item/gadget access with a simple update in the julia command line

The beta only uses text files and command lines, but the first stable release will also integrate a graphical user interface (GUI).

I deeply apologize for those that tested the versions v0.1.x, as, from v0.2.0, the syntax has changed a lot. The reason is to add options to most components. It should not change drastically from now on.

How does it work

The user provides the content (text, images, files) and select which Items will display it. As simple as that. A full working example is provided here (or in the example folder). The result is available as http://baffier.fr

Installation

The only requirement is to install Julia and this package (preferably through the package interface of Julia). Please install the last stable release of Julia on the official download page.

In the Julia REPL (that you can launch as a standalone or call within a console), please enter Pkg REPL. To quote the package manager documentation:

Pkg comes with a REPL. Enter the Pkg REPL by pressing ] from the Julia REPL. To get back to the Julia REPL, press backspace or ^C.

The following code snippet update the general registry of Julia's packages, then install the StaticWebPages.jl package.

(@v1.5) pkg> up
(@v1.5) pkg> add StaticWebPages

You can check that the installation is complete and trigger a precompilation of the package (usually take a few minutes) by using the following command.

import StaticWebPages

Please note that precompilation occurs at first use after installation and updates.

The package can be use from the REPL, but we recommend it to be used through a script file as the run.jl presented below. Running the script should be as simple as writing the following command line.

julia run.jl

or in the REPL

include("run.jl")

Files organization

A compressed template can be found in the example/ folder as either template.tar or template.zip.

The two first following files are the only requirement. However, most users will prefer to provide some images/pictures and additional files such as a cv, a bibliography, and some downloadable content.

Local script file: run.jl

# import the website generator functions
import StaticWebPages
import StaticWebPages: local_info

## private information (local folders, connection infos, etc.)
# content and site paths are always required
local_info["content"] = "path/to/content_folder"
local_info["site"] = "path/to/site_folder"

# necessary only if using the upload_site function
local_info["protocol"] = "ftp"
local_info["user"] = "user"
local_info["password"] = "password"
local_info["server"] = "server_address"

# `rm_dir = true` will clean up the site folder before generating it again. Default to false.
# `opt_in = true` will add a link to this generator website in the side menu. Default to false.
StaticWebPages.export_site(d=local_info, rm_dir = true, opt_in = true)

## upload website (comment/delete if not needed)
# unfortunately does not work yet on windows system, please sync manually for the moment
StaticWebPages.upload_site(local_info)

Content folder

It must contain a content.jl file, and both an img and a files folders. Other content files, such as BibTeX bibliographic file should be put at the root of the folder (alongside content.jl). Please check the provided example if necessary.

## content.jl
######################################
# General information
######################################

# The pic.jpg file needs to be put in the img folder
info["avatar"] = "pic.jpg"

# The cv.pdf file needs to be put in the files folder
info["cv"] = "cv.pdf"

info["lang"] = "en"
info["name"] = "Jean-François BAFFIER"
info["title"] = "Baffier"

# The email is obfuscated using a reverse email writing. The email appear normally (re-reverse) through CSS.
# Although this is an effective technique against bots, it probably won't eventually.
# The user is free to add additional security such as replacing '@' by 'at'.
info["email"] = "jf@baffier.fr"

## icons to social networks in the side menu
# comment/delete the unwanted entries
info["researchgate"] = "https://www.researchgate.net/profile/Jean_Francois_Baffier"
info["googlescholar"] = "https://scholar.google.fr/citations?user=zo7FgSIAAAAJ&hl=fr"
info["orcid"] = "https://orcid.org/0000-0002-8800-6356"
info["dblp"] = "https://dblp.org/pid/139/8142"
info["linkedin"] = "https://www.linkedin.com/in/jeanfrancoisbaffier/"
info["github"] = "https://github.com/Azzaare"
info["twitter"] = "https://twitter.com/bioazzaare"

# The navigation side-bard default to 250px. If the content above doesn't fit, it be set to another length (in px)
info["nav_width"] = "300"

######################################
# publications.html
######################################
page(
    title="publications",
    sections=[
        Section(
            title="Publications",
            items=Publications("publications.bib")
        )
    ]
)

Themes

The only available theme for the moment is using Zurb foundation responsive front-end. Customization of this theme and addition of other themes are expected in a near future (contributions/suggestions/requests are welcome).

Items

Items are guaranteed to be compatible with the main theme (and hopefully new ones will be too).

Publications : a bibliography based on a bibliography file (uses Bibliography.jl)

# Simply provide a BibTeX file (usually .bib)
# Path is based on the root of the content folder
Publications("publications.bib")

To add labels to the publications entries, please add a swp-labels field to your entries. A labels field is also accepted, but will also appear in the bibTeX citation generated for that article. For instance,

@inproceedings{parmentier2019introducing,
    title={Introducing multilayer stream graphs and layer centralities},
    author={Parmentier, Pimprenelle and Viard, Tiphaine and Renoust, Benjamin and Baffier, Jean-Francois},
    booktitle={International Conference on Complex Networks and Their Applications},
    pages={684--696},
    year={2019},
    organization={Springer},
    doi = {10.1007/978-3-030-36683-4_55},
    swp-labels = {conference, preprint, software}
}

Image of a Publication Item

The attribution of colors is done automatically (within the limit of 22 labels, please issue a request if you need more ...)

Deck of Cards : a list of ordered and clearly separate cards

Deck( # Start of the list
    Card( # generic
        "Left",
        "Right",
        "Title",
        "Content"
    ),
    Card( # example
        "2019",
        "current",
        "Postdoctoral Researcher",
        "RIKEN Center for Advanced Intelligence (AIP)"
    )
 ) # End of the list

Image of Card Items

GitRepo : a list of GitHub repository displayed similarly to BibTeX entries

gitrepo = GitRepo( # currently work only with GitHub
    "Azzaare/CompressedStacks.cpp",
    "Humans-of-Julia/StaticWebPages.jl",
    "Humans-of-Julia/Bibliography.jl",
    "Humans-of-Julia/BibParser.jl",
    "Humans-of-Julia/BibInternal.jl",
    "JuliaGraphs/LightGraphs.jl",
    "JuliaGraphs/LightGraphsExtras.jl",
    "JuliaGraphs/SNAPDatasets.jl",
    "Azzaare/PackageStream.jl"
)

Image of a Git Item

Please note that GitHub will restrict unidentified requests to a certain amount per IP within a time limit (that I don't know the value). If it happens, a message error from GitHub API will be returned.

To circumvent this issue, you can uncomment the line local_info["auth_tokens"] = "PATH/TO/token.jl' in run.jl (or add it if necessary) and edit the token.jl by updating your Personnal Access Token.

token.jl aims to store all authentication tokens (for now, just GitHub). It content must be as follow (it is a simple variable containing your PAT):

# WARNING!
# YOUR TOKENS SHOULD NEVER BE SHARED! IF YOU USE GIT, DON'T FORGET TO ADD `token.jl` TO YOUR `.gitignore` FILE!
# YOU CAN ALSO STORE `token.jl` OUTSIDE OF THE STATICWEBPAGES FOLDER!

github_pat = "YOUR_PERSONAL_ACCESS_TOKEN" 

If the token is not valid, a 401: Bad Creditential error from GitHUb API will be returned.

As the comment states, take care not to push your token to your git repo! A good practice could be to store token.jl outside of your git project.

Block : Block of paragraphs with optional images on the side

# Examples with and without images
biography = Block(
    paragraphs(
    """
   Jean-François Baffier is an academic researcher at the RIKEN Center for Advanced Intelligence Project (AIP), and a consultant in Artificial Intelligence, Big Data Science, Data Structures, and Algorithms. As an academic, he gives back to society through fundamental research in computer science supplemented by open source libraries and softwares.
    """,
    """
    paragraph 2
    """,
    """
    paragraph 3
    """,
    """
    Jean-François implemented the StaticWebPages.jl package that was used to generate this website using a simple content file. This is a dummy email: $(email("dummy@example.purpose"))
    """
    ),
    images(
        Image("cs.png", "Compressed Stack"),
        Image("knowledge.png", "Flow of Knowledge")
    )
)

research = Block(
    paragraphs(
        """
        Principal Research Projects: Network Interdiction, Compressed Data Structures, Modern Academics, Explainable AI. Other research interest includes Graph Theory, Geometry, Optimization, and Games.
        """,
        """
        All of this research is supported by Open-Source Softwares and published as peer-review academic papers. 
        """
    ),
    images()
)

Image of a Block Item

TimeLines : a list of continuous items

grants = TimeLine(
    Dot(
        "Top",
        "Title",
        "Content"
    ),
    Dot(
        "2012-2015",
        "MEXT Scholarship",
        "The Monbukagakusho Scholarship is an academic scholarship offered by the Japanese Ministry of Education, Culture, Sports, Science and Technology (MEXT)."
    )
)

Image of a TimeLine Item

Nest! A container to list several items within the same section

# Nest will take a tuple of any Items (except itself)
positions_grants = Double(
    Section(
        title="Positions and grants",
        items=Nest(work_cards, grants)
    ),
    Section(title="Research Topics", items=research)
)

Pages

A page is composed of a name and a list of sections which can each be either single or double column. Each section is either a single Item or a pair of Items.

A publication page with only one single column section (by default, publications spread over two columns on large screens)

######################################
# publications.html
#   option 1: background for the page is set to start with white to emphasize the bibliographic items
######################################
page(
    title="publications",
    background=bg_white,
    sections=[
        Section(
            title="Publications",
            items=Publications("publications.bib")
        )
    ]
)

An index page with a TextSection and a double column (Card, TimeLine)

######################################
# index.html
# biography
# academic positions | honors, awards, and grants
######################################

# using previously defined items, we can define sections
section_biography = Section(title="Biography", items=biography)
positions_grants = Double(
    Section(title="Positions", items=work_cards),
    Section(title="Grants", items=grants)
)

# the next line will add the index page to the generated content
page(
    title="index",
    sections=[section_biography, positions_grants]
)

The hide option for page and Section

# Both page() and Section() can take the hide option
# If a page is hidden, it will not be generated, but it will still appear in the side menu
# If a section is hidden, it will just not appear (and the content will not be generated, including request to external API, such as GitHub)

page(
    title="software",
    background=bg_white,
    sections=[
        Section(
            title="Software",
            hide=true, # default to false
            items=github,
        )
    ]
)

Inline components

Some components can be inserted within the content of usual Items, such as Block, Card, Dot. Currently, only link and email are supported.

Email can obfuscated (default), or not ...

email("dummy@example.purpose") # obfuscated
email(
    "dummy@example.purpose";
    content = "content that appears as the email link", # ignored if obfuscated
    obfuscated = false
    )

Link can be an internal or an external link

link("research project", "research.hmtl") # inner link
link("StaticWebPages.jl", "https://github.com/Humans-of-Julia/StaticWebPages.jl")

The main theme, and some items (BibTeX, Card, TimeLine) are inspired by the Word Press Faculty template of owwwlab, also under GPLv2. All elements inspired from that template can be found in the HTML/CSS code associated with those items.

Download Details:

Author: Humans-of-Julia
Source Code: https://github.com/Humans-of-Julia/StaticWebPages.jl 
License: GPL-2.0 license

#julia #generator #websites 

StaticWebPages.jl: A Black-box Generator for Static Websites
Gordon  Murray

Gordon Murray

1659583740

Assets_generator_by_zpdl: Flutter Assets Code Generator

Assets generator

Provides [Dart Build System] builders for handling assets.

The builders generate code when they find members annotated with classes defined in [package:assets_annotation_by_zpdl]. Generates assets in pubspec.yaml

  • To generate assets pubspec.yaml in for a class, annotate it with @AssetsAnnotation.

Install

Add the following to your pubspec.yaml:

dependencies:
  assets_annotation_by_zpdl: ^1.1.0

dev_dependencies:
  assets_generator_by_zpdl: ^1.1.2
  build_runner: <latest>

Usage

1. Create a class with @AssetsAnnotation

import 'package:assets_annotation_by_zpdl/assets_annotation_by_zpdl.dart';

part 'assets.g.dart';

@AssetsAnnotation.camelCase(version: '1.0.0')
class Assets {
  const Assets();
}

2. Generate your assets

Run the following command to generate a lib/assets.g.dart file :

flutter packages pub run build_runner build

3. Use your assets

const assets = Assets();

print(assets.image.image);
print(assets.animation.animation);

Annotation values

  1. isCamelCase : The first letter is written in lowercase. The first letter of the rest of the following words is capitalized.
  2. isSnakeCase : Place an underline in the middle of each word joined.
  3. version: Used for update

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add assets_generator_by_zpdl

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

dependencies:
  assets_generator_by_zpdl: ^1.1.2

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:assets_generator_by_zpdl/assets_generator_by_zpdl.dart';

example/lib/main.dart

import 'package:assets_annotation_by_zpdl/assets_annotation_by_zpdl.dart';
import 'package:flutter/material.dart';

part 'main.g.dart';

void main() {
  runApp(const MyApp());
}

/// original naming
@AssetsAnnotation(version: '1.0.0')
class Assets {
  const Assets();
}

const assets = Assets();

/// camel case naming
@AssetsAnnotation.camelCase(version: '1.0.0')
class AssetsCamel {
  const AssetsCamel();
}

const assetsCamel = AssetsCamel();

/// snake case naming
@AssetsAnnotation.snakeCase(version: '1.0.0')
class AssetsSnake {
  const AssetsSnake();
}

const assetsSnake = AssetsSnake();

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'assets generator by zpdl Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key,}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Assets generator',)),
      body: ListView(
        children: [
          _buildListTile(
              assets.image.uog____61___264____32__1____920,
              assetsCamel.image.og61264321920,
              assetsSnake.image.og____61___264____32__1____920),
          _buildListTile(
              assets.image.camelAlbum.iconCalendarJpg,
              assetsCamel.image.camelAlbum.iconCalendarJpg,
              assetsSnake.image.camel_album.icon_calendar_jpg),
          _buildListTile(
              assets.image.snake_guide.snake_guide,
              assetsCamel.image.snakeGuide.snakeGuide,
              assetsSnake.image.snake_guide.snake_guide),
          _buildListTile(
              assets.camelGuide,
              assetsCamel.camelGuide,
              assetsSnake.camel_guide),
        ],
      ),
    );
  }

  Widget _buildListTile(String assets, String assetsCamel, String assetsSnake) {
    return ListTile(
      title: Text(assets),
      subtitle: Text('$assetsCamel\n$assetsSnake'),
      leading: Image.asset(assets),
    );
  }
}

Original article source at: https://pub.dev/packages/assets_generator_by_zpdl 

#flutter #dart #generator 

Assets_generator_by_zpdl: Flutter Assets Code Generator
Monty  Boehm

Monty Boehm

1659510360

Clang.jl: Julia interface to Libclang

Clang  

This package provides a Julia language wrapper for libclang: the stable, C-exported interface to the LLVM Clang compiler. The libclang API documentation provides background on the functionality available through libclang, and thus through the Julia wrapper. The repository also hosts related tools built on top of libclang functionality.

Installation

pkg> add Clang

If you'd like to use the old generator(Clang.jl v0.13), please checkout this branch for the documentation. Should you have any questions on how to upgrade the generator script, feel free to submit a post/request in the Discussions area.

Binding Generator

Clang.jl provides a module Clang.Generators for auto-generating C library bindings for Julia language from C headers.

Quick start

Write a config file generator.toml:

[general]
library_name = "libclang"
output_file_path = "./LibClang.jl"
module_name = "LibClang"
jll_pkg_name = "Clang_jll"
export_symbol_prefixes = ["CX", "clang_"]

and a Julia script generator.jl:

using Clang.Generators
using Clang.LibClang.Clang_jll  # replace this with your jll package

cd(@__DIR__)

include_dir = normpath(Clang_jll.artifact_dir, "include")
clang_dir = joinpath(include_dir, "clang-c")

options = load_options(joinpath(@__DIR__, "generator.toml"))

# add compiler flags, e.g. "-DXXXXXXXXX"
args = get_default_args()  # Note you must call this function firstly and then append your own flags
push!(args, "-I$include_dir")

headers = [joinpath(clang_dir, header) for header in readdir(clang_dir) if endswith(header, ".h")]
# there is also an experimental `detect_headers` function for auto-detecting top-level headers in the directory
# headers = detect_headers(clang_dir, args)

# create context
ctx = create_context(headers, args, options)

# run generator
build!(ctx)

Please refer to this toml file for a full list of configuration options.

Examples

The generator is currently used by several projects and you can take them as examples.

Author: JuliaInterop
Source Code: https://github.com/JuliaInterop/Clang.jl 
License: MIT license

#julia #generator 

Clang.jl: Julia interface to Libclang
Gordon  Murray

Gordon Murray

1659410940

Generate Boilerplate Code for using Action_box Package

A library for Dart developers.

Usage

A simple usage example:

import 'package:action_box/action_box.dart';
//add generated file
import 'example.config.dart';

@ActionBoxConfig(
    //actionBoxType: 'ActionBox',
    //actionRootType: 'ActionRoot',
    generateSourceDir: ['*']
)
final actionBox = ActionBox.shared();

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add action_box_generator

With Flutter:

 $ flutter pub add action_box_generator

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

dependencies:
  action_box_generator: ^0.0.30

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

Import it

Now in your Dart code, you can use:

import 'package:action_box_generator/action_box_generator.dart';

example/action_box_generator_example.dart

import 'package:action_box/action_box.dart';
//add
import 'action_box_generator_example.a.b.dart';

@ActionBoxConfig(
    // actionBoxType: 'ActionBox', //default value
    // actionRootType: 'ActionRoot',  //default value
    generateSourceDir: ['lib', 'example'])
final actionBox = ActionBox.shared();

//How to use
void main() {
  var bag = DisposeBag();
  actionBox((d) => d.ui.common.etc.e);
  actionBox((d) => d.ui.common.e);
  actionBox((d) => d.gateway.common.e);
  actionBox((d) => d.gateway.common.etc.c);
  //request data
  actionBox((root) => root.valueConverter.getStringInStringOutValue)
      .go(param: 'test', channel: (c) => c.exCh1);

  //subscribe result
  actionBox((d) => d.valueConverter.getStringInStringOutValue)
      .map(channel: (c) => c.exCh1 | c.exCh2)
      .listen((result) {
    print(result);
  }).disposedBy(bag);

  //call dispose method when completed
  //bag.dispose();
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

Author: Yookjy
Source Code: https://github.com/yookjy/action_box_generator 
License: MIT license

#flutter #dart #generator 

Generate Boilerplate Code for using Action_box Package