text:
import * as o from '../output/output_ast';
import { LifecycleHooks } from '../private_import_core';
import { DetectChangesVars } from './constants';
var STATE_IS_NEVER_CHECKED = o.THIS_EXPR.prop('numberOfChecks').identical(new o.LiteralExpr(0));
var NOT_THROW_ON_CHANGES = o.not(DetectChangesVars.throwOnChange);
export function bindDirectiveAfterContentLifecycleCallbacks(directiveMeta, directiveInstance, compileElement) {
    var view = compileElement.view;
    var lifecycleHooks = directiveMeta.type.lifecycleHooks;
    var afterContentLifecycleCallbacksMethod = view.afterContentLifecycleCallbacksMethod;
    afterContentLifecycleCallbacksMethod.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
    if (lifecycleHooks.indexOf(LifecycleHooks.AfterContentInit) !== -1) {
        afterContentLifecycleCallbacksMethod.addStmt(new o.IfStmt(STATE_IS_NEVER_CHECKED, [directiveInstance.callMethod('ngAfterContentInit', []).toStmt()]));
    }
    if (lifecycleHooks.indexOf(LifecycleHooks.AfterContentChecked) !== -1) {
        afterContentLifecycleCallbacksMethod.addStmt(directiveInstance.callMethod('ngAfterContentChecked', []).toStmt());
    }
}
export function bindDirectiveAfterViewLifecycleCallbacks(directiveMeta, directiveInstance, compileElement) {
    var view = compileElement.view;
    var lifecycleHooks = directiveMeta.type.lifecycleHooks;
    var afterViewLifecycleCallbacksMethod = view.afterViewLifecycleCallbacksMethod;
    afterViewLifecycleCallbacksMethod.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
    if (lifecycleHooks.indexOf(LifecycleHooks.AfterViewInit) !== -1) {
        afterViewLifecycleCallbacksMethod.addStmt(new o.IfStmt(STATE_IS_NEVER_CHECKED, [directiveInstance.callMethod('ngAfterViewInit', []).toStmt()]));
    }
    if (lifecycleHooks.indexOf(LifecycleHooks.AfterViewChecked) !== -1) {
        afterViewLifecycleCallbacksMethod.addStmt(directiveInstance.callMethod('ngAfterViewChecked', []).toStmt());
    }
}
export function bindInjectableDestroyLifecycleCallbacks(provider, providerInstance, compileElement) {
    var onDestroyMethod = compileElement.view.destroyMethod;
    onDestroyMethod.resetDebugInfo(compileElement.nodeIndex, compileElement.sourceAst);
    if (provider.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
        onDestroyMethod.addStmt(providerInstance.callMethod('ngOnDestroy', []).toStmt());
    }
}
export function bindPipeDestroyLifecycleCallbacks(pipeMeta, pipeInstance, view) {
    var onDestroyMethod = view.destroyMethod;
    if (pipeMeta.type.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
        onDestroyMethod.addStmt(pipeInstance.callMethod('ngOnDestroy', []).toStmt());
    }
}
//# sourceMappingURL=lifecycle_binder.js.map

redpajama_set_name: RedPajamaGithub


text:
```JavaScript
class B private constructor() {
    companion object {
        fun getInstance() = Holder.sIntance
    }

    private object Holder {
        val sIntance = B()
    }
}
```

## 同步懒加载 · 单例模式

```JavaScript
class A {
    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            A()
        }
    }
}
```


text:
module Gitlab
  module Lfs
    class Router
      def initialize(project, user, request)
        @project = project
        @user = user
        @env = request.env
        @request = request
      end

      def try_call
        return unless @request && @request.path.present?

        case @request.request_method
        when 'GET'
          get_response
        when 'POST'
          post_response
        when 'PUT'
          put_response
        else
          nil
        end
      end

      private

      def get_response
        path_match = @request.path.match(/\/(info\/lfs|gitlab-lfs)\/objects\/([0-9a-f]{64})$/)
        return nil unless path_match

        oid = path_match[2]
        return nil unless oid

        case path_match[1]
        when "info/lfs"
          lfs.render_download_hypermedia_response(oid)
        when "gitlab-lfs"
          lfs.render_download_object_response(oid)
        else
          nil
        end
      end

      def post_response
        post_path = @request.path.match(/\/info\/lfs\/objects(\/batch)?$/)
        return nil unless post_path

        # Check for Batch API
        if post_path[0].ends_with?("/info/lfs/objects/batch")
          lfs.render_lfs_api_auth
        else
          nil
        end
      end

      def put_response
        object_match = @request.path.match(/\/gitlab-lfs\/objects\/([0-9a-f]{64})\/([0-9]+)(|\/authorize){1}$/)
        return nil if object_match.nil?

        oid = object_match[1]
        size = object_match[2].try(:to_i)
        return nil if oid.nil? || size.nil?

        # GitLab-workhorse requests
        # 1. Try to authorize the request
        # 2. send a request with a header containing the name of the temporary file
        if object_match[3] && object_match[3] == '/authorize'
          lfs.render_storage_upload_authorize_response(oid, size)
        else
          tmp_file_name = sanitize_tmp_filename(@request.env['HTTP_X_GITLAB_LFS_TMP'])
          return nil unless tmp_file_name

          lfs.render_storage_upload_store_response(oid, size, tmp_file_name)
        end
      end

      def lfs
        return unless @project

        Gitlab::Lfs::Response.new(@project, @user, @request)
      end

      def sanitize_tmp_filename(name)
        if name.present?
          name.gsub!(/^.*(\\|\/)/, '')
          name = name.match(/[0-9a-f]{73}/)
          name[0] if name
        else
          nil
        end
      end
    end
  end
end


text:
from ray.rllib.algorithms.apex_ddpg import (  # noqa
    ApexDDPG as ApexDDPGTrainer,
    APEX_DDPG_DEFAULT_CONFIG,
)


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        wx/richtext/richtextbackgroundpage.h
// Purpose:
// Author:      Julian Smart
// Modified by:
// Created:     13/11/2010 11:17:25
// RCS-ID:
// Copyright:   (c) Julian Smart
// Licence:
/////////////////////////////////////////////////////////////////////////////

#ifndef _RICHTEXTBACKGROUNDPAGE_H_
#define _RICHTEXTBACKGROUNDPAGE_H_

/*!
 * Includes
 */

#include "wx/richtext/richtextdialogpage.h"

////@begin includes
#include "wx/statline.h"
////@end includes

/*!
 * Forward declarations
 */

class WXDLLIMPEXP_FWD_RICHTEXT wxRichTextColourSwatchCtrl;

/*!
 * Control identifiers
 */
    /// Control identifiers
    enum {
        ID_RICHTEXTBACKGROUNDPAGE = 10845,
        ID_RICHTEXT_BACKGROUND_COLOUR_CHECKBOX = 10846,
        ID_RICHTEXT_BACKGROUND_COLOUR_SWATCH = 10847
    };

////@begin control identifiers
#define SYMBOL_WXRICHTEXTBACKGROUNDPAGE_STYLE() wxTAB_TRAVERSAL
#define SYMBOL_WXRICHTEXTBACKGROUNDPAGE_TITLE() wxEmptyString
#define SYMBOL_WXRICHTEXTBACKGROUNDPAGE_IDNAME() {.WxWindowID(ID_RICHTEXTBACKGROUNDPAGE).}
#define SYMBOL_WXRICHTEXTBACKGROUNDPAGE_SIZE() constructWxSize(400, 300)
#define SYMBOL_WXRICHTEXTBACKGROUNDPAGE_POSITION() wxDefaultPosition
////@end control identifiers

/*!
 * wxRichTextBackgroundPage class declaration
 */

class WXDLLIMPEXP_RICHTEXT wxRichTextBackgroundPage: public wxRichTextDialogPage
{
public:
    /// Constructors
    wxRichTextBackgroundPage();
    wxRichTextBackgroundPage( wxWindow* parent, wxWindowID id = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_IDNAME, const wxPoint& pos = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_POSITION, const wxSize& size = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_SIZE, long style = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_STYLE );

    /// Creation
    bool Create( wxWindow* parent, wxWindowID id = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_IDNAME, const wxPoint& pos = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_POSITION, const wxSize& size = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_SIZE, long style = SYMBOL_WXRICHTEXTBACKGROUNDPAGE_STYLE );

    /// Destructor
    ~wxRichTextBackgroundPage();

    /// Initialises member variables
    void Init();

    /// Creates the controls and sizers
    void CreateControls();

    /// Gets the attributes from the formatting dialog
    wxRichTextAttr* GetAttributes();

    /// Data transfer
    virtual bool TransferDataToWindow();
    virtual bool TransferDataFromWindow();

    /// Respond to colour swatch click
    void OnColourSwatch(wxCommandEvent& event);

////@begin wxRichTextBackgroundPage event handler declarations

////@end wxRichTextBackgroundPage event handler declarations

////@begin wxRichTextBackgroundPage member function declarations

    /// Retrieves bitmap resources
    wxBitmap GetBitmapResource( const wxString& name );

    /// Retrieves icon resources
    wxIcon GetIconResource( const wxString& name );
////@end wxRichTextBackgroundPage member function declarations

////@begin wxRichTextBackgroundPage member variables
    wxCheckBox* m_backgroundColourCheckBox;
    wxRichTextColourSwatchCtrl* m_backgroundColourSwatch;
////@end wxRichTextBackgroundPage member variables
};

#endif
    // _RICHTEXTBACKGROUNDPAGE_H_


