TypeTree.jl: Julia Type Tree Display Micro Package

TypeTree.jl

Julia type tree displaying micro package

Description

TypeTree.jl is a microscopic package written in the Julia language aimed at providing the simple utility of text-based visual type tree inspection to the human eye, i.e., programmers. It defines and exports the tt function:

julia> using TypeTree

julia> tt
tt (generic function with 2 methods)

The tt function returns a Vector{String} of type entries formatted as a tree for human (programmer) inspection:

julia> tt(Signed)
7-element Vector{String}:
 "Signed\n"
 " ├─ BigInt\n"
 " ├─ Int128\n"
 " ├─ Int16\n"
 " ├─ Int32\n"
 " ├─ Int64\n"
 " └─ Int8\n"

Its output can be simply read on the Julia REPL screen, or be printed:

julia> print(join(tt(Integer), ""))
Integer
 ├─ Bool
 ├─ Signed
 │   ├─ BigInt
 │   ├─ Int128
 │   ├─ Int16
 │   ├─ Int32
 │   ├─ Int64
 │   └─ Int8
 └─ Unsigned
     ├─ UInt128
     ├─ UInt16
     ├─ UInt32
     ├─ UInt64
     └─ UInt8

Concrete types can be filtered off and ASCII-only outputs can be produced:

julia> print(join(tt(Number, uni=false, concrete=false), ""))
Number
 \-- Real
     +-- AbstractFloat
     +-- AbstractIrrational
     \-- Integer
         +-- Signed
         \-- Unsigned

Type names can be displayed without module prefixes by using the mod= option.

julia> print(tt(Base.LibuvStream)...)
Base.LibuvStream
 ├─ Base.BufferStream
 ├─ Base.PipeEndpoint
 ├─ Base.TTY
 ├─ Sockets.TCPSocket
 └─ Sockets.UDPSocket

julia> print(tt(Base.LibuvStream; mod=Base)...)
LibuvStream
 ├─ BufferStream
 ├─ PipeEndpoint
 ├─ TTY
 ├─ Sockets.TCPSocket
 └─ Sockets.UDPSocket

About

Author

Prof. C. Naaktgeboren, PhD. Lattes.

Federal University of Technology, Paraná (site), Guarapuava Campus.

NaaktgeborenC <dot!> PhD {at!} gmail [dot!] com

Citations

How to cite this project:

@Misc{2021-NaaktgeborenC-TypeTree,
  author       = {C. Naaktgeboren},
  title        = {{TypeTree.jl} -- Julia type tree displaying micro package},
  howpublished = {Online},
  year         = {2021},
  journal      = {GitHub repository},
  publisher    = {GitHub},
  url          = {https://github.com/cnaak/TypeTree.jl},
}

Download Details:

Author: Cnaak
Source Code: https://github.com/cnaak/TypeTree.jl 
License: MIT license

#julia #type #tree 

TypeTree.jl: Julia Type Tree Display Micro Package
Nat  Grady

Nat Grady

1664253120

jsTree: R Htmlwidget for inspecting Heirachal Structures

jsTree

R htmlwidget for inspecting heirachal structures with the ‘jQuery’ ‘jsTree’ Plugin.

Installation

#install.packages('jsTree')
remotes::install_github('yonicd/jsTree')

Conventional Use

library(jsTree)
data(states)
data(state_bird)

collapse columns to text (with sep “/”)

nested_string <- apply(states,1,paste,collapse='/')
jsTree(nested_string)

Add tooltips to state names with the state bird

jsTree(nested_string,tooltips = state_bird)

initialize tree with checked boxes for certain fields

nodestate1 <- states$variable=='Area'
jsTree(nested_string,nodestate=nodestate1)
nodestate2 <- states$variable=='Area'&grepl('^M',states$state.name)
jsTree(nested_string,nodestate=nodestate2)
nodestate3 <- states$variable %in% c('Murder') & states$value >= 10
nodestate4 <- states$variable %in% c('HS.Grad') & states$value <= 55
jsTree(nested_string,nodestate=nodestate3|nodestate4)

change the order of the hierarchy

nested_string2 <- apply(states[,c(4,1,2,3,5)],1,paste,collapse='/')
jsTree(nested_string2)

Use other delimiters to define the heirarchy

nested_string <- apply(states,1,paste,collapse='|-|')
jsTree(nested_string,sep = '|-|')

Interacting with remote repositories

Preview a github repo without cloning it

remotes::install_github('yonicd/vcs')

#get repo master branch directory structure
  vcs::navigate_remote('tidyverse/ggplot2')

Search text in files of a repo without cloning it

Download Details:

Author: Yonicd
Source Code: https://github.com/yonicd/jsTree 
License: View license 

#r #tree #html #widgets 

jsTree: R Htmlwidget for inspecting Heirachal Structures

6 Popular Node.js Tree Structure Libraries

In today's post we will learn about 6 Popular Node.js Tree Structure Libraries.

A tree view or a tree structure is a UI component that provides a hierarchical view of your complex data structures. Some items in a tree view may have a number of subitems, and the user can expand & collapse them by clicking on the parent node.

1 - Tree-model-js

Manipulate and traverse tree-like structures in javascript

Installation

Node

TreeModel is available as an npm module so you can install it with npm install tree-model and use it in your script:

var TreeModel = require('tree-model'),
    tree = new TreeModel(),
    root = tree.parse({name: 'a', children: [{name: 'b'}]});

TypeScript

Type definitions are already bundled with the package, which should just work with npm install.

You can maually find the definition files in the types folder.

View on Github

2 - Functional-red-black-tree

A purely functional red-black tree data structure.

Install

npm install functional-red-black-tree

Example

Here is an example of some basic usage:

//Load the library
var createTree = require("functional-red-black-tree")

//Create a tree
var t1 = createTree()

//Insert some items into the tree
var t2 = t1.insert(1, "foo")
var t3 = t2.insert(2, "bar")

//Remove something
var t4 = t3.remove(1)

API

var createTree = require("functional-red-black-tree")

View on Github

3 - Splay-tree

Fast splay-tree data structure

Install

npm i -S splaytree
import SplayTree from 'splaytree';
const tree = new SplayTree();

Or get it from CDN

<script src="https://unpkg.com/splaytree"></script>
<script>
  var tree = new SplayTree();
  ...
</script>

Example

import Tree from 'splaytree';

const t = new Tree();
t.insert(5);
t.insert(-10);
t.insert(0);
t.insert(33);
t.insert(2);

console.log(t.keys()); // [-10, 0, 2, 5, 33]
console.log(t.size);   // 5
console.log(t.min());  // -10
console.log(t.max());  // -33

t.remove(0);
console.log(t.size);   // 4

View on Github

4 - Node-interval-tree

An Interval Tree data structure.

Usage

import IntervalTree from 'node-interval-tree'
const intervalTree = new IntervalTree<string>()

Insert

intervalTree.insert(low, high, 'foo')

Insert an interval with associated data into the tree. Intervals with the same low and high value can be inserted, as long as their data is different. Data can be any JS primitive or object. low and high have to be numbers where low <= high (also the case for all other operations with low and high). Returns true if successfully inserted, false if nothing inserted.

Search

intervalTree.search(low, high)

Search all intervals that overlap low and high arguments, both of them inclusive. Low and high values don't need to be in the tree themselves. Returns an array of all data objects of the intervals in the range [low, high]; doesn't return the intervals themselves.

View on Github

5 - Array-to-tree

Convert a plain array of nodes (with pointers to parent nodes) to a nested data structure

Installation

$ npm install array-to-tree --save

Usage

var arrayToTree = require('array-to-tree');

var dataOne = [
  {
    id: 1,
    name: 'Portfolio',
    parent_id: undefined
  },
  {
    id: 2,
    name: 'Web Development',
    parent_id: 1
  },
  {
    id: 3,
    name: 'Recent Works',
    parent_id: 2
  },
  {
    id: 4,
    name: 'About Me',
    parent_id: undefined
  }
];

arrayToTree(dataOne);

/*
 * Output:
 *
 * Portfolio
 *   Web Development
 *     Recent Works
 * About Me
 */

var dataTwo = [
  {
    _id: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c',
    name: 'Portfolio',
    parent: null
  },
  {
    _id: 'ec666030-7f8f-11e3-ae96-0123456789ab',
    name: 'Web Development',
    parent: 'ec654ec1-7f8f-11e3-ae96-b385f4bc450c'
  },
  {
    _id: 'ec66fc70-7f8f-11e3-ae96-000000000000',
    name: 'Recent Works',
    parent: 'ec666030-7f8f-11e3-ae96-0123456789ab'
  },
  {
    _id: '32a4fbed-676d-47f9-a321-cb2f267e2918',
    name: 'About Me',
    parent: null
  }
];

arrayToTree(dataTwo, {
  parentProperty: 'parent',
  customID: '_id'
});

/*
 * Output:
 *
 * Portfolio
 *   Web Development
 *     Recent Works
 * About Me
 */

View on Github

6 - Treeize

Converts row data (in JSON/associative array format) to tree structure based on column naming conventions.

Installation

npm install treeize

Why?

Because APIs usually require data in a deep object graph/collection form, but SQL results (especially heavily joined data), excel, csv, and other flat data sources that we're often forced to drive our applications from represent data in a very "flat" way. Treeize takes this flattened data and based on simple column/attribute naming conventions, remaps it into a deep object graph - all without the overhead/hassle of hydrating a traditional ORM.

What it does...

// Treeize turns flat associative data (as from SQL queries) like this:
var peopleData = [
  {
    'name': 'John Doe',
    'age': 34,
    'pets:name': 'Rex',
    'pets:type': 'dog',
    'pets:toys:type': 'bone'
  },
  {
    'name': 'John Doe',
    'age': 34,
    'pets:name': 'Rex',
    'pets:type': 'dog',
    'pets:toys:type': 'ball'
  },
  {
    'name': 'Mary Jane',
    'age': 19,
    'pets:name': 'Mittens',
    'pets:type': 'kitten',
    'pets:toys:type': 'yarn'
  },
  {
    'name': 'Mary Jane',
    'age': 19,
    'pets:name': 'Fluffy',
    'pets:type': 'cat'
  }
];


// ...or flat array-of-values data (as from CSV/excel) like this:
var peopleData = [
  ['name', 'age', 'pets:name', 'pets:type', 'pets:toys:type'], // header row
  ['John Doe', 34, 'Rex', 'dog', 'bone'],
  ['John Doe', 34, 'Rex', 'dog', 'ball'],
  ['Mary Jane', 19, 'Mittens', 'kitten', 'yarn'],
  ['Mary Jane', 19, 'Fluffy', 'cat', null]
];


// ...via a dead-simple implementation:
var Treeize   = require('treeize');
var people    = new Treeize();

people.grow(peopleData);


// ...into deep API-ready object graphs like this:
people.getData() == [
  {
    name: 'John Doe',
    age: 34,
    pets: [
      {
        name: 'Rex',
        type: 'dog',
        toys: [
          { type: 'bone' },
          { type: 'ball' }
        ]
      }
    ]
  },
  {
    name: 'Mary Jane',
    age: 19,
    pets: [
      {
        name: 'Mittens',
        type: 'kitten',
        toys: [
          { type: 'yarn' }
        ]
      },
      {
        name: 'Fluffy',
        type: 'cat'
      }
    ]
  }
];

View on Github

Thank you for following this article. 

#node #tree #structure 

6 Popular Node.js Tree Structure Libraries
Hunter  Krajcik

Hunter Krajcik

1662052920

A Simple Widget to Count The Amount Of Nested Widget Tree

widget_tree_depth_counter

Widget Tree Depth Counter

WidgetTreeDepthCounter is a simple widget to count the amount of nested widget tree, useful in the dynamic construction of the interface when it is important to know the depth of widget.

Image
WidgetTreeDepthCounter

Features

  • count of the depth of the widget with respect to the tree (all uses of WidgetTreeDepthCounter in the current tree are counted, the other types of widgets are not counted)

This widget can be used conveniently in such cases:

Dynamically manage the colors of widgets based on their position in the tree

in an app that manages chapter numbers it is very easy to renumber them in case a chapter is removed.

...

Many other cases where it is very difficult to manage a widget through fixed parameters to be managed based on the construction of the tree.

Usage

Make sure to check out the examples on GitHub.

Image
Example of operation in a widget tree

Installation

From pubspec.yaml

Add the following line to pubspec.yaml:

dependencies:
  widget_tree_depth_counter: <last-release>

and

flutter pub get

From cli

run following command:

flutter pub add widget_tree_depth_counter

Basic setup

Complete example available here.

ParentWidget(
  child: WidgetTreeDepthCounter(
    builder: (context, counter) => //counter=0
      Container(
        color: Theme.of(context)
          .primaryColor
          .withOpacity(counter * 0.05 + 0.05),
          child: WidgetTreeDepthCounter(
            builder: (context, counter) =>//counter=1
                Container(
                    color: Theme.of(context)
                    .primaryColor
                        .withOpacity(counter * 0.05 + 0.05),
                ),
          ),
      ),
  ),
),

WidgetTreeDepthCounter Properties

  • builder: Function called at layout time to construct the widget tree, return Widget.
  • count: With this parameter it's possible define or overwrite the current depth count value.

 

Use current counter value during build WidgetTreeDepthCounter

WidgetTreeDepthCounter uses Provider library to count the depth, but if it is necessary to access the current value to perform a sum (for example), it is possible to retrieve the count value through the `Provider 'functions:


WidgetTreeDepthCounter(
            count: context.read<DepthCounter>().value + 2,
            builder: (context, counter) =>
                Text(counter.toString()),
          )

Obviously to access the value via context.read<DepthCounter>() it is necessary that at least one WidgetTreeDepthCounter is present in the tree and provider package is required.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add widget_tree_depth_counter

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

dependencies:
  widget_tree_depth_counter: ^1.0.1

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

Import it

Now in your Dart code, you can use:

import 'package:widget_tree_depth_counter/widget_tree_depth_counter.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:widget_tree_depth_counter/widget_tree_depth_counter.dart';
import 'package:widget_tree_depth_counter_example/helper/colored_container.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'WidgetTreeDepthCounter Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

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

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Widget tree depth counter'),
        centerTitle: true,
      ),
      body: Container(
        child: Center(
          child: ColorExample(),
        ),
      ),
    );
  }
}

class ColorExample extends StatelessWidget {
  const ColorExample({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) => Container(
        width: constraints.maxWidth * .9,
        height: constraints.maxHeight * .9,
        child: WidgetTreeDepthCounter(
          builder: (context, counter) => ColoredContainer(
            counter: counter,
            color: Theme.of(context)
                .primaryColor
                .withOpacity(counter * 0.05 + 0.05),
            child: WidgetTreeDepthCounter(
              builder: (context, counter) => ColoredContainer(
                counter: counter,
                color: Theme.of(context)
                    .primaryColor
                    .withOpacity(counter * 0.05 + 0.05),
                child: WidgetTreeDepthCounter(
                  builder: (context, counter) => ColoredContainer(
                    counter: counter,
                    color: Theme.of(context)
                        .primaryColor
                        .withOpacity(counter * 0.05 + 0.05),
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: WidgetTreeDepthCounter(
                            builder: (context, counter) => ColoredContainer(
                              counter: counter,
                              color: Theme.of(context)
                                  .primaryColor
                                  .withOpacity(counter * 0.05 + 0.05),
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 3,
                          child: WidgetTreeDepthCounter(
                            builder: (context, counter) => ColoredContainer(
                              counter: counter,
                              color: Theme.of(context)
                                  .primaryColor
                                  .withOpacity(counter * 0.05 + 0.05),
                              child: WidgetTreeDepthCounter(
                                builder: (context, counter) => ColoredContainer(
                                  counter: counter,
                                  color: Theme.of(context)
                                      .primaryColor
                                      .withOpacity(counter * 0.05 + 0.05),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: WidgetTreeDepthCounter(
                                          builder: (context, counter) =>
                                              ColoredContainer(
                                            counter: counter,
                                            color: Theme.of(context)
                                                .primaryColor
                                                .withOpacity(
                                                    counter * 0.05 + 0.05),
                                            child: Column(
                                              children: [
                                                Expanded(
                                                  child: WidgetTreeDepthCounter(
                                                    builder:
                                                        (context, counter) =>
                                                            ColoredContainer(
                                                      counter: counter,
                                                      color: Theme.of(context)
                                                          .primaryColor
                                                          .withOpacity(
                                                              counter * 0.05 +
                                                                  0.05),
                                                    ),
                                                  ),
                                                ),
                                                Expanded(
                                                  child: WidgetTreeDepthCounter(
                                                    builder:
                                                        (context, counter) =>
                                                            ColoredContainer(
                                                      counter: counter,
                                                      color: Theme.of(context)
                                                          .primaryColor
                                                          .withOpacity(
                                                              counter * 0.05 +
                                                                  0.05),
                                                      child:
                                                          WidgetTreeDepthCounter(
                                                        builder: (context,
                                                                counter) =>
                                                            ColoredContainer(
                                                          counter: counter,
                                                          color: Theme.of(
                                                                  context)
                                                              .primaryColor
                                                              .withOpacity(
                                                                  counter *
                                                                          0.05 +
                                                                      0.05),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: WidgetTreeDepthCounter(
                                          builder: (context, counter) =>
                                              ColoredContainer(
                                            counter: counter,
                                            color: Theme.of(context)
                                                .primaryColor
                                                .withOpacity(
                                                    counter * 0.05 + 0.05),
                                            child: Row(
                                              children: [
                                                Expanded(
                                                  child: WidgetTreeDepthCounter(
                                                    builder:
                                                        (context, counter) =>
                                                            ColoredContainer(
                                                      counter: counter,
                                                      color: Theme.of(context)
                                                          .primaryColor
                                                          .withOpacity(
                                                              counter * 0.05 +
                                                                  0.05),
                                                    ),
                                                  ),
                                                ),
                                                Expanded(
                                                  child: WidgetTreeDepthCounter(
                                                    builder:
                                                        (context, counter) =>
                                                            ColoredContainer(
                                                      counter: counter,
                                                      color: Theme.of(context)
                                                          .primaryColor
                                                          .withOpacity(
                                                              counter * 0.05 +
                                                                  0.05),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

📚 My other packages

Flutter

PackageVerisonScoreLikesTestCoverage
Pub Packagepub pointslikes  
Pub Packagepub pointslikes  
Pub Packagepub pointslikes  
Pub Packagepub pointslikes  

Dart

PackageVerisonScoreLikesTestCoverage
Pub Packagepub pointslikesTest CIcodecov

Download Details:

Author: Rickypid
Source Code: https://github.com/rickypid/widget_tree_depth_counter 
License: BSD-3-Clause license

#flutter #dart #widget #tree 

A Simple Widget to Count The Amount Of Nested Widget Tree
Nat  Grady

Nat Grady

1661252125

ShinyTree: Shiny integration with The jsTree Library

shinyTree

The shinyTree package enables Shiny application developers to use the jsTree library in their applications.

shiny tree screenshot

Installation

You can install the latest development version of the code using the devtools R package.

# Install devtools, if you haven't already.
install.packages("devtools")

library(devtools)
install_github("shinyTree/shinyTree")

Getting Started

01-simple (Live Demo)

library(shiny)
runApp(system.file("examples/01-simple", package = "shinyTree"))

A simple example to demonstrate the usage of the shinyTree package.

02-attributes (Live Demo)

library(shiny)
runApp(system.file("examples/02-attributes", package = "shinyTree"))

Manage properties of your tree by adding attributes to your list when rendering.

03-checkbox (Live Demo)

library(shiny)
runApp(system.file("examples/03-checkbox", package = "shinyTree"))

Use checkboxes to allow users to more easily manage which nodes are selected.

04-selected (Live Demo)

library(shiny)
runApp(system.file("examples/04-selected", package = "shinyTree"))

An example demonstrating how to set an input to the value of the currently selected node in the tree.

05-structure (Live Demo)

library(shiny)
runApp(system.file("examples/05-structure", package = "shinyTree"))

Demonstrates the low-level usage of a shinyTree as an input in which all attributes describing the state of the tree can be read.

06-search (Live Demo)

library(shiny)
runApp(system.file("examples/06-search", package = "shinyTree"))

An example showing the use of the search plugin to allow users to more easily navigate the nodes in your tree.

07-drag-and-drop (Live Demo)

library(shiny)
runApp(system.file("examples/07-drag-and-drop", package = "shinyTree"))

An example demonstrating the use of the drag-and-drop feature which allows the user to reorder the nodes in the tree.

08-class (Live Demo)

library(shiny)
runApp(system.file("examples/08-class", package = "shinyTree"))

An example demonstrating the use of the ability to style nodes using custom classes.

09-themes

library(shiny)
runApp(system.file("examples/09-themes", package = "shinyTree"))

An example demonstrating the use of built-in tree themes.

10-node-ids

library(shiny)
runApp(system.file("examples/10-node-ids", package = "shinyTree"))

An example demonstrating the ability to label and return node identifiers and classes.

11-tree-update

library(shiny)
runApp(system.file("examples/11-tree-update", package = "shinyTree"))

An example demonstrating the ability to update a tree with a new tree model. This was broken in the original version as the tree was destroyed upon initialization.

12-types

library(shiny)
runApp(system.file("examples/12-types", package = "shinyTree"))

An example demonstrating node types with custom icons.

13-icons

library(shiny)
runApp(system.file("examples/13-icons", package = "shinyTree"))

An example demonstrating various ways to use icons on nodes.

14-files

library(shiny)
runApp(system.file("examples/14-files", package = "shinyTree"))

Demonstrates how to create a file browser tree.

15-files

library(shiny)
runApp(system.file("examples/15-data", package = "shinyTree"))

Demonstrates how to attach and retreive metadata from a node.

16-async

library(shiny)
runApp(system.file("examples/16-async", package = "shinyTree"))

Demonstrates how to render a tree asynchronously.

17-contextmenu

library(shiny)
runApp(system.file("examples/17-contextmenu", package = "shinyTree"))

Demonstrates how to enable the contextmenu.

18-modules

library(shiny)
runApp(system.file("examples/18-modules/app.R", package="shinyTree"))
runApp(system.file("examples/18-modules/app_types.R", package="shinyTree"))

Demonstrates how to use shinyTree with shiny modules.

19-data.tree

library(shiny)
runApp(system.file("examples/19-data.tree", package = "shinyTree"))

Demonstrates how to pass a data.tree to shinyTree.

20-api

library(shiny)
runApp(system.file("examples/20-api", package = "shinyTree"))

An example demonstrating how to extend the operations on the tree to the rest of the jsTree's core functionality.

21-options

library(shiny)
runApp(system.file("examples/21-options/app_setState_refresh.R", package="shinyTree"))

Demonstrates how to fine-tune shinyTree's behaviour with options. Specifically: When internal jstree code calls set_state or refresh, a callback is made so that the shiny server is notified and observe and observeEvents for the tree are fired. This can be useful if the developer would like observe and observeEvents to run after using updateTree. (By default, updateTree does not run observe or observeEvent because it is assumed that the shiny application knows that the tree is being changed already.)

23-file-icons

library(shiny)
library(shinyTree)
runApp(system.file("examples/23-file-icons", package = "shinyTree"))

An example demonstrating how to create a file tree with individual icons.

Known Bugs

See the Issues page for information on outstanding issues.

Download Details:

Author: shinyTree
Source Code: https://github.com/shinyTree/shinyTree 
License: View license

#r #tree #integration 

ShinyTree: Shiny integration with The jsTree Library

CSTParser.jl: A Concrete Syntax Tree Parser for Julia

CSTParser   

A parser for Julia using Tokenize that aims to extend the built-in parser by providing additional meta information along with the resultant AST.

Installation and Usage

using Pkg
Pkg.add("CSTParser")
using CSTParser
CSTParser.parse("x = y + 123")

Documentation: Dev

Structure

CSTParser.EXPR are broadly equivalent to Base.Expr in structure. The key differences are additional fields to store, for each expression:

  • trivia tokens such as punctuation or keywords that are not stored as part of the AST but are needed for the CST representation;
  • the span measurements for an expression;
  • the textual representation of the token (only needed for certain tokens including identifiers (symbols), operators and literals);
  • the parent expression, if present; and
  • any other meta information (this field is untyped and is used within CSTParser to hold errors).

All .head values used in Expr are used in EXPR. Unlike in AST, tokens (terminal expressions with no child expressions) are stored as EXPR and additional head types are used to distinguish between different types of token. These possible head values include:

:IDENTIFIER
:NONSTDIDENTIFIER (e.g. var"id")
:OPERATOR

# Punctuation
:COMMA
:LPAREN
:RPAREN
:LSQUARE
:RSQUARE
:LBRACE
:RBRACE
:ATSIGN
:DOT

# Keywords
:ABSTRACT
:BAREMODULE
:BEGIN
:BREAK
:CATCH
:CONST
:CONTINUE
:DO
:ELSE
:ELSEIF
:END
:EXPORT
:FINALLY
:FOR
:FUNCTION
:GLOBAL
:IF
:IMPORT
:LET
:LOCAL
:MACRO
:MODULE
:MUTABLE
:NEW
:OUTER
:PRIMITIVE
:QUOTE
:RETURN
:STRUCT
:TRY
:TYPE
:USING
:WHILE

# Literals
:INTEGER
:BININT (0b0)
:HEXINT (0x0)
:OCTINT (0o0)
:FLOAT
:STRING
:TRIPLESTRING
:CHAR
:CMD
:TRIPLECMD
:NOTHING 
:TRUE
:FALSE

The ordering of .args members matches that in Base.Expr and members of .trivia are stored in the order in which they appear in text.

Download Details:

Author: julia-vscode
Source Code: https://github.com/julia-vscode/CSTParser.jl 
License: View license

#julia #tree 

CSTParser.jl: A Concrete Syntax Tree Parser for Julia
Royce  Reinger

Royce Reinger

1659765300

RSyntaxtree: Syntax Tree Generator Made with Ruby

RSyntaxTree is a graphical syntax tree generator written in the Ruby programming language.


Web Interface

See updates and a working web interface available at https://yohasebe.com/rsyntaxtree.

You can run RSyntaxTree's web interface on your local machine using Docker Desktop. See RSyntaxTree Web UI


Installation

# gem install rsyntaxtree


Usage

For the web interface, see Usage section of https://yohasebe.com/rsyntaxtree.

For the command-line interface, type $rsyntaxtree -h after installation. Here's what you get:

RSyntaxTree, (linguistic) syntax tree generator written in Ruby.

Usage:
       rsyntaxtree [options] "[VP [VP [V set] [NP bracket notation]] [ADV here]]"
where [options] are:
  -o, --outdir=<s>         Output directory (default: ./)
  -f, --format=<s>         Output format: png, gif, jpg, pdf, or svg (default: png)
  -l, --leafstyle=<s>      visual style of tree leaves: auto, triangle, bar, or nothing (default: auto)
  -n, --fontstyle=<s>      Font style (available when ttf font is specified): sans, serif, cjk (default: sans)
  -t, --font=<s>           Path to a ttf font used to generate tree (optional)
  -s, --fontsize=<i>       Size: 8-26 (default: 16)
  -m, --margin=<i>         Margin: 0-10 (default: 1)
  -v, --vheight=<f>        Connector Height: 0.5-5.0 (default: 2.0)
  -c, --color=<s>          Color text and bars: on or off (default: on)
  -y, --symmetrize=<s>     Generate radically symmetrical, balanced tree: on or off (default: off)
  -r, --transparent=<s>    Make background transparent: on or off (default: off)
  -p, --polyline=<s>       draw polyline connectors: on or off (default: off)
  -e, --version            Print version and exit
  -h, --help               Show this message```

See the documentation for more detailed info about the syntax.


Examples

See RSyntaxTree Examples.

Input text

[S
  [NP |R|<>SyntaxTree]
  [VP
    [V generates]
    [NP
      [Adj #\+multilingual\
            \+beautiful]
      [NP syntax\
          trees]
    ]
  ]
]

Output (PNG or SVG)

 


Development

For the latest updates and downloads please visit http://github.com/yohasebe/rsyntaxtree


Author: Yohasebe
Source Code: https://github.com/yohasebe/rsyntaxtree 
License: MIT License

#ruby #tree #visualization 

RSyntaxtree: Syntax Tree Generator Made with Ruby
Royce  Reinger

Royce Reinger

1659118560

The Ruby Based Wrapper for The TreeTagger By Helmut Schmid

TreeTagger for Ruby

DESCRIPTION

A Ruby based wrapper for the TreeTagger by Helmut Schmid.

Check it out if you are interested in Natural Language Processing (NLP) and/or Human Language Technology (HLT).

This library provides comprehensive bindings for the TreeTagger, a statistical language independed POS tagging and chunking software.

TreeTagger is language agnostic, it will never guess what language you're going to use.

The tagger is described in the following two papers:

Helmut Schmid (1995): Improvements in Part-of-Speech Tagging with an Application to German. Proceedings of the ACL SIGDAT-Workshop. Dublin, Ireland.

Helmut Schmid (1994): Probabilistic Part-of-Speech Tagging Using Decision Trees. Proceedings of International Conference on New Methods in Language Processing, Manchester, UK.

INSTALLATION

Before you install the treetagger-ruby package please ensure you have downloaded and installed the TreeTagger itself.

The TreeTagger is a copyrighted software by Helmut Schmid and IMS, please read the license agreament before you download the TreeTagger package and language models.

After the installation of the TreeTagger set the environment variable TREETAGGER_BINARY to the location where the binary tree-tagger resides. Usually this binary is located under the bin directory in the main installation directory of the TreeTagger.

Also you have to set the variable TREETAGGER_MODEL to the location of the appropriate language model you have acquired in the training step.

For instance you may add the following lines to your .profile file:

export TREETAGGER_BINARY='/path/to/your/TreeTagger/bin/tree-tagger'
export TREETAGGER_MODEL='/path/to/your/TreeTagger/lib/german.par'

It is convinient to work with a default language model, but you can change it every time during the instantiation of a new tagger instance.

treetagger-ruby is provided as a .gem package. Simply install it via RubyGems. To install treetagger-ruby issue the following command: $ gem install treetagger-ruby

If you want to do a system wide installation, do this as root (possibly using sudo).

Alternatively use your Gemfile for dependency management.

SYNOPSIS

Basic Usage

Basic usage is very simple:

$ require 'treetagger'
$ # Instantiate a tagger instance with default values.
$ tagger = TreeTagger::Tagger.new
$ # Process an array of tokens.
$ tagger.process(%w{Ich gehe in die Schule})
$ # Flush the pipeline.
$ tagger.flush
$ # Get the processed data.
$ tagger.get_output

Input Format

Basically you have to provide a tokenized sequence with possibly some additional information on lexical classes of tokens and on their probabilities. Every token has to be on a separate line. Due to technical limitations SGML tags (i.e. sequences with heading < and trailing >) cannot be valid tokens since they are used internally for delimiting meaningful content from flush tokens. It implies the use of the -sgml option which cannot be changes by user. It is a limitation of this library. If you do need to process tags, fall back and use the TreeTagger as a standalone programm possibly employing temp files to store your input and output. This behaviour will be also implemented in futher versions of treetagger-ruby.

Every token may occure alone on the line or be followed by additional information:

  • token;
  • token (\tab tag)+;
  • token (\tab tag \space lemma)+;
  • token (\tab tag \space probability)+;
  • token (\tab tag \space probability \space lemma)+.

You input may look like the following sentence: Die ART 0.99 neuen ADJA neu Hunde NN NP stehen VVFIN 0.99 stehen an den Mauern NN Mauer .

This wrapper accepts the input as String or Array.

If you want to use strings, you are responsible for the proper delimiters inside the string: "Die\tART 0.99\nneuen\tADJA neu\nHunde\tNN NP\nstehen\t VVFIN 0.99 stehen\nan\nden\nMauern\tNN Mauer\n.\n" Now treetagger-ruby does not check your markup for correctness and will possibly report a TreeTagger::ExternalError if the TreeTagger process die due to input errors.

Using arrays is more convinient since they can be built programmatically.

Arrays should have the following structure:

  • ['token', 'token', 'token'];
  • ['token', ['token', ['POS', 'lemma'], ['POS', 'lemma']], 'token'];
  • ['token', ['token', ['POS', prob], ['POS', 'prob']], 'token'];
  • ['token', ['token', ['POS', prob, 'lemma'], ['POS', 'prob', 'lemma']]].

It is internally converted in the sequence token\ntoken\tPOS lemma\t POS lemma\ntoken\n, i.e. in the enriched version alternatives are tab separated and entries a blank separated.

Note that probabilities may be strings or integers.

The lexicon lookup is not implemented for now, that's the latter three forms of input arrays are not supported yet.

Output Format

For now you'll get an array with strings elements. However the precise string structure depends on the command line arguments you've provided during the tagger instantiation.

For instanse for the input ["Veruntreute", "die", "AWO", "Spendengeld", "?"] you'll get the following output with default cmd argumetns:

["Veruntreute\tNN\tVeruntreute", "die\tART\td", "AWO\tNN\t", "Spendengeld\tNN\tSpendengeld", "?\t$.\t?"]

See documentation in the TreeTagger::Tagger class for details on particular methods.

Exception Hierarchy

While using TreeTagger you can face following errors:

  • TreeTagger::UserError;
  • TreeTagger::RuntimeError;
  • TreeTagger::ExternalError.

This three kinds of errors all subclass TreeTagger::Error, which in turn is a subclass of StandardError. For an end user this means that it is possible to intercept all errors from treetagger-ruby with a simple rescue clause.

Implemented Features

Please have a look at the CHANGELOG file for details on implemented and planned features.

SUPPORT

If you have question, bug reports or any suggestions, please drop me an email :)