text:
- Staging: [http://styleguide-staging.cfapps.io](http://styleguide-staging.cfapps.io) - org: pivotal, space: pivotal-ui-staging
- Production: [http://styleguide.pivotal.io](http://styleguide.pivotal.io) - org: pivotal, space: pivotal-ui
- Playground (environment where we can push whatever we want): [http://styleguide-tacos.cfapps.io](http://styleguide-tacos.cfapps.io) - org: pivotal, space: pivotal-ui-playground

## External PR Signature

In order to clearly communicate that we are all on the same team with the same needs for pui projects, use the following signature (updated with the current team, alphabetized):

The Pivotal UI Team
@atomanyih @clairethompson @ctaymor @kennyw12 @nicw @stubbornella

## External PR Flow
When this happens | Do these
------------------|-----------------------
Start story       | Tag story with the name of the external project
Pull request made | Finish story, add a link to PR, and move story to the external PR section of PivotalTracker
Pull request merged in by external team | Rebase dist branch against upstream master, switch package dependency to dist branch, create chore to check for package publichation, deliver story
Package published | Switch package dependency away from dist to newest published version, mark chore complete

## Internal PR Flow

![](http://i.imgur.com/qXhdAPn.png)

## New member checklist

- Add to github, ADT CLA google group, tracker, google drive folder, and calendar invites (ipm, retro, standup, feedback time)
- Add new member's NPM login to the publish helper in `tasks/helpers/publish-helper.js`
- Add new member as owner of dr-frankenstyle or gulp-dr-frankenstyle
- Add github username to the external PR signature (above)
- Add to ~/.gitauthors file on all PUI computers

## Setting up your environment

See the [contribution guidelines](https://github.com/pivotal-cf/pivotal-ui/blob/master/CONTRIBUTING.md#setting-up-your-environment)
for detailed instructions.

## CI

We use [Travis CI](https://travis-ci.org/pivotal-cf/pivotal-ui).

## Deploying the styleguide

The staging styleguide deploys automatically when your changes are merged into
master on github and all the tests go green on Travis CI.  The production
styleguide deploys as part of the release process (see below).

## New components

Once we merge in a PR, it is our responsibility to properly publish new components.

1. Ensure that there is an appropriate example in the README, and that all
   dependencies are listed in the component's `package.json`
3. Ensure that there is an example in the styleguide
1. It can be helpful to set the version number in the `package.json` files to `0.0.1`
   so there is room to fix any errors after first publishing the module
6. Publish the module to NPM (see below)
5. Add the newly published component as a dependency in the top-level `package.json`.
q. Add new css modules as dependencies to the `all` css component.
8. Require/export any new react components in `src/pivotal-ui/javascripts/components.js`.

### Publishing new modules

Our release helper will automatically update the versions of current modules.
If you create a new CSS or React component, you will have to publish the modules
to NPM manually.

First, make sure you are logged into NPM in the terminal

```
npm login
```

Then, do one of the following:

```
gulp css-publish --component <COMPONENT-NAME>
gulp react-publish --component <COMPONENT-NAME>
```

where `<COMPONENT-NAME>` is the name of the folder in `src/pivotal-ui/components/`
or `src/pivotal-ui-react/`.

Once you do this initial publishing, you never have to worry about this module
again.

## Creating a new release

1. Run `gulp release-prepare`. This will:
  - Automatically determine the type of release (patch, major, minor)
  - Updates the version in `package.json`
  - Updates the version in `package.json` for all changed pui modules, and all
    of their dependents.
  - Updates `CHANGELOG.md` with auto-generated release notes
  - Updates `LATEST_CHANGES.md` with auto-generated release notes for the most
    recent change only
  - Creates the `release/pui-vX.X.X` folder

1. If you want to release an alpha, run `gulp release-prepare --alpha` instead
   of the step above. It will update the versions to an alpha of the next
   release (x.x.x-alpha.x).

1. If you want to bump the versions of all components, not just changed
   packages, run `gulp release-prepare --update-all` instead of the step above.

1. If you want to make any changes (e.g. add more docs to the changelog, modify
   a version number, etc.), do that now.

1. Run `gulp ci` - one final check!

9. Run `gulp release-commit` to commit the release.

1. Run `gulp release-push`. This will:
  - Creates a tag for the new version
  - Pushes version bump and new tag to github
  - Creates a draft github release with the auto-generated release notes
  - Publishes all of the updated node packages to npm

1. Be sure to name the release an ice cream flavor.

![](http://images2.fanpop.com/images/photos/3600000/Lucille-Animated-gif-arrested-development-3695222-275-155.gif)

## Setting up a new pairing station:

If your machine was imaged for you on Mavericks, you need to start from the beginning, even though you might not think so.
A machine that starts on Mavericks and upgrades to Yosemite is likely to have installation problems (e.g. You cannot install Nokogiri).

### Verify that your machine is connected to the cloud foundry wired network.
  1. To check, go system preferences -> network and check if your IP falls in 10.80.-.-
    1. If not, send an ask ticket requesting that your machine be put on the Cloud Foundry wired network. They will want machine name and MAC address.

### Boot into network drive
  1. Start up machine while holding down the 'option' key, there should be a network drive available. You may have to wait a little for it to show up.

### Image your machine
  1. Select the pristine Yosemite image (even if it says only for Abhi and Kam) and begin imaging process.
  2. Wait for a while, play some ping pong. It will restart a few times.

### Run Sprout-Wrap
  1. Follow the Readme instructions at https://github.com/pivotal-cf/sprout-wrap
    1. You will need to install xcode, and open it up to accept the agreement
      1. This requires an Apple account. You can get the account ID from an existing computer in the App Store under the 'account' quick link. The password is the 8th oldest Pivotal pairing station password but with the first letter capatilized. If this is not helpful enough send an ask ticket requesting the credentials for apple account access.
    2. In step 4 of the Readme, there is no private key under Volumes. You need to 'ssh-keygen' and then add the new key to your github account
    3. After you have added the ssh-key, you will need to clone something from github (any repo) to confirm github as a host.
    4. In step 6, cd into the 'cf-pivotal-ui' folder in sprout-wrap and run 'soloist'
  2. You will run soloist multiple times. Just keep running it unless you get the same error message twice in a row. You will need to run soloist about 5 times most likely.

### Configure Webstorm
  1. Go to Preferences -> Editor -> Colors and Fonts -> Font and change the font size to 16.
  2. Go to Preferences -> Editor -> Code Style and change tab/indent/continuation indent sizes to 2 for JavaScript/css/scss/html/JSON, and anything else that is needed.
  3. Go to Preferences -> Languages & Frameworks -> JavaScript and set the javascript language version to JSX Harmony.
  4. Copy https://github.com/pivotal/pivotal_ide_prefs/blob/master/pref_sources/RubyMine/templates/jasmine.xml    into     ~/Library/Preferences/WebStorm10/templates/jasmine.xml
    This will give you Jasmine live templates after you restart Webstorm.
  5. Adding a hot key for swapping between test and implementation code
    1. git clone xray
    2. roughly follow the directions from http://pivotallabs.com/swapping-javascript-spec-implementation-rubymine/
      1. Use the script xray/scripts/open_spec_or_impl.sh instead of step 1 in the blog post
      2. Use Webstorm instead of Rubymine
      3. After going to RubyMine -> Preferences -> External Tools -> + in step 2 of the blog post, set 'Working Directory' to $ProjectFileDir$ and uncheck the 'open console' box.

## Acceptance

### Locally Publishing Components for Acceptance
Accepting components with unpublished changes is hard to do in isolation.
If you need an empty project to use that's all set up, check out the [pui-demo-project](https://github.com/pivotal-cf/pui-demo-project).

  7. Go to the pivotal-ui working directory:
  `$ cd pivotal-ui`
  6. Start a Sinopia server (local NPM):
  `$ sinopia .sinopia/config.yaml`
  5. Login with `test`,`test`:
  `$ npm login --registry http://localhost:4873/`
  4. Run the gulp task:
  `$ gulp my-name-is-nic-i-do-acceptance`
  1. Switch to your isolated environment:
  `$ cd ../acceptance-app`
  3. Remove old `node_modules` and reinstall base dependencies (make sure there are no pui-* modules listed as dependencies in the package.json. If there are, remove those lines from the package.json):
  `$ rm -rf node_modules && npm i`
  1. Install unpublished packages from Sinopia:
  `$ npm install [package name] --save --registry http://localhost:4873`
  1. Rebuild the compiled CSS:
  `$ node ./node_modules/.bin/dr-frankenstyle build`
  1. Start the local acceptance server:
  `$ gulp`
  0. Press the green button

### Dev Delivery

Before hitting deliver, the following should be done:
   1. Run `gulp ci`.
   2. Component checked in the the styleguide. Check for
     * Correct appearance, behavior and rendered HTML.
   2. Component checked "in the wild" (outside the styleguide in any form using the NPM modules, such as the [pui-demo-project](https://github.com/pivotal-cf/pui-demo-project)). This can be done with the Sinopia server documented above.
     * Dependencies are correct
     * Sufficient documentation, including of dependencies of the example, to allow you to use the examples assuming no further knowledge about the component
     * Correct appearance, behavior, and HTML
   3. The build on [Travis CI](https://travis-ci.org/) is green.


text:
/*
package tap.nlp.old.openNlp

import tap.UnitSpec

/**
  * Created by andrew@andrewresearch.net on 12/7/17.
  */
class ParserSpec extends UnitSpec {

  val input = "My first lecture started 13 March 2015. This is another sentence."
  val sentences = List("My first lecture started 13 March 2015.","This is another sentence.")
  val tokens = List("My", "first", "lecture", "started", "13", "March", "2015", ".")
  val posTags = List("PRP$", "JJ", "NN", "VBD", "CD", "NNP", "CD", ".")
  val constTree = "(TOP (S (NP (PRP$ My) (JJ first) (NN lecture)) (VP (VBD started) (NP (CD 13) (NNP March) (CD 2015))) (. .)))"

  "sentence" should "parse text into sentences" in {
    val res = Parsers.sentence(input)
    assert(res==sentences)
  }

  "token" should "parse a sentence into tokens" in {
    val res = Parsers.token(sentences.head)
    assert(res==tokens)
  }

  "postag" should "return postags from a list of tokens" in {
    val res = Parsers.posTag(tokens)
    assert(res==posTags)
  }

  "parseTree" should "parse a sentence into tree output as a string" in {
    val res = Parsers.parseTree(tokens.mkString(" "))
    println(res)
    assert(res==constTree)
  }

}
*/


text:
var tape = require("tape"),
    createStore = require("..");

tape("createStore() should create waekmap like store", function(assert) {
    var store = createStore(),
        object = {};

    store.set(object, "{}");
    assert.equals(store.has(object), true);
    assert.equals(store.get(object), "{}");
    assert.equals(store.size(), 1);

    store.remove(object);
    assert.equals(store.has(object), false);
    assert.equals(store.get(object), undefined);
    assert.equals(store.size(), 0);

    store.set(object, "{}");
    store.clear();
    assert.equals(store.get(object), undefined);
    assert.equals(store.size(), 0);

    assert.end();
});


text:
@implementation UITextField (GCDelegateBlock)

- (void)usingBlocks {
    [self registerBlockProxyWithClass:[UITextFieldDelegateImplementationProxy class]];
}

@dynamic blockForShouldBeginEditing;
@dynamic blockForDidBeginEditing;
@dynamic blockForShouldEndEditing;
@dynamic blockForDidEndEditing;
@dynamic blockForShouldReplacementString;
@dynamic blockForShouldClear;
@dynamic blockForShouldReturn;

+ (void)load {
    [self extensionAccessorGenerator];
}

@end


text:
namespace views {

namespace {

// Returns true if bounds passed to window in SetBounds should be treated as
// though they are in screen coordinates.
bool PositionWindowInScreenCoordinates(aura::Window* window) {
  if (window->GetType() == aura::client::WINDOW_TYPE_POPUP)
    return true;

  Widget* widget = Widget::GetWidgetForNativeView(window);
  return widget && widget->is_top_level();
}

}  // namespace

DesktopScreenPositionClient::~DesktopScreenPositionClient() = default;

void DesktopScreenPositionClient::SetBounds(aura::Window* window,
                                            const gfx::Rect& bounds,
                                            const display::Display& display) {
  // TODO(jam): Use the 3rd parameter, |display|.
  aura::Window* root = window->GetRootWindow();

  internal::NativeWidgetPrivate* desktop_native_widget =
      DesktopNativeWidgetAura::ForWindow(root);
  if (desktop_native_widget &&
      desktop_native_widget->GetNativeView() == window) {
    desktop_native_widget->SetBounds(bounds);
    return;
  }

  if (PositionWindowInScreenCoordinates(window)) {
    // The caller expects windows we consider "embedded" to be placed in the
    // screen coordinate system. So we need to offset the root window's
    // position (which is in screen coordinates) from these bounds.

    gfx::Point origin = bounds.origin();
    aura::Window::ConvertPointToTarget(window->parent(), root, &origin);

    gfx::Point host_origin = GetRootWindowOriginInScreen(root);
    origin.Offset(-host_origin.x(), -host_origin.y());
    window->SetBounds(gfx::Rect(origin, bounds.size()));
    return;
  }

  window->SetBounds(bounds);
}

}  // namespace views


text:
using JetBrains.Annotations;

namespace JsonApiDotNetCore.Queries.Expressions;

/// <summary>
/// Represents a non-null constant value, resulting from text such as: equals(firstName,'Jack')
/// </summary>
[PublicAPI]
public class LiteralConstantExpression : IdentifierExpression
{
    public string Value { get; }

    public LiteralConstantExpression(string text)
    {
        ArgumentGuard.NotNull(text);

        Value = text;
    }

    public override TResult Accept<TArgument, TResult>(QueryExpressionVisitor<TArgument, TResult> visitor, TArgument argument)
    {
        return visitor.VisitLiteralConstant(this, argument);
    }

    public override string ToString()
    {
        string value = Value.Replace("\'", "\'\'");
        return $"'{value}'";
    }

    public override string ToFullString()
    {
        return ToString();
    }

    public override bool Equals(object? obj)
    {
        if (ReferenceEquals(this, obj))
        {
            return true;
        }

        if (obj is null || GetType() != obj.GetType())
        {
            return false;
        }

        var other = (LiteralConstantExpression)obj;

        return Value == other.Value;
    }

    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }
}


text:
class CreateTaggings < ActiveRecord::Migration
  def change
    create_table :taggings do |t|
      t.integer :tag_id, :null => false
      t.string :taggable_type, :null => false
      t.integer :taggable_id, :null => false
      t.timestamps
    end
  end
end


text:
package ilc
package feature
package let

trait Traversals extends Syntax {
  type =?>:[A, B] = PartialFunction[A, B]

  //Switch to Scalaz?
  //Does not work.
  //def or[T, U](f: T =?>: U)(g: T => U): T => U =
  //Works.
  def or[T, U](f: PartialFunction[T, U])(g: T => U): T => U =
    x => f applyOrElse (x, g)

  def orIdentity[T](f: T =?>: T): T => T =
    or(f)(identity)

  //Switch to shapeless?
  //Probably yes, since I had to debug this, and it needs to be extended for Let (as lots of existing code), and so on.
  /**
    * Transform a Term by traversing it in post-order.
    * The transformer argument receives a tree where children have been
    * transformed.
    */
  def everywhere: (Term => Term) => (Term => Term) =
    transf => term =>
      transf(term match {
        case App(f, t) => App(everywhere(transf)(f), everywhere(transf)(t))
        case Abs(v, body) => Abs(v, everywhere(transf)(body))
        case Let(v, exp, body) => Let(v, everywhere(transf)(exp), everywhere(transf)(body))
        case other =>
          other
      })

  /**
    * Transform a Term by traversing it in post-order.
    * The transformer argument receives a tree where children have been
    * transformed, together with the original tree (which is instead
    * not passed by everywhere).
    */
  def everywherePrePost: ((Term, Term) => Term) => (Term => Term) =
    transf => term =>
      transf(term, term match {
        case App(f, t) => App(everywherePrePost(transf)(f), everywherePrePost(transf)(t))
        case Abs(v, body) => Abs(v, everywherePrePost(transf)(body))
        case Let(v, exp, body) => Let(v, everywherePrePost(transf)(exp), everywherePrePost(transf)(body))
        case other =>
          other
      })
}


text:
define(['backbone.marionette', 'hbs!cards/acception/templates/dashboardItemview'],

function (Marionette, template) {
  "use strict";
  return Marionette.ItemView.extend({
    tagName: 'li',
    template: template
  });
});


text:
<title>VeriFast error: No matching heap chunks</title>
<link rel="stylesheet" type="text/css" href="verifast-help.css" />

VeriFast Help > Error messages

Error message

No matching heap chunks: chunk pattern

Context

When consuming a field assertion or predicate assertion.

Cause

No chunk matching the field assertion or predicate assertion was found in the symbolic heap.

Notes

The program element that causes the error is shown in red, with a double underline.

The chunk pattern shown in the error message is an evaluated version of the assertion being consumed.

Consumption of a field assertion or predicate assertion occurs implicitly in the following circumstances:

a field access consumes (and then produces) the field predicate;

a <tt>free</tt> statement consumes the field predicates and the malloc block predicate of the struct instance being freed;

an <tt>open</tt> statement consumes the predicate being opened.

Suggested solutions

Ensure that a matching chunk is present in the symbolic heap. Suggested approaches:

Force the current function's caller to provide the chunk. To do so, mention the chunk in the current function's <tt>requires</tt> clause.

If the chunk is a predicate chunk, close the predicate.

If the chunk is contained within a chunk that is present in the symbolic heap, open the containing chunk.

If the chunk can be derived from existing chunks, call a lemma function that derives the chunk.


text:
#import "ORKQuestionStep.h"

NS_ASSUME_NONNULL_BEGIN

@interface ORKQuestionStep ()

- (BOOL)isFormatImmediateNavigation;
- (BOOL)isFormatChoiceWithImageOptions;
- (BOOL)isFormatFitsChoiceCells;
- (BOOL)isFormatTextfield;

- (BOOL)formatRequiresTableView;

- (nullable ORKAnswerFormat *)impliedAnswerFormat;

@end

NS_ASSUME_NONNULL_END


text:
// This file is licensed to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Spines.Tools.AnalyzerBuilder.Precalculation
{
  internal class Hopcroft
  {
    public Hopcroft(IEnumerable<int> normalStates, IEnumerable<IEnumerable<int>> finalStates, int alphabetSize, Func<HashSet<int>, int, IEnumerable<int>> getIncomingStates)
    {
      // From Wikipedia
      // P := {F, Q \ F};
      // W := {F};
      // while (W is not empty) do
      //   choose and remove a set A from W
      //   for each c in Σ do
      //     let X be the set of states for which a transition on c leads to a state in A
      //     for each set Y in P for which X ∩ Y is nonempty and Y \ X is nonempty do
      //       replace Y in P by the two sets X ∩ Y and Y \ X
      //       if Y is in W
      //         replace Y in W by the same two sets
      //       else
      //         if |X ∩ Y| <= |Y \ X|
      //           add X ∩ Y to W
      //         else
      //           add Y \ X to W
      //     end;
      //   end;
      // end;

      var s = Enumerable.Range(0, alphabetSize).ToList(); // The alphabet.
      var n = new HashSet<int>(normalStates); // All nonfinal states.
      var f = finalStates.Select(fs => new HashSet<int>(fs)).ToList();
      var p = new HashSet<HashSet<int>> {n}; // The partition.
      var q = new HashSet<int>(f.Where(ff => ff.Count == 1).Select(ff => ff.First())); // Single element sets of the partition are collected here for performance.
      var w = new HashSet<HashSet<int>>(f.Where(ff => ff.Count > 1)); // The remaining sets to check.

      while (w.Count > 0)
      {
        var a = w.First();
        w.Remove(a);

        foreach (var c in s)
        {
          var x = new HashSet<int>(getIncomingStates(a, c));
          if (x.Count == 0)
          {
            continue; // Intersections with an empty set are always empty.
          }
          foreach (var y in p.ToList()) // p is modified in this loop, but all new elements are inserted into w and checked later.
          {
            if (IsIntersectionEmpty(x, y))
            {
              continue;
            }
            if (IsDifferenceEmpty(y, x))
            {
              continue;
            }
            p.Remove(y);
            var intersection = new HashSet<int>(Intersect(x, y));
            if (intersection.Count > 1)
            {
              p.Add(intersection);
            }
            else
            {
              q.Add(intersection.First());
            }
            var difference = new HashSet<int>(Subtract(y, x));
            if (difference.Count > 1)
            {
              p.Add(difference);
            }
            else
            {
              q.Add(difference.First());
            }

            if (w.Contains(y))
            {
              w.Remove(y);
              w.Add(intersection);
              w.Add(difference);
            }
            else
            {
              w.Add(intersection.Count <= difference.Count ? intersection : difference);
            }
          }
        }
      }

      EquivalenceGroups = p.Concat(q.Select(i => new HashSet<int> {i})).ToList();
    }

    /// <summary>
    /// Each Set in this list contains only elements that are equivalent to each other.
    /// </summary>
    public IReadOnlyList<ISet<int>> EquivalenceGroups { get; }

    private static IEnumerable<int> Subtract(HashSet<int> a, HashSet<int> b)
    {
      return a.Where(aa => !b.Contains(aa));
    }

    private static IEnumerable<int> Intersect(HashSet<int> a, HashSet<int> b)
    {
      return a.Count < b.Count ? a.Where(b.Contains) : b.Where(a.Contains);
    }

    private static bool IsDifferenceEmpty(HashSet<int> a, HashSet<int> b)
    {
      return b.Count >= a.Count && a.All(b.Contains);
    }

    private static bool IsIntersectionEmpty(HashSet<int> a, HashSet<int> b)
    {
      return a.Count < b.Count ? !a.Any(b.Contains) : !b.Any(a.Contains);
    }
  }
}


text:
#pragma once

#include <folly/Conv.h>
#include <folly/dynamic.h>
#include <react/debug/react_native_assert.h>
#include <react/renderer/attributedstring/AttributedString.h>
#include <react/renderer/attributedstring/ParagraphAttributes.h>
#include <react/renderer/attributedstring/TextAttributes.h>
#include <react/renderer/attributedstring/conversions.h>
#include <react/renderer/attributedstring/primitives.h>
#include <react/renderer/core/LayoutableShadowNode.h>
#include <react/renderer/core/PropsParserContext.h>
#include <react/renderer/core/ShadowNode.h>
#include <react/renderer/core/conversions.h>
#include <react/renderer/core/propsConversions.h>
#include <react/renderer/graphics/conversions.h>
#include <cmath>

#ifdef ANDROID
#include <react/renderer/mapbuffer/MapBuffer.h>
#include <react/renderer/mapbuffer/MapBufferBuilder.h>
#endif

#include <glog/logging.h>

namespace facebook {
namespace react {

inline std::string toString(const DynamicTypeRamp &dynamicTypeRamp) {
  switch (dynamicTypeRamp) {
    case DynamicTypeRamp::Caption2:
      return "caption2";
    case DynamicTypeRamp::Caption1:
      return "caption1";
    case DynamicTypeRamp::Footnote:
      return "footnote";
    case DynamicTypeRamp::Subheadline:
      return "subheadline";
    case DynamicTypeRamp::Callout:
      return "callout";
    case DynamicTypeRamp::Body:
      return "body";
    case DynamicTypeRamp::Headline:
      return "headline";
    case DynamicTypeRamp::Title3:
      return "title3";
    case DynamicTypeRamp::Title2:
      return "title2";
    case DynamicTypeRamp::Title1:
      return "title1";
    case DynamicTypeRamp::LargeTitle:
      return "largeTitle";
  }

  LOG(ERROR) << "Unsupported DynamicTypeRamp value";
  react_native_assert(false);

  // Sane default in case of parsing errors
  return "body";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    DynamicTypeRamp &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "caption2") {
      result = DynamicTypeRamp::Caption2;
    } else if (string == "caption1") {
      result = DynamicTypeRamp::Caption1;
    } else if (string == "footnote") {
      result = DynamicTypeRamp::Footnote;
    } else if (string == "subheadline") {
      result = DynamicTypeRamp::Subheadline;
    } else if (string == "callout") {
      result = DynamicTypeRamp::Callout;
    } else if (string == "body") {
      result = DynamicTypeRamp::Body;
    } else if (string == "headline") {
      result = DynamicTypeRamp::Headline;
    } else if (string == "title3") {
      result = DynamicTypeRamp::Title3;
    } else if (string == "title2") {
      result = DynamicTypeRamp::Title2;
    } else if (string == "title1") {
      result = DynamicTypeRamp::Title1;
    } else if (string == "largeTitle") {
      result = DynamicTypeRamp::LargeTitle;
    } else {
      // sane default
      LOG(ERROR) << "Unsupported DynamicTypeRamp value: " << string;
      react_native_assert(false);
      result = DynamicTypeRamp::Body;
    }
    return;
  }

  LOG(ERROR) << "Unsupported DynamicTypeRamp type";
  react_native_assert(false);

  // Sane default in case of parsing errors
  result = DynamicTypeRamp::Body;
}

inline std::string toString(const EllipsizeMode &ellipsisMode) {
  switch (ellipsisMode) {
    case EllipsizeMode::Clip:
      return "clip";
    case EllipsizeMode::Head:
      return "head";
    case EllipsizeMode::Tail:
      return "tail";
    case EllipsizeMode::Middle:
      return "middle";
  }

  LOG(ERROR) << "Unsupported EllipsizeMode value";
  react_native_assert(false);

  // Sane default in case of parsing errors
  return "tail";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    EllipsizeMode &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "clip") {
      result = EllipsizeMode::Clip;
    } else if (string == "head") {
      result = EllipsizeMode::Head;
    } else if (string == "tail") {
      result = EllipsizeMode::Tail;
    } else if (string == "middle") {
      result = EllipsizeMode::Middle;
    } else {
      // sane default
      LOG(ERROR) << "Unsupported EllipsizeMode value: " << string;
      react_native_assert(false);
      result = EllipsizeMode::Tail;
    }
    return;
  }

  LOG(ERROR) << "Unsupported EllipsizeMode type";
  react_native_assert(false);

  // Sane default in case of parsing errors
  result = EllipsizeMode::Tail;
}

inline std::string toString(const TextBreakStrategy &textBreakStrategy) {
  switch (textBreakStrategy) {
    case TextBreakStrategy::Simple:
      return "simple";
    case TextBreakStrategy::HighQuality:
      return "highQuality";
    case TextBreakStrategy::Balanced:
      return "balanced";
  }

  LOG(ERROR) << "Unsupported TextBreakStrategy value";
  react_native_assert(false);
  return "highQuality";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    TextBreakStrategy &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "simple") {
      result = TextBreakStrategy::Simple;
    } else if (string == "highQuality") {
      result = TextBreakStrategy::HighQuality;
    } else if (string == "balanced") {
      result = TextBreakStrategy::Balanced;
    } else {
      // sane default
      LOG(ERROR) << "Unsupported TextBreakStrategy value: " << string;
      react_native_assert(false);
      result = TextBreakStrategy::HighQuality;
    }
    return;
  }

  LOG(ERROR) << "Unsupported TextBreakStrategy type";
  react_native_assert(false);
  result = TextBreakStrategy::HighQuality;
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    FontWeight &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "normal") {
      result = FontWeight::Regular;
    } else if (string == "regular") {
      result = FontWeight::Regular;
    } else if (string == "bold") {
      result = FontWeight::Bold;
    } else if (string == "100") {
      result = FontWeight::Weight100;
    } else if (string == "200") {
      result = FontWeight::Weight200;
    } else if (string == "300") {
      result = FontWeight::Weight300;
    } else if (string == "400") {
      result = FontWeight::Weight400;
    } else if (string == "500") {
      result = FontWeight::Weight500;
    } else if (string == "600") {
      result = FontWeight::Weight600;
    } else if (string == "700") {
      result = FontWeight::Weight700;
    } else if (string == "800") {
      result = FontWeight::Weight800;
    } else if (string == "900") {
      result = FontWeight::Weight900;
    } else {
      LOG(ERROR) << "Unsupported FontWeight value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = FontWeight::Regular;
    }
    return;
  }

  LOG(ERROR) << "Unsupported FontWeight type";
  react_native_assert(false);
  result = FontWeight::Regular;
}

inline std::string toString(const FontWeight &fontWeight) {
  return folly::to<std::string>((int)fontWeight);
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    FontStyle &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "normal") {
      result = FontStyle::Normal;
    } else if (string == "italic") {
      result = FontStyle::Italic;
    } else if (string == "oblique") {
      result = FontStyle::Oblique;
    } else {
      LOG(ERROR) << "Unsupported FontStyle value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = FontStyle::Normal;
    }
    return;
  }

  LOG(ERROR) << "Unsupported FontStyle type";
  react_native_assert(false);
  // sane default for prod
  result = FontStyle::Normal;
}

inline std::string toString(const FontStyle &fontStyle) {
  switch (fontStyle) {
    case FontStyle::Normal:
      return "normal";
    case FontStyle::Italic:
      return "italic";
    case FontStyle::Oblique:
      return "oblique";
  }

  LOG(ERROR) << "Unsupported FontStyle value";
  react_native_assert(false);
  // sane default for prod
  return "normal";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    FontVariant &result) {
  react_native_assert(value.hasType<std::vector<std::string>>());
  result = FontVariant::Default;
  if (value.hasType<std::vector<std::string>>()) {
    auto items = std::vector<std::string>{value};
    for (const auto &item : items) {
      if (item == "small-caps") {
        result = (FontVariant)((int)result | (int)FontVariant::SmallCaps);
      } else if (item == "oldstyle-nums") {
        result = (FontVariant)((int)result | (int)FontVariant::OldstyleNums);
      } else if (item == "lining-nums") {
        result = (FontVariant)((int)result | (int)FontVariant::LiningNums);
      } else if (item == "tabular-nums") {
        result = (FontVariant)((int)result | (int)FontVariant::TabularNums);
      } else if (item == "proportional-nums") {
        result =
            (FontVariant)((int)result | (int)FontVariant::ProportionalNums);
      } else {
        LOG(ERROR) << "Unsupported FontVariant value: " << item;
        react_native_assert(false);
      }
      continue;
    }
  } else {
    LOG(ERROR) << "Unsupported FontVariant type";
  }
}

inline std::string toString(const FontVariant &fontVariant) {
  auto result = std::string{};
  auto separator = std::string{", "};
  if ((int)fontVariant & (int)FontVariant::SmallCaps) {
    result += "small-caps" + separator;
  }
  if ((int)fontVariant & (int)FontVariant::OldstyleNums) {
    result += "oldstyle-nums" + separator;
  }
  if ((int)fontVariant & (int)FontVariant::LiningNums) {
    result += "lining-nums" + separator;
  }
  if ((int)fontVariant & (int)FontVariant::TabularNums) {
    result += "tabular-nums" + separator;
  }
  if ((int)fontVariant & (int)FontVariant::ProportionalNums) {
    result += "proportional-nums" + separator;
  }

  if (!result.empty()) {
    result.erase(result.length() - separator.length());
  }

  return result;
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    TextTransform &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "none") {
      result = TextTransform::None;
    } else if (string == "uppercase") {
      result = TextTransform::Uppercase;
    } else if (string == "lowercase") {
      result = TextTransform::Lowercase;
    } else if (string == "capitalize") {
      result = TextTransform::Capitalize;
    } else if (string == "unset") {
      result = TextTransform::Unset;
    } else {
      LOG(ERROR) << "Unsupported TextTransform value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = TextTransform::None;
    }
    return;
  }

  LOG(ERROR) << "Unsupported TextTransform type";
  react_native_assert(false);
  // sane default for prod
  result = TextTransform::None;
}