HOW TO CONTRIBUTE

Please contact me and suggest your ideas, report bugs, talk to me, if you want to implement some features in the future releases of this library.

Please don't feel offended if I cannot accept all your pull requests, I have to review them and find the appropriate time and place in the code base to incorporate your valuable changes.

Any help is deeply appreciated!

TODO:

  • How to use TreeTagger in the wild;
  • Input and output format, tokenization;
  • The actual german parameter file has been estimated on one byte encoded data.

RubyGems | RTT Project Page | Source Code | Bug Tracker 

Author: Arbox
Source Code: https://github.com/arbox/treetagger-ruby 
License: MIT license

#ruby #tree 

The Ruby Based Wrapper for The TreeTagger By Helmut Schmid
Monty  Boehm

Monty Boehm

1658980320

Treekenize.jl: Parser with Beginners and Enders and infix

Clean parser

Goal

Intended to be a parser where the relation to the AST tree and the code is clear. (In Julia, the Expr objects tree.)

In order to be able to use homoiconicness of a language properly, it is useful not to have gotchas in the syntax. This attempts to reach that by parsing a language that consists of two elements:

There are 'blocks' with a beginner and an ender. For instance in Julia: (-),[-] and {-} but also begin-end, function-end, type-end, and @,typealias,const and a new line.