inline std::string toString(const TextTransform &textTransform) {
  switch (textTransform) {
    case TextTransform::None:
      return "none";
    case TextTransform::Uppercase:
      return "uppercase";
    case TextTransform::Lowercase:
      return "lowercase";
    case TextTransform::Capitalize:
      return "capitalize";
    case TextTransform::Unset:
      return "unset";
  }

  LOG(ERROR) << "Unsupported TextTransform value";
  react_native_assert(false);
  // sane default for prod
  return "none";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    TextAlignment &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "auto") {
      result = TextAlignment::Natural;
    } else if (string == "left") {
      result = TextAlignment::Left;
    } else if (string == "center") {
      result = TextAlignment::Center;
    } else if (string == "right") {
      result = TextAlignment::Right;
    } else if (string == "justify") {
      result = TextAlignment::Justified;
    } else {
      LOG(ERROR) << "Unsupported TextAlignment value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = TextAlignment::Natural;
    }
    return;
  }

  LOG(ERROR) << "Unsupported TextAlignment type";
  // sane default for prod
  result = TextAlignment::Natural;
}

inline std::string toString(const TextAlignment &textAlignment) {
  switch (textAlignment) {
    case TextAlignment::Natural:
      return "auto";
    case TextAlignment::Left:
      return "left";
    case TextAlignment::Center:
      return "center";
    case TextAlignment::Right:
      return "right";
    case TextAlignment::Justified:
      return "justified";
  }

  LOG(ERROR) << "Unsupported TextAlignment value";
  // sane default for prod
  return "auto";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    WritingDirection &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "natural" || string == "auto") {
      result = WritingDirection::Natural;
    } else if (string == "ltr") {
      result = WritingDirection::LeftToRight;
    } else if (string == "rtl") {
      result = WritingDirection::RightToLeft;
    } else {
      LOG(ERROR) << "Unsupported WritingDirection value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = WritingDirection::Natural;
    }
    return;
  }

  LOG(ERROR) << "Unsupported WritingDirection type";
  // sane default for prod
  result = WritingDirection::Natural;
}