Further there is infix notation, with some order.

Implementation

The implementation is much more flexible than that, a beginner-ender can change the beginners and enders insider entirely.

Problems/deviations for application to julia

For functions to work, 'nothing or just whitespace' would have to be a potential infix symbol.

if would have to be able to deal with else and elseif, perhaps extend the concept.

" needs to deal with escapes.

Other issues(const?)

Author: o-jasper
Source Code: https://github.com/o-jasper/Treekenize.jl 
License: MIT license

#julia #tree 

Treekenize.jl: Parser with Beginners and Enders and infix
Royce  Reinger

Royce Reinger

1658921460

ID3-based Implementation Of The ML Decision Tree Algorithm

Decision Tree

A Ruby library which implements ID3 (information gain) algorithm for decision tree learning. Currently, continuous and discrete datasets can be learned.

  • Discrete model assumes unique labels & can be graphed and converted into a png for visual analysis
  • Continuous looks at all possible values for a variable and iteratively chooses the best threshold between all possible assignments. This results in a binary tree which is partitioned by the threshold at every step. (e.g. temperate > 20C)

Features

  • ID3 algorithms for continuous and discrete cases, with support for inconsistent datasets.
  • Graphviz component to visualize the learned tree
  • Support for multiple, and symbolic outputs and graphing of continuous trees.
  • Returns default value when no branches are suitable for input