inline std::string toString(const WritingDirection &writingDirection) {
  switch (writingDirection) {
    case WritingDirection::Natural:
      return "auto";
    case WritingDirection::LeftToRight:
      return "ltr";
    case WritingDirection::RightToLeft:
      return "rtl";
  }

  LOG(ERROR) << "Unsupported WritingDirection value";
  // sane default for prod
  return "auto";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    LineBreakStrategy &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "none") {
      result = LineBreakStrategy::None;
    } else if (string == "push-out") {
      result = LineBreakStrategy::PushOut;
    } else if (string == "hangul-word") {
      result = LineBreakStrategy::HangulWordPriority;
    } else if (string == "standard") {
      result = LineBreakStrategy::Standard;
    } else {
      LOG(ERROR) << "Unsupported LineBreakStrategy value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = LineBreakStrategy::None;
    }
    return;
  }

  LOG(ERROR) << "Unsupported LineBreakStrategy type";
  // sane default for prod
  result = LineBreakStrategy::None;
}

inline std::string toString(const LineBreakStrategy &lineBreakStrategy) {
  switch (lineBreakStrategy) {
    case LineBreakStrategy::None:
      return "none";
    case LineBreakStrategy::PushOut:
      return "push-out";
    case LineBreakStrategy::HangulWordPriority:
      return "hangul-word";
    case LineBreakStrategy::Standard:
      return "standard";
  }

  LOG(ERROR) << "Unsupported LineBreakStrategy value";
  // sane default for prod
  return "none";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    TextDecorationLineType &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "none") {
      result = TextDecorationLineType::None;
    } else if (string == "underline") {
      result = TextDecorationLineType::Underline;
    } else if (string == "strikethrough" || string == "line-through") {
      // TODO: remove "line-through" after deprecation
      result = TextDecorationLineType::Strikethrough;
    } else if (
        string == "underline-strikethrough" ||
        string == "underline line-through") {
      // TODO: remove "underline line-through" after "line-through" deprecation
      result = TextDecorationLineType::UnderlineStrikethrough;
    } else {
      LOG(ERROR) << "Unsupported TextDecorationLineType value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = TextDecorationLineType::None;
    }
    return;
  }

  LOG(ERROR) << "Unsupported TextDecorationLineType type";
  // sane default for prod
  result = TextDecorationLineType::None;
}

inline std::string toString(
    const TextDecorationLineType &textDecorationLineType) {
  switch (textDecorationLineType) {
    case TextDecorationLineType::None:
      return "none";
    case TextDecorationLineType::Underline:
      return "underline";
    case TextDecorationLineType::Strikethrough:
      return "strikethrough";
    case TextDecorationLineType::UnderlineStrikethrough:
      return "underline-strikethrough";
  }

  LOG(ERROR) << "Unsupported TextDecorationLineType value";
  react_native_assert(false);
  // sane default for prod
  return "none";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    TextDecorationStyle &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "solid") {
      result = TextDecorationStyle::Solid;
    } else if (string == "double") {
      result = TextDecorationStyle::Double;
    } else if (string == "dotted") {
      result = TextDecorationStyle::Dotted;
    } else if (string == "dashed") {
      result = TextDecorationStyle::Dashed;
    } else {
      LOG(ERROR) << "Unsupported TextDecorationStyle value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = TextDecorationStyle::Solid;
    }
    return;
  }

  LOG(ERROR) << "Unsupported TextDecorationStyle type";
  // sane default for prod
  result = TextDecorationStyle::Solid;
}

inline std::string toString(const TextDecorationStyle &textDecorationStyle) {
  switch (textDecorationStyle) {
    case TextDecorationStyle::Solid:
      return "solid";
    case TextDecorationStyle::Double:
      return "double";
    case TextDecorationStyle::Dotted:
      return "dotted";
    case TextDecorationStyle::Dashed:
      return "dashed";
  }

  LOG(ERROR) << "Unsupported TextDecorationStyle value";
  react_native_assert(false);
  // sane default for prod
  return "solid";
}

inline std::string toString(const AccessibilityRole &accessibilityRole) {
  switch (accessibilityRole) {
    case AccessibilityRole::None:
      return "none";
    case AccessibilityRole::Button:
      return "button";
    case AccessibilityRole::Link:
      return "link";
    case AccessibilityRole::Search:
      return "search";
    case AccessibilityRole::Image:
      return "image";
    case AccessibilityRole::Imagebutton:
      return "imagebutton";
    case AccessibilityRole::Keyboardkey:
      return "keyboardkey";
    case AccessibilityRole::Text:
      return "text";
    case AccessibilityRole::Adjustable:
      return "adjustable";
    case AccessibilityRole::Summary:
      return "summary";
    case AccessibilityRole::Header:
      return "header";
    case AccessibilityRole::Alert:
      return "alert";
    case AccessibilityRole::Checkbox:
      return "checkbox";
    case AccessibilityRole::Combobox:
      return "combobox";
    case AccessibilityRole::Menu:
      return "menu";
    case AccessibilityRole::Menubar:
      return "menubar";
    case AccessibilityRole::Menuitem:
      return "menuitem";
    case AccessibilityRole::Progressbar:
      return "progressbar";
    case AccessibilityRole::Radio:
      return "radio";
    case AccessibilityRole::Radiogroup:
      return "radiogroup";
    case AccessibilityRole::Scrollbar:
      return "scrollbar";
    case AccessibilityRole::Spinbutton:
      return "spinbutton";
    case AccessibilityRole::Switch:
      return "switch";
    case AccessibilityRole::Tab:
      return "tab";
    case AccessibilityRole::TabBar:
      return "tabbar";
    case AccessibilityRole::Tablist:
      return "tablist";
    case AccessibilityRole::Timer:
      return "timer";
    case AccessibilityRole::Toolbar:
      return "toolbar";
  }

  LOG(ERROR) << "Unsupported AccessibilityRole value";
  react_native_assert(false);
  // sane default for prod
  return "none";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    AccessibilityRole &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "none") {
      result = AccessibilityRole::None;
    } else if (string == "button") {
      result = AccessibilityRole::Button;
    } else if (string == "link") {
      result = AccessibilityRole::Link;
    } else if (string == "search") {
      result = AccessibilityRole::Search;
    } else if (string == "image") {
      result = AccessibilityRole::Image;
    } else if (string == "imagebutton") {
      result = AccessibilityRole::Imagebutton;
    } else if (string == "keyboardkey") {
      result = AccessibilityRole::Keyboardkey;
    } else if (string == "text") {
      result = AccessibilityRole::Text;
    } else if (string == "adjustable") {
      result = AccessibilityRole::Adjustable;
    } else if (string == "summary") {
      result = AccessibilityRole::Summary;
    } else if (string == "header") {
      result = AccessibilityRole::Header;
    } else if (string == "alert") {
      result = AccessibilityRole::Alert;
    } else if (string == "checkbox") {
      result = AccessibilityRole::Checkbox;
    } else if (string == "combobox") {
      result = AccessibilityRole::Combobox;
    } else if (string == "menu") {
      result = AccessibilityRole::Menu;
    } else if (string == "menubar") {
      result = AccessibilityRole::Menubar;
    } else if (string == "menuitem") {
      result = AccessibilityRole::Menuitem;
    } else if (string == "progressbar") {
      result = AccessibilityRole::Progressbar;
    } else if (string == "radio") {
      result = AccessibilityRole::Radio;
    } else if (string == "radiogroup") {
      result = AccessibilityRole::Radiogroup;
    } else if (string == "scrollbar") {
      result = AccessibilityRole::Scrollbar;
    } else if (string == "spinbutton") {
      result = AccessibilityRole::Spinbutton;
    } else if (string == "switch") {
      result = AccessibilityRole::Switch;
    } else if (string == "tab") {
      result = AccessibilityRole::Tab;
    } else if (string == "tabbar") {
      result = AccessibilityRole::TabBar;
    } else if (string == "tablist") {
      result = AccessibilityRole::Tablist;
    } else if (string == "timer") {
      result = AccessibilityRole::Timer;
    } else if (string == "toolbar") {
      result = AccessibilityRole::Toolbar;
    } else {
      LOG(ERROR) << "Unsupported AccessibilityRole value: " << string;
      react_native_assert(false);
      // sane default for prod
      result = AccessibilityRole::None;
    }
    return;
  }

  LOG(ERROR) << "Unsupported AccessibilityRole type";
  react_native_assert(false);
  // sane default for prod
  result = AccessibilityRole::None;
}

inline std::string toString(const HyphenationFrequency &hyphenationFrequency) {
  switch (hyphenationFrequency) {
    case HyphenationFrequency::None:
      return "none";
    case HyphenationFrequency::Normal:
      return "normal";
    case HyphenationFrequency::Full:
      return "full";
  }

  LOG(ERROR) << "Unsupported HyphenationFrequency value";
  react_native_assert(false);
  return "none";
}

inline void fromRawValue(
    const PropsParserContext &context,
    const RawValue &value,
    HyphenationFrequency &result) {
  react_native_assert(value.hasType<std::string>());
  if (value.hasType<std::string>()) {
    auto string = (std::string)value;
    if (string == "none") {
      result = HyphenationFrequency::None;
    } else if (string == "normal") {
      result = HyphenationFrequency::Normal;
    } else if (string == "full") {
      result = HyphenationFrequency::Full;
    } else {
      // sane default
      LOG(ERROR) << "Unsupported HyphenationFrequency value: " << string;
      react_native_assert(false);
      result = HyphenationFrequency::None;
    }
    return;
  }

  LOG(ERROR) << "Unsupported HyphenationFrequency type";
  react_native_assert(false);
  result = HyphenationFrequency::None;
}

inline ParagraphAttributes convertRawProp(
    const PropsParserContext &context,
    RawProps const &rawProps,
    ParagraphAttributes const &sourceParagraphAttributes,
    ParagraphAttributes const &defaultParagraphAttributes) {
  auto paragraphAttributes = ParagraphAttributes{};

  paragraphAttributes.maximumNumberOfLines = convertRawProp(
      context,
      rawProps,
      "numberOfLines",
      sourceParagraphAttributes.maximumNumberOfLines,
      defaultParagraphAttributes.maximumNumberOfLines);
  paragraphAttributes.ellipsizeMode = convertRawProp(
      context,
      rawProps,
      "ellipsizeMode",
      sourceParagraphAttributes.ellipsizeMode,
      defaultParagraphAttributes.ellipsizeMode);
  paragraphAttributes.textBreakStrategy = convertRawProp(
      context,
      rawProps,
      "textBreakStrategy",
      sourceParagraphAttributes.textBreakStrategy,
      defaultParagraphAttributes.textBreakStrategy);
  paragraphAttributes.adjustsFontSizeToFit = convertRawProp(
      context,
      rawProps,
      "adjustsFontSizeToFit",
      sourceParagraphAttributes.adjustsFontSizeToFit,
      defaultParagraphAttributes.adjustsFontSizeToFit);
  paragraphAttributes.minimumFontSize = convertRawProp(
      context,
      rawProps,
      "minimumFontSize",
      sourceParagraphAttributes.minimumFontSize,
      defaultParagraphAttributes.minimumFontSize);
  paragraphAttributes.maximumFontSize = convertRawProp(
      context,
      rawProps,
      "maximumFontSize",
      sourceParagraphAttributes.maximumFontSize,
      defaultParagraphAttributes.maximumFontSize);
  paragraphAttributes.includeFontPadding = convertRawProp(
      context,
      rawProps,
      "includeFontPadding",
      sourceParagraphAttributes.includeFontPadding,
      defaultParagraphAttributes.includeFontPadding);
  paragraphAttributes.android_hyphenationFrequency = convertRawProp(
      context,
      rawProps,
      "android_hyphenationFrequency",
      sourceParagraphAttributes.android_hyphenationFrequency,
      defaultParagraphAttributes.android_hyphenationFrequency);

  return paragraphAttributes;
}

inline void fromRawValue(
    const PropsParserContext &context,
    RawValue const &value,
    AttributedString::Range &result) {
  auto map = (butter::map<std::string, int>)value;

  auto start = map.find("start");
  if (start != map.end()) {
    result.location = start->second;
  }
  auto end = map.find("end");
  if (end != map.end()) {
    result.length = start->second - result.location;
  }
}

inline std::string toString(AttributedString::Range const &range) {
  return "{location: " + folly::to<std::string>(range.location) +
      ", length: " + folly::to<std::string>(range.length) + "}";
}

#ifdef ANDROID

inline folly::dynamic toDynamic(
    const ParagraphAttributes &paragraphAttributes) {
  auto values = folly::dynamic::object();
  values("maximumNumberOfLines", paragraphAttributes.maximumNumberOfLines);
  values("ellipsizeMode", toString(paragraphAttributes.ellipsizeMode));
  values("textBreakStrategy", toString(paragraphAttributes.textBreakStrategy));
  values("adjustsFontSizeToFit", paragraphAttributes.adjustsFontSizeToFit);
  values("includeFontPadding", paragraphAttributes.includeFontPadding);
  values(
      "android_hyphenationFrequency",
      toString(paragraphAttributes.android_hyphenationFrequency));

  return values;
}

inline folly::dynamic toDynamic(const FontVariant &fontVariant) {
  auto result = folly::dynamic::array();
  if ((int)fontVariant & (int)FontVariant::SmallCaps) {
    result.push_back("small-caps");
  }
  if ((int)fontVariant & (int)FontVariant::OldstyleNums) {
    result.push_back("oldstyle-nums");
  }
  if ((int)fontVariant & (int)FontVariant::LiningNums) {
    result.push_back("lining-nums");
  }
  if ((int)fontVariant & (int)FontVariant::TabularNums) {
    result.push_back("tabular-nums");
  }
  if ((int)fontVariant & (int)FontVariant::ProportionalNums) {
    result.push_back("proportional-nums");
  }

  return result;
}