Implementation

  • Ruleset is a class that trains an ID3Tree with 2/3 of the training data, converts it into set of rules and prunes the rules with the remaining 1/3 of the training data (in a C4.5 way).
  • Bagging is a bagging-based trainer (quite obvious), which trains 10 Ruleset trainers and when predicting chooses the best output based on voting.

Blog post with explanation & examples

Example

require 'decisiontree'

attributes = ['Temperature']
training = [
  [36.6, 'healthy'],
  [37, 'sick'],
  [38, 'sick'],
  [36.7, 'healthy'],
  [40, 'sick'],
  [50, 'really sick'],
]

# Instantiate the tree, and train it based on the data (set default to '1')
dec_tree = DecisionTree::ID3Tree.new(attributes, training, 'sick', :continuous)
dec_tree.train

test = [37, 'sick']
decision = dec_tree.predict(test)
puts "Predicted: #{decision} ... True decision: #{test.last}"

# => Predicted: sick ... True decision: sick

# Specify type ("discrete" or "continuous") in the training data
labels = ["hunger", "color"]
training = [
        [8, "red", "angry"],
        [6, "red", "angry"],
        [7, "red", "angry"],
        [7, "blue", "not angry"],
        [2, "red", "not angry"],
        [3, "blue", "not angry"],
        [2, "blue", "not angry"],
        [1, "red", "not angry"]
]

dec_tree = DecisionTree::ID3Tree.new(labels, training, "not angry", color: :discrete, hunger: :continuous)
dec_tree.train

test = [7, "red", "angry"]
decision = dec_tree.predict(test)
puts "Predicted: #{decision} ... True decision: #{test.last}"

# => Predicted: angry ... True decision: angry

Author: igrigorik
Source Code: https://github.com/igrigorik/decisiontree 
License: MIT License

#ruby #tree #machinelearning 

ID3-based Implementation Of The ML Decision Tree Algorithm
Monty  Boehm