inline folly::dynamic toDynamic(const TextAttributes &textAttributes) {
  auto _textAttributes = folly::dynamic::object();
  if (textAttributes.foregroundColor) {
    _textAttributes(
        "foregroundColor", toAndroidRepr(textAttributes.foregroundColor));
  }
  if (textAttributes.backgroundColor) {
    _textAttributes(
        "backgroundColor", toAndroidRepr(textAttributes.backgroundColor));
  }
  if (!std::isnan(textAttributes.opacity)) {
    _textAttributes("opacity", textAttributes.opacity);
  }
  if (!textAttributes.fontFamily.empty()) {
    _textAttributes("fontFamily", textAttributes.fontFamily);
  }
  if (!std::isnan(textAttributes.fontSize)) {
    _textAttributes("fontSize", textAttributes.fontSize);
  }
  if (!std::isnan(textAttributes.fontSizeMultiplier)) {
    _textAttributes("fontSizeMultiplier", textAttributes.fontSizeMultiplier);
  }
  if (textAttributes.fontWeight.has_value()) {
    _textAttributes("fontWeight", toString(*textAttributes.fontWeight));
  }
  if (textAttributes.fontStyle.has_value()) {
    _textAttributes("fontStyle", toString(*textAttributes.fontStyle));
  }
  if (textAttributes.fontVariant.has_value()) {
    _textAttributes("fontVariant", toDynamic(*textAttributes.fontVariant));
  }
  if (textAttributes.allowFontScaling.has_value()) {
    _textAttributes("allowFontScaling", *textAttributes.allowFontScaling);
  }
  if (!std::isnan(textAttributes.letterSpacing)) {
    _textAttributes("letterSpacing", textAttributes.letterSpacing);
  }
  if (textAttributes.textTransform.has_value()) {
    _textAttributes("textTransform", toString(*textAttributes.textTransform));
  }
  if (!std::isnan(textAttributes.lineHeight)) {
    _textAttributes("lineHeight", textAttributes.lineHeight);
  }
  if (textAttributes.alignment.has_value()) {
    _textAttributes("alignment", toString(*textAttributes.alignment));
  }
  if (textAttributes.baseWritingDirection.has_value()) {
    _textAttributes(
        "baseWritingDirection", toString(*textAttributes.baseWritingDirection));
  }
  if (textAttributes.lineBreakStrategy.has_value()) {
    _textAttributes(
        "lineBreakStrategyIOS", toString(*textAttributes.lineBreakStrategy));
  }
  // Decoration
  if (textAttributes.textDecorationColor) {
    _textAttributes(
        "textDecorationColor",
        toAndroidRepr(textAttributes.textDecorationColor));
  }
  if (textAttributes.textDecorationLineType.has_value()) {
    _textAttributes(
        "textDecorationLine", toString(*textAttributes.textDecorationLineType));
  }
  if (textAttributes.textDecorationStyle.has_value()) {
    _textAttributes(
        "textDecorationStyle", toString(*textAttributes.textDecorationStyle));
  }
  // Shadow
  // textShadowOffset = textAttributes.textShadowOffset.has_value() ?
  // textAttributes.textShadowOffset.value() : textShadowOffset;
  if (!std::isnan(textAttributes.textShadowRadius)) {
    _textAttributes("textShadowRadius", textAttributes.textShadowRadius);
  }
  if (textAttributes.textShadowColor) {
    _textAttributes(
        "textShadowColor", toAndroidRepr(textAttributes.textShadowColor));
  }
  // Special
  if (textAttributes.isHighlighted.has_value()) {
    _textAttributes("isHighlighted", *textAttributes.isHighlighted);
  }
  if (textAttributes.layoutDirection.has_value()) {
    _textAttributes(
        "layoutDirection", toString(*textAttributes.layoutDirection));
  }
  if (textAttributes.accessibilityRole.has_value()) {
    _textAttributes(
        "accessibilityRole", toString(*textAttributes.accessibilityRole));
  }
  return _textAttributes;
}

inline folly::dynamic toDynamic(const AttributedString &attributedString) {
  auto value = folly::dynamic::object();
  auto fragments = folly::dynamic::array();
  for (auto fragment : attributedString.getFragments()) {
    folly::dynamic dynamicFragment = folly::dynamic::object();
    dynamicFragment["string"] = fragment.string;
    if (fragment.parentShadowView.componentHandle) {
      dynamicFragment["reactTag"] = fragment.parentShadowView.tag;
    }
    if (fragment.isAttachment()) {
      dynamicFragment["isAttachment"] = true;
      dynamicFragment["width"] =
          fragment.parentShadowView.layoutMetrics.frame.size.width;
      dynamicFragment["height"] =
          fragment.parentShadowView.layoutMetrics.frame.size.height;
    }
    dynamicFragment["textAttributes"] = toDynamic(fragment.textAttributes);
    fragments.push_back(dynamicFragment);
  }
  value("fragments", fragments);
  value(
      "hash", std::hash<facebook::react::AttributedString>{}(attributedString));
  value("string", attributedString.getString());
  return value;
}

inline folly::dynamic toDynamic(AttributedString::Range const &range) {
  folly::dynamic dynamicValue = folly::dynamic::object();
  dynamicValue["location"] = range.location;
  dynamicValue["length"] = range.length;
  return dynamicValue;
}

// constants for AttributedString serialization
constexpr static MapBuffer::Key AS_KEY_HASH = 0;
constexpr static MapBuffer::Key AS_KEY_STRING = 1;
constexpr static MapBuffer::Key AS_KEY_FRAGMENTS = 2;
constexpr static MapBuffer::Key AS_KEY_CACHE_ID = 3;

// constants for Fragment serialization
constexpr static MapBuffer::Key FR_KEY_STRING = 0;
constexpr static MapBuffer::Key FR_KEY_REACT_TAG = 1;
constexpr static MapBuffer::Key FR_KEY_IS_ATTACHMENT = 2;
constexpr static MapBuffer::Key FR_KEY_WIDTH = 3;
constexpr static MapBuffer::Key FR_KEY_HEIGHT = 4;
constexpr static MapBuffer::Key FR_KEY_TEXT_ATTRIBUTES = 5;

// constants for Text Attributes serialization
constexpr static MapBuffer::Key TA_KEY_FOREGROUND_COLOR = 0;
constexpr static MapBuffer::Key TA_KEY_BACKGROUND_COLOR = 1;
constexpr static MapBuffer::Key TA_KEY_OPACITY = 2;
constexpr static MapBuffer::Key TA_KEY_FONT_FAMILY = 3;
constexpr static MapBuffer::Key TA_KEY_FONT_SIZE = 4;
constexpr static MapBuffer::Key TA_KEY_FONT_SIZE_MULTIPLIER = 5;
constexpr static MapBuffer::Key TA_KEY_FONT_WEIGHT = 6;
constexpr static MapBuffer::Key TA_KEY_FONT_STYLE = 7;
constexpr static MapBuffer::Key TA_KEY_FONT_VARIANT = 8;
constexpr static MapBuffer::Key TA_KEY_ALLOW_FONT_SCALING = 9;
constexpr static MapBuffer::Key TA_KEY_LETTER_SPACING = 10;
constexpr static MapBuffer::Key TA_KEY_LINE_HEIGHT = 11;
constexpr static MapBuffer::Key TA_KEY_ALIGNMENT = 12;
constexpr static MapBuffer::Key TA_KEY_BEST_WRITING_DIRECTION = 13;
constexpr static MapBuffer::Key TA_KEY_TEXT_DECORATION_COLOR = 14;
constexpr static MapBuffer::Key TA_KEY_TEXT_DECORATION_LINE = 15;
constexpr static MapBuffer::Key TA_KEY_TEXT_DECORATION_STYLE = 16;
constexpr static MapBuffer::Key TA_KEY_TEXT_SHADOW_RADIUS = 18;
constexpr static MapBuffer::Key TA_KEY_TEXT_SHADOW_COLOR = 19;
constexpr static MapBuffer::Key TA_KEY_IS_HIGHLIGHTED = 20;
constexpr static MapBuffer::Key TA_KEY_LAYOUT_DIRECTION = 21;
constexpr static MapBuffer::Key TA_KEY_ACCESSIBILITY_ROLE = 22;
constexpr static MapBuffer::Key TA_KEY_LINE_BREAK_STRATEGY = 23;

// constants for ParagraphAttributes serialization
constexpr static MapBuffer::Key PA_KEY_MAX_NUMBER_OF_LINES = 0;
constexpr static MapBuffer::Key PA_KEY_ELLIPSIZE_MODE = 1;
constexpr static MapBuffer::Key PA_KEY_TEXT_BREAK_STRATEGY = 2;
constexpr static MapBuffer::Key PA_KEY_ADJUST_FONT_SIZE_TO_FIT = 3;
constexpr static MapBuffer::Key PA_KEY_INCLUDE_FONT_PADDING = 4;
constexpr static MapBuffer::Key PA_KEY_HYPHENATION_FREQUENCY = 5;

inline MapBuffer toMapBuffer(const ParagraphAttributes &paragraphAttributes) {
  auto builder = MapBufferBuilder();
  builder.putInt(
      PA_KEY_MAX_NUMBER_OF_LINES, paragraphAttributes.maximumNumberOfLines);
  builder.putString(
      PA_KEY_ELLIPSIZE_MODE, toString(paragraphAttributes.ellipsizeMode));
  builder.putString(
      PA_KEY_TEXT_BREAK_STRATEGY,
      toString(paragraphAttributes.textBreakStrategy));
  builder.putBool(
      PA_KEY_ADJUST_FONT_SIZE_TO_FIT, paragraphAttributes.adjustsFontSizeToFit);
  builder.putBool(
      PA_KEY_INCLUDE_FONT_PADDING, paragraphAttributes.includeFontPadding);
  builder.putString(
      PA_KEY_HYPHENATION_FREQUENCY,
      toString(paragraphAttributes.android_hyphenationFrequency));

  return builder.build();
}

inline MapBuffer toMapBuffer(const FontVariant &fontVariant) {
  auto builder = MapBufferBuilder();
  int index = 0;
  if ((int)fontVariant & (int)FontVariant::SmallCaps) {
    builder.putString(index++, "small-caps");
  }
  if ((int)fontVariant & (int)FontVariant::OldstyleNums) {
    builder.putString(index++, "oldstyle-nums");
  }
  if ((int)fontVariant & (int)FontVariant::LiningNums) {
    builder.putString(index++, "lining-nums");
  }
  if ((int)fontVariant & (int)FontVariant::TabularNums) {
    builder.putString(index++, "tabular-nums");
  }
  if ((int)fontVariant & (int)FontVariant::ProportionalNums) {
    builder.putString(index++, "proportional-nums");
  }

  return builder.build();
}

inline MapBuffer toMapBuffer(const TextAttributes &textAttributes) {
  auto builder = MapBufferBuilder();
  if (textAttributes.foregroundColor) {
    builder.putInt(
        TA_KEY_FOREGROUND_COLOR, toAndroidRepr(textAttributes.foregroundColor));
  }
  if (textAttributes.backgroundColor) {
    builder.putInt(
        TA_KEY_BACKGROUND_COLOR, toAndroidRepr(textAttributes.backgroundColor));
  }
  if (!std::isnan(textAttributes.opacity)) {
    builder.putDouble(TA_KEY_OPACITY, textAttributes.opacity);
  }
  if (!textAttributes.fontFamily.empty()) {
    builder.putString(TA_KEY_FONT_FAMILY, textAttributes.fontFamily);
  }
  if (!std::isnan(textAttributes.fontSize)) {
    builder.putDouble(TA_KEY_FONT_SIZE, textAttributes.fontSize);
  }
  if (!std::isnan(textAttributes.fontSizeMultiplier)) {
    builder.putDouble(
        TA_KEY_FONT_SIZE_MULTIPLIER, textAttributes.fontSizeMultiplier);
  }
  if (textAttributes.fontWeight.has_value()) {
    builder.putString(TA_KEY_FONT_WEIGHT, toString(*textAttributes.fontWeight));
  }
  if (textAttributes.fontStyle.has_value()) {
    builder.putString(TA_KEY_FONT_STYLE, toString(*textAttributes.fontStyle));
  }
  if (textAttributes.fontVariant.has_value()) {
    auto fontVariantMap = toMapBuffer(*textAttributes.fontVariant);
    builder.putMapBuffer(TA_KEY_FONT_VARIANT, fontVariantMap);
  }
  if (textAttributes.allowFontScaling.has_value()) {
    builder.putBool(
        TA_KEY_ALLOW_FONT_SCALING, *textAttributes.allowFontScaling);
  }
  if (!std::isnan(textAttributes.letterSpacing)) {
    builder.putDouble(TA_KEY_LETTER_SPACING, textAttributes.letterSpacing);
  }
  if (!std::isnan(textAttributes.lineHeight)) {
    builder.putDouble(TA_KEY_LINE_HEIGHT, textAttributes.lineHeight);
  }
  if (textAttributes.alignment.has_value()) {
    builder.putString(TA_KEY_ALIGNMENT, toString(*textAttributes.alignment));
  }
  if (textAttributes.baseWritingDirection.has_value()) {
    builder.putString(
        TA_KEY_BEST_WRITING_DIRECTION,
        toString(*textAttributes.baseWritingDirection));
  }
  if (textAttributes.lineBreakStrategy.has_value()) {
    builder.putString(
        TA_KEY_LINE_BREAK_STRATEGY,
        toString(*textAttributes.lineBreakStrategy));
  }
  // Decoration
  if (textAttributes.textDecorationColor) {
    builder.putInt(
        TA_KEY_TEXT_DECORATION_COLOR,
        toAndroidRepr(textAttributes.textDecorationColor));
  }
  if (textAttributes.textDecorationLineType.has_value()) {
    builder.putString(
        TA_KEY_TEXT_DECORATION_LINE,
        toString(*textAttributes.textDecorationLineType));
  }
  if (textAttributes.textDecorationStyle.has_value()) {
    builder.putString(
        TA_KEY_TEXT_DECORATION_STYLE,
        toString(*textAttributes.textDecorationStyle));
  }

  // Shadow
  if (!std::isnan(textAttributes.textShadowRadius)) {
    builder.putDouble(
        TA_KEY_TEXT_SHADOW_RADIUS, textAttributes.textShadowRadius);
  }
  if (textAttributes.textShadowColor) {
    builder.putInt(
        TA_KEY_TEXT_SHADOW_COLOR,
        toAndroidRepr(textAttributes.textShadowColor));
  }
  // Special
  if (textAttributes.isHighlighted.has_value()) {
    builder.putBool(TA_KEY_IS_HIGHLIGHTED, *textAttributes.isHighlighted);
  }
  if (textAttributes.layoutDirection.has_value()) {
    builder.putString(
        TA_KEY_LAYOUT_DIRECTION, toString(*textAttributes.layoutDirection));
  }
  if (textAttributes.accessibilityRole.has_value()) {
    builder.putString(
        TA_KEY_ACCESSIBILITY_ROLE, toString(*textAttributes.accessibilityRole));
  }
  return builder.build();
}

inline MapBuffer toMapBuffer(const AttributedString &attributedString) {
  auto fragmentsBuilder = MapBufferBuilder();

  int index = 0;
  for (auto fragment : attributedString.getFragments()) {
    auto dynamicFragmentBuilder = MapBufferBuilder();
    dynamicFragmentBuilder.putString(FR_KEY_STRING, fragment.string);
    if (fragment.parentShadowView.componentHandle) {
      dynamicFragmentBuilder.putInt(
          FR_KEY_REACT_TAG, fragment.parentShadowView.tag);
    }
    if (fragment.isAttachment()) {
      dynamicFragmentBuilder.putBool(FR_KEY_IS_ATTACHMENT, true);
      dynamicFragmentBuilder.putDouble(
          FR_KEY_WIDTH,
          fragment.parentShadowView.layoutMetrics.frame.size.width);
      dynamicFragmentBuilder.putDouble(
          FR_KEY_HEIGHT,
          fragment.parentShadowView.layoutMetrics.frame.size.height);
    }
    auto textAttributesMap = toMapBuffer(fragment.textAttributes);
    dynamicFragmentBuilder.putMapBuffer(
        FR_KEY_TEXT_ATTRIBUTES, textAttributesMap);
    auto dynamicFragmentMap = dynamicFragmentBuilder.build();
    fragmentsBuilder.putMapBuffer(index++, dynamicFragmentMap);
  }

  auto builder = MapBufferBuilder();
  builder.putInt(
      AS_KEY_HASH,
      std::hash<facebook::react::AttributedString>{}(attributedString));
  builder.putString(AS_KEY_STRING, attributedString.getString());
  auto fragmentsMap = fragmentsBuilder.build();
  builder.putMapBuffer(AS_KEY_FRAGMENTS, fragmentsMap);
  return builder.build();
}

#endif

} // namespace react
} // namespace facebook


text:
<?php
/**
 * ProductVariantCreate.php
 *
 * @since 23/10/16
 * @author gseidel
 */

namespace Enhavo\Bundle\ShopBundle\Form\Type;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Enhavo\Bundle\ShopBundle\Model\ProductInterface;
use Sylius\Component\Variation\Model\VariantInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;

class ProductVariantCreateType extends AbstractType
{
    /**
     * @var string
     */
    protected $dataClass;

    /**
     * ProductVariantCreateType constructor.
     *
     * @param $dataClass
     */
    public function __construct($dataClass)
    {
        $this->dataClass = $dataClass;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) {
            $variant = $event->getData();
            $form = $event->getForm();

            $options = [];
            if($variant instanceof VariantInterface) {
                $product = $variant->getObject();
                if($product instanceof ProductInterface) {
                    $options = $product->getOptions();
                }
            }

            $form->add('options', 'sylius_product_option_value_collection', [
                'options' => $options
            ]);
        });

        $builder->add('code', TextType::class);
    }

    public function getName()
    {
        return 'enhavo_shop_product_variant_create';
    }
}


text:
package com.blazebit.persistence.view.testsuite.convert.view.model;

import com.blazebit.persistence.testsuite.entity.Document;
import com.blazebit.persistence.testsuite.entity.Person;
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.IdMapping;
import com.blazebit.persistence.view.MappingParameter;
import com.blazebit.persistence.view.PostConvert;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author Christian Beikov
 * @since 1.2.0
 */
@EntityView(Document.class)
public interface DocumentCloneView extends Serializable {

    @IdMapping
    public Long getId();

    public String getName();

    public long getAge();

    public PersonView getOwner();

    public List<PersonView> getPeople();

    public Set<PersonView> getPartners();

    public Map<Integer, Person> getContacts();

    @MappingParameter("source")
    public Object getSource();

    public void setSource(Object source);

    @PostConvert
    default void postConvert(Object source) {
        setSource(source);
    }
}


text:
  Lélex est
       un village
       situé dans le département de l'Ain en Rhône-Alpes. Elle comptait 225 habitants en 2008.

La commune compte quelques  équipements, elle dispose, entre autres, de un terrain de tennis et un domaine skiable.

Le nombre de logements, à Lélex, était réparti en 2011 en 605 appartements et 96 maisons soit
une nette supériorité des appartements.

Si vous pensez venir habiter à Lélex, vous pourrez aisément trouver une maison à acheter.

À proximité de Lélex sont situées les villes de
Les Moussières localisée à 4 km, 187 habitants,
Coyrière à 8 km, 61 habitants,
Lajoux à 8 km, 253 habitants,
Mijoux située à 7 km, 376 habitants,
Septmoncel située à 7 km, 648 habitants,
Villeneuve à 6 km, 1 259 habitants,
 entre autres. De plus, Lélex est située à seulement 25 km de Annemasse.


text:
function getAnchor(data, transform) {
    var obj;

    if (data.property('ADBE Anchor Point') instanceof Property) {
        obj = data.property('ADBE Anchor Point');
    } else if (data.property('ADBE Vector Anchor') instanceof Property) {
        obj = data.property('ADBE Vector Anchor');
    } else {
        return null;
    }

    if (obj.isTimeVarying || obj.value[0] !== 0 || obj.value[1] !== 0) {

        var anchor = getProperty(obj);
        anchor = removeZValue(anchor);
        anchor = roundValue(anchor);
        anchor = normalizeKeyframes(anchor);

        transform.anchor = anchor;
    }
}


text:
/**
 * Created by Alina on 10/24/2016.
 */
import React, { Component, PropTypes } from 'react';
import { injectIntl, intlShape, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { Button, Input, Label, Icon, Form, Segment, Divider } from 'semantic-ui-react'

// Import Style
import styles from './AuthorizationPage.css';

import { logInRequest } from '../../UserActions'

export class AuthorizationPage extends Component {
    constructor(props) {
        super(props);
        this.state = { loginClicked: false}
    }

    onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    };

    logIn = ()=> {
      this.setState({loginClicked: true});
      if(this.state.email && this.state.password) {
        let user = {email: this.state.email, password: this.state.password};
       let res = this.props.dispatch(logInRequest(user));
        if(res == "err"){
          alert("Invalid login or password!");
        }
      }
    };

  registerLink = () => this.context.router.push('/registration');

    render() {
      return (

<FormattedMessage id="loginForm"/>

          <Segment compact>
            <Form className={styles['form-container']}>
              <Form.Field error={this.state.loginClicked && !this.state.email}>
                <FormattedMessage id="userEmail"/>
                <Input
                  icon='user'
                  iconPosition='left'
                  type='text'
                  placeholder={this.props.intl.messages.userEmail}
                  name='email'
                  value={this.state.email}
                  onChange={this.onChange}/>
              </Form.Field>
              <Form.Field error={this.state.loginClicked && !this.state.password}>
                <FormattedMessage id="userPassword"/>
                <Input
                  icon='lock'
                  iconPosition='left'
                  type='password'
                  placeholder={this.props.intl.messages.userPassword}
                  name='password'
                  value={this.state.password}
                  onChange={this.onChange}/>
              </Form.Field>
            </Form>
            <Button
              fluid
              onClick={this.logIn}
              color="blue"><FormattedMessage
              id="login"/></Button>
            <Divider horizontal className={styles["text-center"]} ><FormattedMessage
              id="or"/></Divider>
            <Button fluid onClick={this.registerLink} color="green"><FormattedMessage
              id="registration"/></Button>
          </Segment>

      );
    }
}

AuthorizationPage.propTypes = {
    intl: intlShape.isRequired,
};
AuthorizationPage.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state, props) {
    return {intl: state.intl,
        };
}

export default connect(mapStateToProps)(injectIntl(AuthorizationPage));


text:
/***************************************************************************//**
* @file
* Serial Tree
*
* @version @n 1.0
* @date @n 1/9/2014
*
* @author @n Kwabena W. Agyeman
* @copyright @n (c) 2014 Kwabena W. Agyeman
* @n All rights reserved - Please see the end of the file for the terms of use
*
* @par Update History:
* @n v1.0 - Original release - 1/9/2014
*******************************************************************************/

#ifndef SERIALTREE_H
#define SERIALTREE_H

#include <QtCore>
#include <QtWidgets>

#include "serialwindow.h"

#define TREE_KEY_COLUMN 0
#define TREE_VALUE_COLUMN 1

namespace Ui
{
    class SerialTree;
}

class SerialTree : public SerialWindow
{
    Q_OBJECT

public:

    explicit SerialTree(const QString &title,
                        QSettings *settings = NULL,
                        QWidget *parent = NULL);

    virtual ~SerialTree();

    virtual bool importExportEnabled() const;

    virtual QString keyGroup() const;
    virtual QString keyState() const;
    virtual QString keyGeometry() const;