Monty Boehm

1658877960

DependencyTrees.jl: Dependency Parsing in Julia

DependencyTrees.jl   

DependencyTrees.jl is a Julia package for working with dependency structures in natural language sentences. It provides a representation of dependency parse trees (DependencyTree), a treebank reader, and transition-based parsing algorithms.

Features

Trees and Treebanks

The DependencyTree type represents a dependency parse of a natural language sentence.

julia> using DependencyTrees

julia> treebank = Treebank("test/data/english.conllu")

julia> for tree in treebank
           # ...
       end

julia> tree = first(treebank)
┌──────────────────── ROOT
│                 ┌─► Pierre
│     ┌─►┌──┌──┌──└── Vinken
│     │  │  │  └────► ,
│     │  │  │     ┌─► 61
│     │  │  │  ┌─►└── years
│     │  │  └─►└───── old
│     │  └──────────► ,
└─►┌──└───────────┌── will
   │  ┌─────┌──┌──└─► join
   │  │     │  │  ┌─► the
   │  │     │  └─►└── board
   │  │  ┌──└───────► as
   │  │  │     ┌────► a
   │  │  │     │  ┌─► nonexecutive
   │  │  └────►└──└── director
   │  └──────────►┌── Nov.
   │              └─► 29
   └────────────────► .

Transition-based parsing

A number of transition systems and oracles are implemented in the TransitionParsing submodule.

julia> using DependencyTrees
julia> using DependencyTrees.TransitionParsing
julia> treebank = Treebank("test/data/english.conll")
julia> oracle = Oracle(ArcHybrid(), dymanic_oracle)
julia> for tree in treebank, (config, gold ts) in oracle(tree)
           # ...
       end

Transition systems:

  • ArcStandard (static oracle)
  • ArcEager[1],[2] (static and dynamic oracles)
  • ArcHybrid[3],[4] (static and dynamic oracles)
  • ArcSwift[5] (static oracle)
  • ListBasedNonProjective[2] (static oracle)

See the documentation for details.

Installation

]add DependencyTrees

Contributing & Help

Open an issue! Bug reports, feature requests, etc. are all welcome.

References

[1]: Nivre 2003: An efficient algorithm for projective dependency parsing. http://stp.lingfil.uu.se/~nivre/docs/iwpt03.pdf

[2]: Nivre 2008: Algorithms for Deterministic Incremental Dependency Parsing. https://www.aclweb.org/anthology/J/J08/J08-4003.pdf

[3]: Kuhlmann et all 2011: Dynamic programming algorithms for transition-based dependency parsers. https://www.aclweb.org/anthology/P/P11/P11-1068.pdf

[4]: Goldberg & Nivre 2013: Training deterministic parsers with non-deterministic oracles. https://aclweb.org/anthology/Q/Q13/Q13-1033.pdf

[5]: Qi & Manning 2016: Arc-swift: a novel transition system for dependency parsing. https://nlp.stanford.edu/pubs/qi2017arcswift.pdf

Read the docs!

Author: Dellison
Source Code: https://github.com/dellison/DependencyTrees.jl 
License: MIT license

#julia #tree #naturallanguageprocessing 

DependencyTrees.jl: Dependency Parsing in Julia
Monty  Boehm

Monty Boehm

1658863080

BKTrees.jl: Burkhard-Keller Trees Implementation

BKTrees.jl

Julia implementation of BKTrees based on the Python implementation found here.

Documentation

This short example illustrates the usage of the B-K trees for approximate string matching:

julia> using Pkg
       Pkg.activate(".")
       using BKTrees
       using Random
       using StringDistances
       
       lev(x,y) = evaluate(Levenshtein(), x, y)
       dictionary = [randstring(10) for _ in 1:100_000]  # random dictionary
       bkt = BKTree(lev, dictionary)  # build tree
       
       target = randstring(10)  # target string
       
       # search for best 3 matches with distance < 10
       found = find(bkt, target, 10, k=3)
       @show target, found

#(target, found) = ("RIqWKU2A38", Tuple{Float64,String}[(7.0, "uIfPK02wH9"), (7.0, "RIqTF8YC6O"), (7.0, "XMqWKG1GHN")])

Installation

The installation can be done through the usual channels (manually by cloning the repository or installing it though the julia REPL).

Introductio

For more information on BK-trees check out https://en.wikipedia.org/wiki/BK-tree and https://github.com/Jetsetter/pybktree.

Acknowledgments

This work is heavily based on the implementation found here

Author: JuliaNeighbors
Source Code: https://github.com/JuliaNeighbors/BKTrees.jl 
License: MIT license

#julia #tree #string 

BKTrees.jl: Burkhard-Keller Trees Implementation
Rupert  Beatty

Rupert Beatty

1658763300

Adjacency List’ed Closure Table Database Design Pattern Implementation

ClosureTable 

This is a database manipulation package for the Laravel 5.4+ framework. You may want to use it when you need to store and operate hierarchical data in your database. The package is an implementation of a well-known design pattern called closure table. However, in order to simplify and optimize SQL SELECT queries, it uses adjacency lists to query direct parent/child relationships.

Installation

It's strongly recommended to use Composer to install the package:

$ composer require franzose/closure-table

If you use Laravel 5.5+, the package's service provider is automatically registered for you thanks to the package auto-discovery feature. Otherwise, you have to manually add it to your config/app.php:

<?php

return [
    'providers' => [
        Franzose\ClosureTable\ClosureTableServiceProvider::class
    ]
];

Setup

In a basic scenario, you can simply run the following command:

$ php artisan closuretable:make Node

Where Node is the name of the entity model. This is what you get from running the above:
 

  1. Two models in the app directory: App\Node and App\NodeClosure
     
  2. A new migration in the database/migrations directory

As you can see, the command requires a single argument, name of the entity model. However, it accepts several options in order to provide some sort of customization:

OptionAliasMeaning
namespacensCustom namespace for generated models. Keep in mind that the given namespace will override model namespaces: php artisan closuretable:make Foo\\Node --namespace=Qux --closure=Bar\\NodeTree will generate Qux\Node and Qux\NodeTree models.
entity-tableetDatabase table name for the entity model
closurecClass name for the closure model
closure-tablectDatabase table name for the closure model
models-pathmdlDirectory in which to put generated models
migrations-pathmgrDirectory in which to put generated migrations
use-innodbiThis flag will tell the generator to set database engine to InnoDB. Useful only if you use MySQL

Requirements

You have to keep in mind that, by design of this package, the models/tables have a required minimum of attributes/columns:

Entity
Attribute/ColumnCustomized byMeaning
parent_idEntity::getParentIdColumn()ID of the node's immediate parent, simplifies queries for immediate parent/child nodes.
positionEntity::getPositionColumn()Node position, allows to order nodes of the same depth level
ClosureTable
Attribute/ColumnCustomized byMeaning
id  
ancestorClosureTable::getAncestorColumn()Parent (self, immediate, distant) node ID
descendantClosureTable::getDescendantColumn()Child (self, immediate, distant) node ID
depthClosureTable::getDepthColumn()Current nesting level, 0+

Examples

In the examples, let's assume that we've set up a Node model which extends the Franzose\ClosureTable\Models\Entity model.

Scopes

Since ClosureTable 6, a lot of query scopes have become available in the Entity model:

ancestors()
ancestorsOf($id)
ancestorsWithSelf()
ancestorsWithSelfOf($id)
descendants()
descendantsOf($id)
descendantsWithSelf()
descendantsWithSelfOf($id)
childNode()
childNodeOf($id)
childAt(int $position)
childOf($id, int $position)
firstChild()
firstChildOf($id)
lastChild()
lastChildOf($id)
childrenRange(int $from, int $to = null)
childrenRangeOf($id, int $from, int $to = null)
sibling()
siblingOf($id)
siblings()
siblingsOf($id)
neighbors()
neighborsOf($id)
siblingAt(int $position)
siblingOfAt($id, int $position)
firstSibling()
firstSiblingOf($id)
lastSibling()
lastSiblingOf($id)
prevSibling()
prevSiblingOf($id)
prevSiblings()
prevSiblingsOf($id)
nextSibling()
nextSiblingOf($id)
nextSiblings()
nextSiblingsOf($id)
siblingsRange(int $from, int $to = null)
siblingsRangeOf($id, int $from, int $to = null)

You can learn how to use query scopes from the Laravel documentation.

Parent/Root

<?php
$nodes = [
    new Node(['id' => 1]),
    new Node(['id' => 2]),
    new Node(['id' => 3]),
    new Node(['id' => 4, 'parent_id' => 1])
];

foreach ($nodes as $node) {
    $node->save();
}

Node::getRoots()->pluck('id')->toArray(); // [1, 2, 3]
Node::find(1)->isRoot(); // true
Node::find(1)->isParent(); // true
Node::find(4)->isRoot(); // false
Node::find(4)->isParent(); // false

// make node 4 a root at the fourth position (1 => 0, 2 => 1, 3 => 2, 4 => 3)
$node = Node::find(4)->makeRoot(3);
$node->isRoot(); // true
$node->position; // 3

Node::find(4)->moveTo(0, Node::find(2)); // same as Node::find(4)->moveTo(0, 2);
Node::find(2)->getChildren()->pluck('id')->toArray(); // [4]

Ancestors

<?php
$nodes = [
    new Node(['id' => 1]),
    new Node(['id' => 2, 'parent_id' => 1]),
    new Node(['id' => 3, 'parent_id' => 2]),
    new Node(['id' => 4, 'parent_id' => 3])
];

foreach ($nodes as $node) {
    $node->save();
}

Node::find(4)->getAncestors()->pluck('id')->toArray(); // [1, 2, 3]
Node::find(4)->countAncestors(); // 3
Node::find(4)->hasAncestors(); // true
Node::find(4)->ancestors()->where('id', '>', 1)->get()->pluck('id')->toArray(); // [2, 3];
Node::find(4)->ancestorsWithSelf()->where('id', '>', 1)->get()->pluck('id')->toArray(); // [2, 3, 4];
Node::ancestorsOf(4)->where('id', '>', 1)->get()->pluck('id')->toArray(); // [2, 3];
Node::ancestorsWithSelfOf(4)->where('id', '>', 1)->get()->pluck('id')->toArray(); // [2, 3, 4];

There are several methods that have been deprecated since ClosureTable 6:

-Node::find(4)->getAncestorsTree();
+Node::find(4)->getAncestors()->toTree();

-Node::find(4)->getAncestorsWhere('id', '>', 1);
+Node::find(4)->ancestors()->where('id', '>', 1)->get();

Descendants

<?php
$nodes = [
    new Node(['id' => 1]),
    new Node(['id' => 2, 'parent_id' => 1]),
    new Node(['id' => 3, 'parent_id' => 2]),
    new Node(['id' => 4, 'parent_id' => 3])
];

foreach ($nodes as $node) {
    $node->save();
}

Node::find(1)->getDescendants()->pluck('id')->toArray(); // [2, 3, 4]
Node::find(1)->countDescendants(); // 3
Node::find(1)->hasDescendants(); // true
Node::find(1)->descendants()->where('id', '<', 4)->get()->pluck('id')->toArray(); // [2, 3];
Node::find(1)->descendantsWithSelf()->where('id', '<', 4)->get()->pluck('id')->toArray(); // [1, 2, 3];
Node::descendantsOf(1)->where('id', '<', 4)->get()->pluck('id')->toArray(); // [2, 3];
Node::descendantsWithSelfOf(1)->where('id', '<', 4)->get()->pluck('id')->toArray(); // [1, 2, 3];

There are several methods that have been deprecated since ClosureTable 6:

-Node::find(4)->getDescendantsTree();
+Node::find(4)->getDescendants()->toTree();

-Node::find(4)->getDescendantsWhere('foo', '=', 'bar');
+Node::find(4)->descendants()->where('foo', '=', 'bar')->get();

Children

<?php
$nodes = [
    new Node(['id' => 1]),
    new Node(['id' => 2, 'parent_id' => 1]),
    new Node(['id' => 3, 'parent_id' => 1]),
    new Node(['id' => 4, 'parent_id' => 1]),
    new Node(['id' => 5, 'parent_id' => 1]),
    new Node(['id' => 6, 'parent_id' => 2]),
    new Node(['id' => 7, 'parent_id' => 3])
];

foreach ($nodes as $node) {
    $node->save();
}

Node::find(1)->getChildren()->pluck('id')->toArray(); // [2, 3, 4, 5]
Node::find(1)->countChildren(); // 3
Node::find(1)->hasChildren(); // true

// get child at the second position (positions start from zero)
Node::find(1)->getChildAt(1)->id; // 3

Node::find(1)->getChildrenRange(1)->pluck('id')->toArray(); // [3, 4, 5]
Node::find(1)->getChildrenRange(0, 2)->pluck('id')->toArray(); // [2, 3, 4]

Node::find(1)->getFirstChild()->id; // 2
Node::find(1)->getLastChild()->id; // 5

Node::find(6)->countChildren(); // 0
Node::find(6)->hasChildren(); // false

Node::find(6)->addChild(new Node(['id' => 7]));

Node::find(1)->addChildren([new Node(['id' => 8]), new Node(['id' => 9])], 2);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray(); // [2 => 0, 3 => 1, 8 => 2, 9 => 3, 4 => 4, 5 => 5]

// remove child by its position
Node::find(1)->removeChild(2);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray(); // [2 => 0, 3 => 1, 9 => 2, 4 => 3, 5 => 4]

Node::find(1)->removeChildren(2, 4);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray(); // [2 => 0, 3 => 1]

Siblings

<?php
$nodes = [
    new Node(['id' => 1]),
    new Node(['id' => 2, 'parent_id' => 1]),
    new Node(['id' => 3, 'parent_id' => 1]),
    new Node(['id' => 4, 'parent_id' => 1]),
    new Node(['id' => 5, 'parent_id' => 1]),
    new Node(['id' => 6, 'parent_id' => 1]),
    new Node(['id' => 7, 'parent_id' => 1])
];

foreach ($nodes as $node) {
    $node->save();
}

Node::find(7)->getFirstSibling()->id; // 2
Node::find(7)->getSiblingAt(0); // 2
Node::find(2)->getLastSibling(); // 7
Node::find(7)->getPrevSibling()->id; // 6
Node::find(7)->getPrevSiblings()->pluck('id')->toArray(); // [2, 3, 4, 5, 6]
Node::find(7)->countPrevSiblings(); // 5
Node::find(7)->hasPrevSiblings(); // true

Node::find(2)->getNextSibling()->id; // 3
Node::find(2)->getNextSiblings()->pluck('id')->toArray(); // [3, 4, 5, 6, 7]
Node::find(2)->countNextSiblings(); // 5
Node::find(2)->hasNextSiblings(); // true

Node::find(3)->getSiblings()->pluck('id')->toArray(); // [2, 4, 5, 6, 7]
Node::find(3)->getNeighbors()->pluck('id')->toArray(); // [2, 4]
Node::find(3)->countSiblings(); // 5
Node::find(3)->hasSiblings(); // true

Node::find(2)->getSiblingsRange(2)->pluck('id')->toArray(); // [4, 5, 6, 7]
Node::find(2)->getSiblingsRange(2, 4)->pluck('id')->toArray(); // [4, 5, 6]

Node::find(4)->addSibling(new Node(['id' => 8]));
Node::find(4)->getNextSiblings()->pluck('id')->toArray(); // [5, 6, 7, 8]