    bool newItem(const QString &key, const QString &value);
    bool setItemValue(const QString &key, const QString &value);
    QString getItemValue(const QString &key, bool *ok);
    bool deleteItem(const QString &key);
    void deleteItems();

public slots:

    virtual void importState(const QString &fileName = QString());
    virtual void exportState(const QString &fileName = QString());

    void exportToCSV(const QString &fileName = QString());

private slots:

    void findKey();

    void generalHelp();
    void treeHelp();

private:

    Q_DISABLE_COPY(SerialTree)

    QList<QTreeWidgetItem *> itemChildren(QTreeWidgetItem *parent);

    QList< QPair<QString, QString> > json2Item(const QJsonObject &json);
    QJsonObject item2Json(QTreeWidgetItem *parent);

    QTreeWidgetItem *itemExists(const QString &FName,
                                const QString &key);

    bool itemDoesNotExist(const QString &FName,
                          const QString &key,
                          QPair<QTreeWidgetItem *, QStringList> *pair);

    QString m_findString;

    Ui::SerialTree *m_ui;
};

#endif // SERIALTREE_H

/***************************************************************************//**
* @file
* @par MIT License - TERMS OF USE:
* @n Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* @n
* @n The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* @n
* @n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/


text:
// [WriteFile Name=FindServiceAreasForMultipleFacilities, Category=Routing]
// [Legal]
// Copyright 2020 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

#include "FindServiceAreasForMultipleFacilities.h"

#include "FeatureLayer.h"
#include "GraphicsOverlay.h"
#include "Map.h"
#include "MapQuickView.h"
#include "PictureMarkerSymbol.h"
#include "QueryParameters.h"
#include "ServiceAreaParameters.h"
#include "ServiceAreaPolygon.h"
#include "ServiceAreaResult.h"
#include "ServiceAreaTask.h"
#include "ServiceFeatureTable.h"
#include "SimpleFillSymbol.h"
#include "SimpleRenderer.h"
#include "TaskWatcher.h"

#include <QUrl>

using namespace Esri::ArcGISRuntime;

namespace
{
const QUrl url("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0");
const QUrl imageUrl("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png");
const QUrl serviceAreaTaskUrl("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea");
}

FindServiceAreasForMultipleFacilities::FindServiceAreasForMultipleFacilities(QObject* parent /* = nullptr */):
  QObject(parent),
  m_map(new Map(BasemapStyle::ArcGISLightGray, this)),
  m_serviceAreasOverlay(new GraphicsOverlay(this))
{
  // create fill symbols for rendering the results
  m_fillSymbols.append(new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, QColor(255, 166, 0, 66), this)); // translucent orange
  m_fillSymbols.append(new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, QColor(255, 0, 0, 66), this)); // translucent red

  m_facilitiesTable = new ServiceFeatureTable(url, this);
  m_facilitiesFeatureLayer = new FeatureLayer(m_facilitiesTable, this);

  // create a symbol to display the facilities
  PictureMarkerSymbol* facilitiesSymbol = new PictureMarkerSymbol(imageUrl, this);
  facilitiesSymbol->setWidth(25);
  facilitiesSymbol->setHeight(25);
  m_facilitiesFeatureLayer->setRenderer(new SimpleRenderer(facilitiesSymbol, this));

  // add the facilities feature layer to the map
  m_map->operationalLayers()->append(m_facilitiesFeatureLayer);
}

FindServiceAreasForMultipleFacilities::~FindServiceAreasForMultipleFacilities() = default;

void FindServiceAreasForMultipleFacilities::init()
{
  // Register the map view for QML
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<FindServiceAreasForMultipleFacilities>("Esri.Samples", 1, 0, "FindServiceAreasForMultipleFacilitiesSample");
}

MapQuickView* FindServiceAreasForMultipleFacilities::mapView() const
{
  return m_mapView;
}

bool FindServiceAreasForMultipleFacilities::taskRunning() const
{
  return !m_taskWatcher.isDone();
}

// Set the view (created in QML)
void FindServiceAreasForMultipleFacilities::setMapView(MapQuickView* mapView)
{
  if (!mapView || mapView == m_mapView)
    return;

  m_mapView = mapView;

  connect(m_facilitiesFeatureLayer, &FeatureLayer::doneLoading, this, [this](Error loadError)
  {
    if (!loadError.isEmpty())
    {
      qDebug() << loadError.message() << loadError.additionalMessage();
      return;
    }

    // zoom to the full extent of the feature layer
    int buffer = 100;
    m_mapView->setViewpointGeometry(m_facilitiesFeatureLayer->fullExtent(), buffer);

  });

  m_mapView->setMap(m_map);

  m_mapView->graphicsOverlays()->append(m_serviceAreasOverlay);

  emit mapViewChanged();
}

void FindServiceAreasForMultipleFacilities::connectServiceAreaTaskSignals()
{
  // once service area task is done loading, create default parameters
  connect(m_serviceAreaTask, &ServiceAreaTask::doneLoading, this, [this](Error loadError)
  {
    if (!loadError.isEmpty())
    {
      qDebug() << loadError.message() << loadError.additionalMessage();
      return;
    }
    m_serviceAreaTask->createDefaultParameters();
  });

  // once default parameters created, set parameters and solve
  connect(m_serviceAreaTask, &ServiceAreaTask::createDefaultParametersCompleted, this, [this](QUuid, ServiceAreaParameters serviceAreaParameters)
  {
    serviceAreaParameters.setPolygonDetail(ServiceAreaPolygonDetail::High);
    serviceAreaParameters.setReturnPolygons(true);

    QList<double> travelTimes = {1.0, 3.0};

    // add service areas of 1 minute and 3 minutes travel time by car
    serviceAreaParameters.setDefaultImpedanceCutoffs(travelTimes);

    // create query parameters used to select all facilities from the feature table
    QueryParameters queryParameters;
    queryParameters.setWhereClause("1=1");

    // add all facilities to the service area parameters
    serviceAreaParameters.setFacilitiesWithFeatureTable(m_facilitiesTable, queryParameters);

    m_taskWatcher = m_serviceAreaTask->solveServiceArea(serviceAreaParameters);
    if (!m_taskWatcher.isValid())
      qWarning() << "Task not valid.";

    emit taskRunningChanged();
  });

  connect(m_serviceAreaTask, &ServiceAreaTask::solveServiceAreaCompleted, this, [this](QUuid, ServiceAreaResult serviceAreaResult)
  {
    emit taskRunningChanged();

    // iterate through the facilities to get the service area polygons
    for (int i = 0; i < serviceAreaResult.facilities().size(); ++i)
    {
      QList<ServiceAreaPolygon> serviceAreaPolygonList = serviceAreaResult.resultPolygons(i);
      // create a graphic for each available polygon
      for (int j = 0; j < serviceAreaPolygonList.size(); ++j)
      {
        m_serviceAreasOverlay->graphics()->append(new Graphic(serviceAreaPolygonList[j].geometry(), m_fillSymbols[j], this));
      }
    }
  });
}

void FindServiceAreasForMultipleFacilities::findServiceAreas()
{
  if (m_serviceAreaTask)
    return;

  m_serviceAreaTask = new ServiceAreaTask(serviceAreaTaskUrl, this);
  connectServiceAreaTaskSignals();
  m_serviceAreaTask->load();
}


text:
vtk_module(vtkRenderingContextOpenGL
  DEPENDS
    vtkRenderingOpenGL
  IMPLEMENTS
    vtkRenderingContext2D
  BACKEND
    OpenGL
  IMPLEMENTATION_REQUIRED_BY_BACKEND
  PRIVATE_DEPENDS
    vtkRenderingFreeType
  KIT
    vtkOpenGL
  )


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
All Removals Index
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

    Filter the Index:

All Differences

Removals

Additions

Changes

Listed as: Added,  Removed,  Changed

C
D
E
G
P
R
S
T
U
X
 TOP

<nobr>Config
()</nobr> constructor

D
C
E
G
P
R
S
T
U
X
 TOP

<nobr>DebugUtils
()</nobr> constructor

E
C
D
G
P
R
S
T
U
X
 TOP

<nobr>EventLog
()</nobr> constructor

G
C
D
E
P
R
S
T
U
X
 TOP

<nobr>getPluginList
()</nobr>

P
C
D
E
G
R
S
T
U
X
 TOP

Plugin

Plugin.PreferencesClickHandler

PluginData

PluginList

R
C
D
E
G
P
S
T
U
X
 TOP

<nobr>refreshPlugins
(boolean)</nobr>

S
C
D
E
G
P
R
T
U
X
 TOP

<nobr>StateSet
()</nobr> constructor

T
C
D
E
G
P
R
S
U
X
 TOP

<nobr>TimeUtils
()</nobr> constructor

U
C
D
E
G
P
R
S
T
X
 TOP

UrlInterceptHandler

UrlInterceptRegistry

X
C
D
E
G
P
R
S
T
U
 TOP

<nobr>Xml
()</nobr> constructor


text:
// -----------------------------------------------------------------------
//  Copyright (c) 2014 Tom Bulatewicz, Kansas State University
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
// -----------------------------------------------------------------------

package edu.kstate.datastore.data;

import com.hazelcast.nio.DataSerializable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

// This class is cross-platform serializable.
public class WebServiceEntry implements DataSerializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String type;
    private String description;
    private String url;
    private String serviceTimeMS;
    private String maxRequests;
    private String quantities;

    /**
     * Required for serialization;
     */
    public WebServiceEntry() {
    }

    public WebServiceEntry(String id, String type, String description, String url, String serviceTimeMS, String maxRequests,
                           String quantities) {
        this.id = id;
        this.type = type;
        this.description = description;
        this.url = url;
        this.serviceTimeMS = serviceTimeMS;
        this.maxRequests = maxRequests;
        this.quantities = quantities;
    }

    public String toString() {
        return id + ":" + type + ":" + url + ":" + quantities;
    }

    public String getId() {
        return this.id;
    }
    public String getType() {
        return this.type;
    }

    public void setId(String value) {
        this.id = value;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String value) {
        this.description = value;
    }

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String value) {
        this.url = value;
    }

    public long getServiceTimeMS() {
        return Long.parseLong(this.serviceTimeMS);
    }

    public void setServiceTimeMS(String value) {
        this.serviceTimeMS = value;
    }

    public String getMaxRequests() {
        return this.maxRequests;
    }

    public void setMaxRequests(String value) {
        this.maxRequests = value;
    }

    public String getQuantities() {
        return this.quantities;
    }

    public void setQuantities(String value) {
        this.quantities = value;
    }

    @Override
    public void readData(DataInput in) throws IOException {
        this.id = in.readUTF();
        this.type = in.readUTF();
        this.description = in.readUTF();
        this.url = in.readUTF();
        this.serviceTimeMS = in.readUTF();
        this.maxRequests = in.readUTF();
        this.quantities = in.readUTF();
    }

    @Override
    public void writeData(DataOutput out) throws IOException {
        out.writeUTF(this.id);
        out.writeUTF(this.type);
        out.writeUTF(this.description);
        out.writeUTF(this.url);
        out.writeUTF(this.serviceTimeMS);
        out.writeUTF(this.maxRequests);
        out.writeUTF(this.quantities);
    }
}


text:
  - https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt
  - https://www.kernel.org/doc/Documentation/sysfs-rules.txt
  - http://www.crashcourse.ca/wiki/index.php/Kobjects
  - http://www.crashcourse.ca/wiki/index.php/Kernel_sysfs
  - http://lxr.free-electrons.com/source/lib/kobject.c
  - http://lxr.free-electrons.com/source/include/linux/kobject.h

##Useful Commands:
  - modinfo
  - lsmod
  - insmod
  - modprobe
  - rmmod