Node::find(4)->addSibling(new Node(['id' => 9]), 1);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray();
// [2 => 0, 9 => 1, 3 => 2, 4 => 3, 5 => 4, 6 => 5, 7 => 6, 8 => 7]

Node::find(8)->addSiblings([new Node(['id' => 10]), new Node(['id' => 11])]);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray();
// [2 => 0, 9 => 1, 3 => 2, 4 => 3, 5 => 4, 6 => 5, 7 => 6, 8 => 7, 10 => 8, 11 => 9]

Node::find(2)->addSiblings([new Node(['id' => 12]), new Node(['id' => 13])], 3);
Node::find(1)->getChildren()->pluck('position', 'id')->toArray();
// [2 => 0, 9 => 1, 3 => 2, 12 => 3, 13 => 4, 4 => 5, 5 => 6, 6 => 7, 7 => 8, 8 => 9, 10 => 10, 11 => 11]

Tree

<?php
Node::createFromArray([
    'id' => 1,
    'children' => [
        [
            'id' => 2,
            'children' => [
                [
                    'id' => 3,
                    'children' => [
                        [
                            'id' => 4,
                            'children' => [
                                [
                                    'id' => 5,
                                    'children' => [
                                        [
                                            'id' => 6,
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
]);

Node::find(4)->deleteSubtree();
Node::find(1)->getDescendants()->pluck('id')->toArray(); // [2, 3, 4]

Node::find(4)->deleteSubtree(true);
Node::find(1)->getDescendants()->pluck('id')->toArray(); // [2, 3]

There are several methods that have been deprecated since ClosureTable 6:

-Node::getTree();
-Node::getTreeByQuery(...);
-Node::getTreeWhere('foo', '=', 'bar');
+Node::where('foo', '=', 'bar')->get()->toTree();

Collection methods

This library uses an extended collection class which offers some convenient methods:

<?php
Node::createFromArray([
    'id' => 1,
    'children' => [
        ['id' => 2],
        ['id' => 3],
        ['id' => 4],
        ['id' => 5],
        [
            'id' => 6,
            'children' => [
                ['id' => 7],
                ['id' => 8],
            ]
        ],
    ]
]);

/** @var Franzose\ClosureTable\Extensions\Collection $children */
$children = Node::find(1)->getChildren();
$children->getChildAt(1)->id; // 3
$children->getFirstChild()->id; // 2
$children->getLastChild()->id; // 6
$children->getRange(1)->pluck('id')->toArray(); // [3, 4, 5, 6]
$children->getRange(1, 3)->pluck('id')->toArray(); // [3, 4, 5]
$children->getNeighbors(2)->pluck('id')->toArray(); // [3, 5]
$children->getPrevSiblings(2)->pluck('id')->toArray(); // [2, 3]
$children->getNextSiblings(2)->pluck('id')->toArray(); // [5, 6]
$children->getChildrenOf(4)->pluck('id')->toArray(); // [7, 8]
$children->hasChildren(4); // true
$tree = $children->toTree();

Author: franzose
Source Code: https://github.com/franzose/ClosureTable 
License: MIT license

#laravel #closure #table #tree #database #php 

Adjacency List’ed Closure Table Database Design Pattern Implementation
Hunter  Krajcik

Hunter Krajcik

1658598720

Flutter_tree_pro: Flutter Tree Select Widget

packages

Flutter tree select widget.

Screenshot

flutter_tree

Usage

To use this plugin, add flutter_tree_pro as a dependency in your pubspec.yaml file.

dependencies:
  flutter_tree_pro: ^0.0.3

Use as a widget

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter tree pro')),
      body: Container(
        child: FlutterTree(
          listData: treeListData,
          initialListData: initialTreeData,
          config: Config(
            parentId: 'parentId',
            dataType: DataType.DataList,
            label: 'value',
          ),
          onChecked: (List<Map<String, dynamic>> checkedList) {},
        ),
      ),
    );
  }

Property

propertydescription
listDataThe data source
initialListDataThe initial data source
parentIdThe key name of parent id
dataTypeThe type of data source
labelThe key name of the value
onCheckedThe item checked callback function

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_tree_pro

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

dependencies:
  flutter_tree_pro: ^0.0.7

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

Import it

Now in your Dart code, you can use:

import 'package:flutter_tree_pro/flutter_tree_pro.dart';

example/lib/main.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tree_pro/flutter_tree_pro.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: MyHomePage(title: 'Flutter Tree Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Map<String, dynamic>> treeListData = [];

  //默认数据
  List<Map<String, dynamic>> initialTreeData = [
    {"parentId": 1063, "value": "牡丹江市", "id": 1314},
    {"parentId": 1063, "value": "齐齐哈尔市", "id": 1318},
    {"parentId": 1063, "value": "佳木斯市", "id": 1320},
    {"parentId": 1066, "value": "长春市", "id": 1323},
    {"parentId": 1066, "value": "通化市", "id": 1325},
    {"parentId": 1066, "value": "白山市", "id": 1328},
    {"parentId": 1066, "value": "辽源市", "id": 1330},
    {"parentId": 1066, "value": "松原市", "id": 1332},
    {"parentId": 1009, "value": "南京市", "id": 1130},
    {"parentId": 1009, "value": "无锡市", "id": 1132},
    {"parentId": 1009, "value": "常州市", "id": 1133},
    {"parentId": 1009, "value": "镇江市", "id": 1134},
  ];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  loadData() async {
    var response = await rootBundle.loadString('assets/data.json');
    setState(() {
      json.decode(response)['country'].forEach((item) {
        treeListData.add(item);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: treeListData.isNotEmpty
          ? FlutterTreePro(
              // isExpanded: true,
              listData: treeListData,
              initialListData: initialTreeData,
              config: Config(
                parentId: 'parentId',
                dataType: DataType.DataList,
                label: 'value',
              ),
              onChecked: (List<Map<String, dynamic>> checkedList) {
                logger.v(checkedList);
              },
            )
          : Center(child: CircularProgressIndicator()),
    );
  }
}

Author: Invincible1996
Source Code: https://github.com/Invincible1996/flutter_tree 
License: Apache-2.0 license

#flutter #tree #dart 

Flutter_tree_pro: Flutter Tree Select Widget
Royce  Reinger

Royce Reinger

1657883940

RSTT: Another Ruby Wrapper for Stuttgarter Tree Tagger

TreeTagger for Ruby

!!! actual it is out of maintainance !!!

DESCRIPTION

The Ruby based wrapper for the TreeTagger by Helmut Schmid. Check it out if you are interested in Natural Language Processing (NLP) and Human Language Technology (HLT).

INSTALLATION + REQUIREMENTS

Before you install the treetagger-ruby package please ensure you have downloaded and installe the TreeTagger itself.
(And pls, respect his terms of license)

    gem install rstt
    rstt -c /path/to/your/TreeTagger/

USAGE

You have some class, where you want to use Rstt ..
the input is given by: Rstt.set_input lang: lang, content: content with default language 'en';
accessible languages could be found by Rstt.language_codes;
installed languages are stored in Rstt::LANGUAGES (cause it could be different)

 class Foo
 	include Rstt
 	
 	def pos_tagging(lang,content)
 		Rstt.set_input lang: lang, content: content
 		Rstt.preprocessing
 		Rstt.tagging
 		processed_ data = Rstt.tagged
 	end
 end

that's all, the processed data are accessible via Rstt.tagged,
it is an Array, thereby each element self is an Array with following elements

  1. the input word itself
  2. the word class
  3. the lemma of the input; depends on your input language

or via CLI, check usage with rstt -h

Author: LeFnord
Source Code: https://github.com/LeFnord/rstt 
License: MIT license

#ruby #tree 

RSTT: Another Ruby Wrapper for Stuttgarter Tree Tagger