text:
<!doctype html>

    <title>Code coverage report for responses/forbidden.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../prettify.css">
    <link rel="stylesheet" href="../base.css">

Code coverage report for responses/forbidden.js

        Statements: 4.55% (1 / 22)
        Branches: 0% (0 / 16)
        Functions: 0% (0 / 2)
        Lines: 4.55% (1 / 22)
        Ignored: none

All files » responses/ » forbidden.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

1

/**
 * 403 (Forbidden) Handler
 *
 * Usage:
 * return res.forbidden();
 * return res.forbidden(err);
 * return res.forbidden(err, 'some/specific/forbidden/view');
 *
 * e.g.:
 * ```
 * return res.forbidden('Access denied.');
 * ```
 */

module.exports = function forbidden (data, options) {

  // Get access to `req`, `res`, & `sails`
  var req = this.req;
  var res = this.res;
  var sails = req._sails;

  // Set status code
  res.status(403);

  // Log error to console
  if (data !== undefined) {
    sails.log.verbose('Sending 403 ("Forbidden") response: \n',data);
  }
  else sails.log.verbose('Sending 403 ("Forbidden") response');

  // Only include errors in response if application environment
  // is not set to 'production'.  In production, we shouldn't
  // send back any identifying information about errors.
  if (sails.config.environment === 'production') {
    data = undefined;
  }

  // If the user-agent wants JSON, always respond with JSON
  if (req.wantsJSON) {
    return res.jsonx(data);
  }

  // If second argument is a string, we take that to mean it refers to a view.
  // If it was omitted, use an empty object (`{}`)
  options = (typeof options === 'string') ? { view: options } : options || {};

  // If a view was provided in options, serve it.
  // Otherwise try to guess an appropriate view, or if that doesn't
  // work, just send JSON.
  if (options.view) {
    return res.view(options.view, { data: data });
  }

  // If no second argument provided, try to serve the default view,
  // but fall back to sending JSON(P) if any errors occur.
  else return res.view('403', { data: data }, function (err, html) {

    // If a view error occured, fall back to JSON(P).
    if (err) {
      //
      // Additionally:
      // • If the view was missing, ignore the error but provide a verbose log.
      if (err.code === 'E_VIEW_FAILED') {
        sails.log.verbose('res.forbidden() :: Could not locate view for error page (sending JSON instead).  Details: ',err);
      }
      // Otherwise, if this was a more serious error, log to the console with the details.
      else {
        sails.log.warn('res.forbidden() :: When attempting to render error page view, an error occured (sending JSON instead).  Details: ', err);
      }
      return res.jsonx(data);
    }

    return res.send(html);
  });

};

Generated by istanbul at Wed Apr 29 2015 12:33:17 GMT+0800 (MYT)


text:
<?php

namespace UserManagement\Controller\Admin;

use Micro\Application\Controller\Crud;
use Micro\Model\EntityInterface;
use Micro\Form\Form;
use Micro\Helper\Files;
use Micro\Cache;
use UserManagement\Model\Groups as GroupsModel;

class Groups extends Crud
{
    protected $model = GroupsModel::class;

    protected $scope = 'admin';

    protected function prepareForm(Form $form, EntityInterface $item)
    {
        try {

            $resources = [];

            if ($item['id']) {
                $access = $item['rights'];
                if ($access) {
                    $access = json_decode($access, \true);
                    $access = $access ? $access : [];
                    foreach ($access as $resource => $junk) {
                        $resources[str_replace(["\\", "@"], "_", $resource)] = $junk;
                    }
                }
            }

            if ($this->request->isPost()) {
                $resources = json_decode($this->request->getPost('rights', ''), \true);
                $resources = $resources ? array_flip($resources) : [];
            }

            $tree = $this->buildTree(
                Files::fetchControllers(),
                $resources
            );

        } catch (\Exception $e) {

            $tree = [];
        }

        $this->view->assign('tree', $tree);
    }

    protected function modifyEntity(EntityInterface $entity)
    {
        $resources = json_decode($this->request->getPost('rights', ''), \true);
        $resources = $resources ? array_flip($resources) : [];

        $rights = [];

        foreach ($resources as $resource => $junk) {
            $resource = str_replace('_', "\\", $resource);
            $resource = explode("\\", $resource);
            $action = $resource[count($resource) - 1];
            unset($resource[count($resource) - 1]);
            $rights[implode("\\", $resource) . "@" . $action] = \true;
        }

        $entity['rights'] = json_encode($rights);

        if (($cache = app('cache')) instanceof Cache\Core) {
            $cache->remove('Acl');
        }
    }

    public function buildTree(array $items, array $accessRights)
    {
        /**
         {
         id          : "string" // will be autogenerated if omitted
         text        : "string" // node text
         icon        : "string" // string for custom
         state       : {
         opened    : boolean  // is the node open
         disabled  : boolean  // is the node disabled
         selected  : boolean  // is the node selected
         },
         children    : []  // array of strings or objects
         li_attr     : {}  // attributes for the generated LI node
         a_attr      : {}  // attributes for the generated A node
         }
         */

        $tree = array();

        foreach ($items as $item) {

            $sibling = array(
                'id' => $item['id'],
                'text' => $item['name']
            );

            if (isset($accessRights[$item['id']])) {
                $sibling['state']['selected'] = \true;
            }

            if (!empty($item['resources'])) {
                $sibling['children'] = $this->buildTree($item['resources'], $accessRights);
            } else {
                $sibling['icon'] = 'jstree-file';
            }

            $tree[] = $sibling;
        }

        return $tree;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Text;

namespace Uno
{
	public static class StreamExtensions
	{
		public static void WriteLongString(BinaryWriter w, string s)
		{
			w.Write ((ushort)s.Length);
			var chars = Encoding.UTF8.GetBytes (s);
			w.Write (chars);
		}

		public static string ReadLongString(BinaryReader r)
		{
			var len = (int)r.ReadUInt16 ();
			var chars = r.ReadBytes (len);
			return Encoding.UTF8.GetString (chars);
		}
	}
}


text:
@interface PodsDummy_VeeContactPicker : NSObject
@end
@implementation PodsDummy_VeeContactPicker
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- 忘记密码的头部分 -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="54dp"
    android:layout_gravity="center_vertical"
    android:background="@drawable/dk_bg_top" >

    <ImageView
        android:id="@+id/dk_logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="25dp"
        android:src="@drawable/dk_logo" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/dk_titlebar_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="center"
            android:textColor="@color/dk_color_333333"
            android:textSize="17sp" />
    </LinearLayout>

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_vertical">

        <ImageView android:id="@+id/dk_close"
	        android:layout_width="15dp"
	        android:layout_height="15dp"
	        android:layout_gravity="right|center_vertical"
	        android:layout_marginRight="25dp"
	        />

        <View android:id="@+id/dk_close_container"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="right|center_vertical"
            android:background="@color/dk_transparent"/>

    </FrameLayout>

</FrameLayout>


text:
require 'active_support/hash_with_indifferent_access'
require 'rack'

module Muster
  # Rack middleware plugin for Muster query string parsing
  #
  # @example
  #
  #   app = Rack::Builder.new do
  #     use Muster::Rack, Muster::Strategies::Hash, :fields => [:name, :choices]
  #   end
  #
  #   # GET /?name=bob&choices=1&choices=2
  #   match '/' do
  #     env['muster.query']  #=> {'name' => 'bob', 'choices' => ['1', '2']}
  #   end
  class Rack
    # @attribute [r] app
    # @return [Object] Rack application middleware is running under
    attr_reader :app

    # @attribute [r] strategy
    # @return [Muster::Strategies::Rack] Muster Strategy to run
    attr_reader :strategy

    # @attribute [r] options
    # @return [Hash] options to pass to strategy
    attr_reader :options

    # Key in ENV where processed query string are stored
    QUERY = 'muster.query'.freeze

    # Key in ENV where the query string that was processed is stored
    QUERY_STRING = 'muster.query_string'.freeze

    # Creates a new Rack::Muster middleware instance
    #
    # @param app [String] Rack application
    # @param strategy [Muster::Strategies::Rack] Muster query string parsing strategy to run
    # @param options [Hash] options to pass to the specified strategy
    #
    # @example
    #
    #   middleware = Muster::Rack.new(app, Muster::Strategies::Hash, :fields => [:name, :choices])
    #
    #   strategy = Muster::Strategies::Hash.new(:fields => [:name, :choices])
    #   middleware = Muster::Rack.new(app, strategy)
    def initialize(app, strategy, options = {})
      @app = app
      @strategy = strategy
      @options = options
    end

    # Handle Rack request
    #
    # @param env [Hash] Rack environment
    #
    # @return [Array]
    def call(env) # rubocop:disable Metrics/AbcSize
      request  = ::Rack::Request.new(env)
      parser   = strategy.is_a?(Class) ? strategy.new(options) : strategy

      env[QUERY] ||= Muster::Results.new({})
      env[QUERY].merge! parser.parse(request.query_string)
      env[QUERY_STRING] = request.query_string

      @app.call(env)
    end
  end
end


text:
#ifndef _ANDROID_SKIN_SCALER_H
#define _ANDROID_SKIN_SCALER_H

#include "android/skin/image.h"

typedef struct SkinScaler   SkinScaler;

/* create a new image scaler. by default, it uses a scale of 1.0 */
extern SkinScaler*  skin_scaler_create( void );

/* change the scale of a given scaler. returns 0 on success, or -1 in case of
 * problem (unsupported scale) */
extern int          skin_scaler_set( SkinScaler*  scaler,
                                     double       scale,
                                     double       xDisp,
                                     double       yDisp );

/* retrieve the position of the scaled source rectangle 'srect' into 'drect'
 * you can use the same pointer for both parameters. */
extern void         skin_scaler_get_scaled_rect( SkinScaler*  scaler,
                                                  SkinRect*    srect,
                                                  SkinRect*    drect );

extern void         skin_scaler_free( SkinScaler*  scaler );

extern void         skin_scaler_scale( SkinScaler*   scaler,
                                       SDL_Surface*  dst,
                                       SDL_Surface*  src,
                                       int           sx,
                                       int           sy,
                                       int           sw,
                                       int           sh );

#endif /* _ANDROID_SKIN_SCALER_H */


text:
package the.bhushan.template.pojo;

public class Task {
	private String description;
	private String status;
	private double effort;

	public String getDescription() {
		return description;
	}

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

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public double getEffort() {
		return effort;
	}

	public void setEffort(double effort) {
		this.effort = effort;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="a342com.linkedlist.ListActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/lst_msglist"
            tools:listitem="@layout/sub_list_element"
            android:divider="#424242"
            android:dividerHeight="1px"
            android:clickable="false"
            android:focusable="false"/>

    </android.support.v4.widget.SwipeRefreshLayout>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="center|end"
        android:clickable="true"
        android:cropToPadding="false"
        android:focusable="false"
        android:tint="#ffffff"
        android:scaleType="center"
        android:onClick="createList"
        android:visibility="visible"/>
</android.support.design.widget.CoordinatorLayout>


text:
<!--- Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> -->
# OAuth

[OAuth](https://oauth.net/) is a simple way to publish and interact with protected data. It's also a safer and more secure way for people to give you access. For example, it can be used to access your users' data on [Twitter](https://dev.twitter.com/oauth/overview/introduction).

There are two very different versions of OAuth: [OAuth 1.0](https://tools.ietf.org/html/rfc5849) and [OAuth 2.0](https://oauth.net/2/). Version 2 is simple enough to be implemented easily without library or helpers, so Play only provides support for OAuth 1.0.

## Usage

To use OAuth, first add `ws` to your `build.sbt` file:

@[javaws-sbt-dependencies](code/javaws.sbt)

## Required Information

OAuth requires you to register your application to the service provider. Make sure to check the callback URL that you provide, because the service provider may reject your calls if they don't match. When working locally, you can use `/etc/hosts` to fake a domain on your local machine.

The service provider will give you:

* Application ID
* Secret key
* Request Token URL
* Access Token URL
* Authorize URL

## Authentication Flow

Most of the flow will be done by the Play library.

1. Get a request token from the server (in a server-to-server call)
2. Redirect the user to the service provider, where he will grant your application rights to use his data
3. The service provider will redirect the user back, giving you a /verifier/
4. With that verifier, exchange the /request token/ for an /access token/ (server-to-server call)

Now the /access token/ can be passed to any call to access protected data.

More details on OAuth's process flow are available at [The OAuth Bible](http://oauthbible.com/).

## Example

`conf/routes`:

@[ws-oauth-routes](code/javaguide.ws.routes)

controller:

@[ws-oauth-controller](code/javaguide/ws/controllers/Twitter.java)

> **Note:** OAuth does not provide any protection against [MITM attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack).  This example shows the OAuth token and secret stored in a session cookie -- for the best security, always use HTTPS with `play.http.session.secure=true` defined.


text:
"""
File: diatonic_pitch_reflection_function.py

Purpose: Class defining a pitch function based on flipping about a tone or about a neighboring tone pair.

"""
from enum import Enum

from tonalmodel.chromatic_scale import ChromaticScale
from tonalmodel.diatonic_foundation import DiatonicFoundation
from tonalmodel.diatonic_pitch import DiatonicPitch
from tonalmodel.diatonic_pitch import DiatonicToneCache
from tonalmodel.diatonic_tone import DiatonicTone
from tonalmodel.pitch_range import PitchRange
from tonalmodel.pitch_scale import PitchScale
from transformation.functions.pitchfunctions.general_pitch_function import GeneralPitchFunction
from transformation.functions.tonalfunctions.tonality_permutation_function import TonalityPermutationFunction

class FlipType(Enum):
    """
    Enumeration of types of flips:
    CenterTone: that a given tone is stable, and surrounding pairs reflection.
    LowerNeighborOfPair: that a given town flips with the next higher, and the same for concentric pairs.
    UpperNeighborOfPair: that a given town flips with the next lower, and the same for concentric pairs.
    """
    CenterTone = 1
    LowerNeighborOfPair = 2
    UpperNeighborOfPair = 3

class DiatonicPitchReflectionFunction(GeneralPitchFunction):
    """
    Class for a pitch function based on flipping tones across a variety of boundaries as defined by FlipType, for
    a given tonality.
    """

    def __init__(self, tonality, cue_pitch, domain_pitch_range, flip_type=FlipType.CenterTone):
        """
        Constructor
        :param tonality: Tonality (key) of reflection_tests.
        :param cue_pitch: A pitch used to define/start the reflection_tests on the tonality scale.
        :param domain_pitch_range: The scale range that limits the flipped scale.
        :param flip_type: The reflection_tests type of the cue_pitch
        """
        self._tonality = tonality
        self._tones = tonality.annotation[:len(tonality.annotation) - 1]
        if cue_pitch.diatonic_tone not in self._tones:
            raise Exception('Tone \'{0}\' is not in tonality \'{1}\''.format(cue_pitch.diatonic_tone, tonality))
        self._tone_index = self._tones.index(cue_pitch.diatonic_tone)
        self._flip_type = flip_type
        self._scale_origin_octave = cue_pitch.octave
        self._domain_pitch_range = domain_pitch_range
        self._cue_tone = cue_pitch.diatonic_tone

        self._tonal_function = self._build_tonal_function()

        GeneralPitchFunction.__init__(self, self._build_pitch_map())

    @property
    def flip_type(self):
        return self._flip_type

    @property
    def cue_tone(self):
        return self._cue_tone

    @property
    def tones(self):
        return self._tones

    @property
    def tonality(self):
        return self._tonality

    @property
    def tonal_function(self):
        return self._tonal_function

    @property
    def domain_pitch_range(self):
        return self._domain_pitch_range

    def _build_tonal_function(self):
        cycles = []
        n_tones = len(self.tones)
        if self.flip_type == FlipType.CenterTone:
            cycles.append([self.cue_tone])
            pairs = (n_tones - 1) // 2 if n_tones % 2 == 1 else (n_tones - 2) // 2
            for i in range(1, pairs + 1):
                low = (self._tone_index - i) % n_tones
                high = (self._tone_index + i) % n_tones
                cycles.append([self.tones[low], self.tones[high]])
            if n_tones % 2 == 0:
                extra = (self._tone_index - pairs - 1) % n_tones
                cycles.append([self.tones[extra]])
        else:
            low_idx = self._tone_index if self.flip_type == FlipType.LowerNeighborOfPair else self._tone_index - 1
            high_idx = low_idx + 1
            pairs = (n_tones - 1) // 2 if n_tones % 2 == 1 else n_tones // 2
            for i in range(0, pairs):
                low = (low_idx - i) % n_tones
                high = (high_idx + i) % n_tones
                cycles.append([self.tones[low], self.tones[high]])
            if n_tones % 2 == 0:
                extra = (self._tone_index - pairs) % n_tones
                cycles.append([self.tones[extra]])

        pure_map = TonalityPermutationFunction.create(self.tonality, cycles)

        extension = self._build_chromatic_extension(pure_map)
        extended_map = TonalityPermutationFunction.create(self.tonality, cycles, extension)

        return extended_map

    def _build_pitch_map(self):
        imap = dict()
        n_tones = len(self.tones)
        if self.flip_type == FlipType.CenterTone:
            upper = lower = self._tone_index
            upper_octave = lower_octave = self._scale_origin_octave
            upper_tone = self.cue_tone
            lower_tone = self.tonal_function[self.cue_tone]
            imap[DiatonicPitch(lower_octave, lower_tone)] = DiatonicPitch(upper_octave, upper_tone)
        else:
            if self.flip_type == FlipType.LowerNeighborOfPair:
                lower = self._tone_index
                upper = (lower + 1) % n_tones
                lower_tone = self.tones[lower]
                upper_tone = self.tonal_function[lower_tone]  # self.tones[upper]
                lower_octave = self._scale_origin_octave
                upper_octave = self._scale_origin_octave + 1 if DiatonicPitch.crosses_c(lower_tone, upper_tone, True)\
                    else self._scale_origin_octave
            else:
                upper = self._tone_index
                lower = (upper - 1) % n_tones
                lower_tone = self.tones[lower]
                upper_tone = self.tonal_function[lower_tone]  # self.tones[upper]
                upper_octave = self._scale_origin_octave
                lower_octave = self._scale_origin_octave if not DiatonicPitch.crosses_c(lower_tone, upper_tone, True) \
                    else self._scale_origin_octave - 1

            lower_pitch = DiatonicPitch(lower_octave, lower_tone)
            upper_pitch = DiatonicPitch(upper_octave, upper_tone)
            imap[lower_pitch] = upper_pitch
            imap[upper_pitch] = lower_pitch

        entered_range = False
        while True:
            lower = (lower - 1) % n_tones
            upper = (upper + 1) % n_tones
            if DiatonicPitch.crosses_c(lower_tone, self._tones[lower], False):
                lower_octave = lower_octave - 1
            if DiatonicPitch.crosses_c(upper_tone, self._tones[upper], True):
                upper_octave = upper_octave + 1
            lower_tone = self._tones[lower]
            upper_tone = self.tonal_function[lower_tone]

            lower_pitch = DiatonicPitch(lower_octave, lower_tone)
            upper_pitch = DiatonicPitch(upper_octave, upper_tone)
            if upper_pitch.chromatic_distance < ChromaticScale.chromatic_start_index() or \
                    upper_pitch.chromatic_distance > ChromaticScale.chromatic_end_index():
                break
            if lower_pitch.chromatic_distance < ChromaticScale.chromatic_start_index() or \
                    lower_pitch.chromatic_distance > ChromaticScale.chromatic_end_index():
                break
            if entered_range:
                if not self._domain_pitch_range.is_pitch_inbounds(lower_pitch) and \
                        not self._domain_pitch_range.is_pitch_inbounds(upper_pitch):
                    break
            elif self._domain_pitch_range.is_pitch_inbounds(lower_pitch) or \
                    self._domain_pitch_range.is_pitch_inbounds(upper_pitch):
                entered_range = True
            else:
                continue
            imap[lower_pitch] = upper_pitch
            imap[upper_pitch] = lower_pitch

        return self._build_non_tonal_pitch_map(imap)

    def __getitem__(self, pitch):
        if pitch is None:
            return None
        if not isinstance(pitch, DiatonicPitch) and not isinstance(pitch, str):
            raise Exception('Map only good for diatonic pitch or string, not {0}'.format(type(pitch)))
        if isinstance(pitch, str):
            pitch = DiatonicPitch.parse(pitch)
            if pitch is None:
                raise Exception('Illegal pitch string representation {0}.'.format(pitch))
        if pitch in self.map.keys():
            return super(DiatonicPitchReflectionFunction, self).__getitem__(pitch)
        print('++++++ calling map non tonality pitch')
        raise Exception('Flip cannot map \'{0}\', not in keys.'.format(pitch))

    def __str__(self):
        return str(self.tonal_function)

    def _build_non_tonal_pitch_map(self, pmap):
        octave_start = self._domain_pitch_range.start_index // 12
        octave_end = self._domain_pitch_range.end_index // 12
        for octave in range(octave_start, octave_end + 1):
            for ltr in 'ABCDEFG':
                for aug in ['bb', 'b', '', '#', "##"]:
                    p = DiatonicPitch(octave, DiatonicFoundation.get_tone(ltr + aug))
                    if self._domain_pitch_range.is_pitch_inbounds(p) and p not in pmap.keys():
                        closest_p, closest_distance = self._find_closest_pitch(p)
                        if closest_p not in pmap.keys():
                            continue
                        closest_p_prime = pmap[closest_p]
                        t = self.tonal_function[p.diatonic_tone]
                        if closest_p > p:
                            o = closest_p_prime.octave + 1 if DiatonicPitch.crosses_c(closest_p_prime.diatonic_tone,
                                                                                t,
                                                                                True) else closest_p_prime.octave
                        else:
                            o = closest_p_prime.octave - 1 if DiatonicPitch.crosses_c(closest_p_prime.diatonic_tone,
                                                                                t,
                                                                                False) else closest_p_prime.octave
                        p_prime = DiatonicPitch(o, t)
                        pmap[p] = p_prime
                        # The mapping is not-symmetrical.
                        # e.g. E-pentatonic reflection_tests on G#, f(A#)->G and f(g)->G##
        return pmap

    '''
    Approach to chromatic interpretation.

    Given a non-tonal tone/pitch, to what should it map?
    The approach is the following for pitch P:
    1) If the tone ltr l of P is in the tonality, get the actual tone L of l. Devise an augmentation 'aug'
       that modifies L to P's tone. Map L to L' with the tonal function.
       Change aug to its complement aug'.
       Liquidate aug' with L's augmentation. Use that tone.
       e.g. P = F#, l=F, L=F, aug=# F-->D (L'==D). aug'=b : F#-->Db!
    2) If the tone ltr l of P has no augmented counterpart in the tonality,
            find a tone P' in the tonality that is closest to P (in half-steps).
       Let s be the number of diatonic steps from P to P', e.g. Eb to D# is s=-1.
       Map P' --> P'' using the tonal map.
       Let tone T be the pure tone '-s' diatonic steps from P''.
       Form the pitch Q based on T and correct octave (requires octave cross check).
       Modify Q with an augmentation to get same half step distance to P'', as P is from P'.

       Note: concerning pitch comparision.
       DiatonicPitch comparison is primarily based on comparing chromatic_distance, and for equality, ensuring the
       DiatonicTones are exactly the same. There is no allowance for enharmonic equality.
       In our logic below, we need to alter that comparision. Comparing chromatic_distance covers < and > just fine.
       However, given say G#:4 and Ab:4 or worse B#:4 and C:5, we need for this logic that in each case the former
       precedes the latter (I hesitate to say 'less than'), giving a sort of order to enharmonic tones. This is
       important here, since the tone letter makes a big difference when computing chromatic locality.
       The ordering of enharmonic pitches is based on:
       1) Ensuring the pitches match chromatic distance, i.e. they are enharmonic.
       2) The tones are not more than 2 letters apart, i.e. their indices are within 2.
       Loosely for A < B, using indices 'CDEFGAB', B.index - A.index in [1, 2, -5, -6]
                               consider D<E (1) or B<C (-6)
               for A > B, B.index - A.index in [-1, -2, 5, 6]

       Why not use intervals to do these calclations? Intervals do not support some of the stretches, e.g. Cb to C# is
        in E major pentatonic, a doubly-augmented Perfect. If we extend interval to doubly augmented/diminished
        intervals, it would be worth considering.  Ref. test E##:5' == str(f['Cb:4'])
    '''

    def _find_closest_pitch(self, pitch):
        """
        Given a pitch, find the scale pitch closest to it in chromatic distance.
        :param pitch:
        :return:
           1) closest in half-steps pitch in tonality.
           2) chromatic distance measured from closest pitch to given pitch.
        Note: algorithm looks for tonal pitches with same letter as pitch first, otherwise nearest non-tonal pitch.
        """
        start_octave = max(pitch.octave - 1, ChromaticScale.CHROMATIC_START[0])
        end_octave = min(pitch.octave + 1, ChromaticScale.CHROMATIC_END[0])

        # Compute the first and last pitches within the start/end octave range. To build a PitchScale
        first_pitch = None
        for t in self.tonality.annotation:
            first_pitch = DiatonicPitch(start_octave, t)
            if DiatonicFoundation.get_chromatic_distance(first_pitch) >= ChromaticScale.chromatic_start_index():
                break

        last_pitch = None
        loop_finished = False
        for o in range(end_octave, end_octave - 2, -1):
            if loop_finished:
                break
            for t in reversed(self.tonality.annotation):
                last_pitch = DiatonicPitch(o, t)
                if DiatonicFoundation.get_chromatic_distance(last_pitch) <= ChromaticScale.chromatic_end_index():
                    loop_finished = True
                    break

        scale = PitchScale(self.tonality, PitchRange.create(first_pitch, last_pitch))

        # determine if pitch ltr is in tonality, get that tone
        ll = [t for t in self.tones if t.diatonic_letter == pitch.diatonic_tone.diatonic_letter]
        if len(ll) == 1:
            pp = DiatonicPitch(pitch.octave, ll[0])
            return pp, pitch.chromatic_distance - pp.chromatic_distance

        # Do something if len(ll) > 1
        elif len(ll) > 1:
            ll.sort(key=lambda x: abs(x.augmentation_offset - pitch.diatonic_tone.augmentation_offset))
            pp = DiatonicPitch(pitch.octave, ll[0])
            return pp, pitch.chromatic_distance - pp.chromatic_distance

        before_pitch = first_pitch
        after_pitch = last_pitch
        for p in scale.pitch_scale:
            if pitch.chromatic_distance <= p.chromatic_distance:
                after_pitch = p
                break
            else:
                before_pitch = p

        before_distance = pitch.chromatic_distance - before_pitch.chromatic_distance
        after_distance = pitch.chromatic_distance - after_pitch.chromatic_distance

        if pitch.diatonic_tone.diatonic_letter == before_pitch.diatonic_tone.diatonic_letter:
            closest_distance = before_distance
            closest_pitch = before_pitch
        elif pitch.diatonic_tone.diatonic_letter == after_pitch.diatonic_tone.diatonic_letter:
            closest_distance = after_distance
            closest_pitch = after_pitch
        else:
            if abs(before_distance) < abs(after_distance):
                closest_distance = before_distance
                closest_pitch = before_pitch
            else:
                closest_distance = after_distance
                closest_pitch = after_pitch

        return closest_pitch, closest_distance

    def _build_chromatic_extension(self, pure_tonal_map):
        m = dict()
        for c in 'ABCDEFG':
            for aug in ['bb', 'b', '', '#', '##']:
                tone = DiatonicToneCache.get_tone(c + aug)
                if tone not in pure_tonal_map.tonality_permutation.tone_domain:
                    m[tone] = self._map_non_tonality_tone(tone, pure_tonal_map)
        return m

    def _map_non_tonality_tone(self, ttone, pure_tonal_map):
        # Get the closest tone in terms of chromatic distance.
        closest_tone, closest_distance = self._find_closest_tone(ttone)

        dd = closest_tone.diatonic_index - ttone.diatonic_index
        # Look for octave crossing.  if dd in {-5, -6] closest pitch is one octave up.
        if dd in [-5, -6]:  # [1, 2] are alright.  pitch < closest_pitch
            dd = (7 + dd) % 7
        elif dd in [5, 6]:  # [-1, -2] are alright.  pitch > closest_pitch
            dd = dd - 7

        closest_tone_target = pure_tonal_map[closest_tone]
        index = (closest_tone_target.diatonic_index + dd) % 7
        tone = DiatonicToneCache.get_tone('CDEFGAB'[index])

        # Octave 4 is chosen arbitrarily, and using dd we determine if ttone and closest need different
        # octave assignments.  We do this in order to get accurate chromatic distances below.
        if dd < 0:
            octave = 3 if DiatonicPitch.crosses_c(tone, closest_tone_target, True) else 4
        elif dd > 0:
            octave = 5 if DiatonicPitch.crosses_c(tone, closest_tone_target, False) else 4
        else:
            octave = 4

        target_pitch = DiatonicPitch(octave, tone)
        actual_distance = target_pitch.chromatic_distance - DiatonicPitch(4, closest_tone_target).chromatic_distance
        # recall: closest_distance is chrom. dist to get from closest pitch to pitch: we are on 'other side', so
        #         we use the negative of it.
        correction = closest_distance - actual_distance

        if correction == 0:
            return tone
        result_tone = DiatonicTone.alter_tone_by_augmentation(tone, correction)

        return result_tone

    def _find_closest_tone(self, tone):
        # determine if pitch ltr is in tonality, get that tone
        ll = [t for t in self.tones if t.diatonic_letter == tone.diatonic_letter]
        if len(ll) == 1:
            return ll[0], ll[0].augmentation_offset - tone.augmentation_offset

        # Do something if len(ll) > 1
        elif len(ll) > 1:
            ll.sort(key=lambda x: abs(x.augmentation_offset - tone.augmentation_offset))
            return ll[0], ll[0].augmentation_offset - tone.augmentation_offset

        first_pitch = DiatonicPitch(3, self.tones[0])
        last_pitch = DiatonicPitch(5, self.tones[-1])
        scale = PitchScale(self.tonality, PitchRange.create(first_pitch, last_pitch))

        pitch = DiatonicPitch(4, tone)
        after_pitch = last_pitch
        before_pitch = None
        for p in scale.pitch_scale:
            if pitch.chromatic_distance <= p.chromatic_distance:
                after_pitch = p
                break
            else:
                before_pitch = p

        # distance measured FROM pitch TO near pitch (e.g., -1 before, +1 after)
        before_distance = before_pitch.chromatic_distance - pitch.chromatic_distance
        after_distance = after_pitch.chromatic_distance - pitch.chromatic_distance

        if abs(before_distance) < abs(after_distance):
            closest_distance = before_distance
            closest_pitch = before_pitch
        else:
            closest_distance = after_distance
            closest_pitch = after_pitch

        return closest_pitch.diatonic_tone, closest_distance


text:
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/url"
	"strconv"
	"strings"

	"github.com/agl/xmpp-client/xmpp"
	"golang.org/x/crypto/otr"
	"golang.org/x/crypto/ssh/terminal"
	"golang.org/x/net/proxy"
)

type Config struct {
	filename                      string `json:"-"`
	Account                       string
	Server                        string   `json:",omitempty"`
	Resource                      string   `json:",omitempty"`
	Proxies                       []string `json:",omitempty"`
	Password                      string   `json:",omitempty"`
	Port                          int      `json:",omitempty"`
	PrivateKey                    []byte
	KnownFingerprints             []KnownFingerprint
	RawLogFile                    string   `json:",omitempty"`
	NotifyCommand                 []string `json:",omitempty"`
	IdleSecondsBeforeNotification int      `json:",omitempty"`
	Bell                          bool
	HideStatusUpdates             bool
	UseTor                        bool
	OTRAutoTearDown               bool
	OTRAutoAppendTag              bool
	OTRAutoStartSession           bool
	ServerCertificateSHA256       string   `json:",omitempty"`
	AlwaysEncrypt                 bool     `json:",omitempty"`
	AlwaysEncryptWith             []string `json:",omitempty"`
}

type KnownFingerprint struct {
	UserId         string
	FingerprintHex string
	fingerprint    []byte `json:"-"`
}

func ParseConfig(filename string) (c *Config, err error) {
	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	c = new(Config)
	if err = json.Unmarshal(contents, &c); err != nil {
		return
	}

	c.filename = filename

	for i, known := range c.KnownFingerprints {
		c.KnownFingerprints[i].fingerprint, err = hex.DecodeString(known.FingerprintHex)
		if err != nil {
			err = errors.New("xmpp: failed to parse hex fingerprint for " + known.UserId + ": " + err.Error())
			return
		}
	}

	return
}

func (c *Config) Save() error {
	for i, known := range c.KnownFingerprints {
		c.KnownFingerprints[i].FingerprintHex = hex.EncodeToString(known.fingerprint)
	}

	contents, err := json.MarshalIndent(c, "", "\t")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(c.filename, contents, 0600)
}

func (c *Config) UserIdForFingerprint(fpr []byte) string {
	for _, known := range c.KnownFingerprints {
		if bytes.Equal(fpr, known.fingerprint) {
			return known.UserId
		}
	}

	return ""
}

func (c *Config) HasFingerprint(uid string) bool {
	for _, known := range c.KnownFingerprints {
		if uid == known.UserId {
			return true
		}
	}

	return false
}

func (c *Config) ShouldEncryptTo(uid string) bool {
	if c.AlwaysEncrypt {
		return true
	}

	for _, contact := range c.AlwaysEncryptWith {
		if contact == uid {
			return true
		}
	}
	return false
}

func isYes(s string) bool {
	lower := strings.ToLower(s)
	return lower == "yes" || lower == "y"
}

func enroll(config *Config, term *terminal.Terminal) bool {
	var err error
	warn(term, "Enrolling new config file")

	var domain string
	for {
		term.SetPrompt("Account (i.e. user@example.com, enter to quit): ")
		if config.Account, err = term.ReadLine(); err != nil || len(config.Account) == 0 {
			return false
		}

		parts := strings.SplitN(config.Account, "@", 2)
		if len(parts) != 2 {
			alert(term, "invalid username (want user@domain): "+config.Account)
			continue
		}
		domain = parts[1]
		break
	}

	term.SetPrompt("Resource name (i.e. work, enter for empty): ")
	if config.Resource, err = term.ReadLine(); err != nil {
		return false
	}

	const debugLogFile = "/tmp/xmpp-client-debug.log"
	term.SetPrompt("Enable debug logging to " + debugLogFile + " (y/n)?: ")
	if debugLog, err := term.ReadLine(); err != nil || !isYes(debugLog) {
		info(term, "Not enabling debug logging...")
	} else {
		config.RawLogFile = debugLogFile
		info(term, "Debug logging enabled.")
	}

	term.SetPrompt("Use Tor (y/n)?: ")
	if useTorQuery, err := term.ReadLine(); err != nil || !isYes(useTorQuery) {
		info(term, "Not using Tor...")
		config.UseTor = false
	} else {
		info(term, "Using Tor...")
		config.UseTor = true
	}

	term.SetPrompt("File to import libotr private key from (enter to generate): ")

	var priv otr.PrivateKey
	for {
		importFile, err := term.ReadLine()
		if err != nil {
			return false
		}
		if len(importFile) > 0 {
			privKeyBytes, err := ioutil.ReadFile(importFile)
			if err != nil {
				alert(term, "Failed to open private key file: "+err.Error())
				continue
			}

			if !priv.Import(privKeyBytes) {
				alert(term, "Failed to parse libotr private key file (the parser is pretty simple I'm afraid)")
				continue
			}
			break
		} else {
			info(term, "Generating private key...")
			priv.Generate(rand.Reader)
			break
		}
	}
	config.PrivateKey = priv.Serialize(nil)

	config.OTRAutoAppendTag = true
	config.OTRAutoStartSession = true
	config.OTRAutoTearDown = false

	// List well known Tor hidden services.
	knownTorDomain := map[string]string{
		"jabber.ccc.de":             "okj7xc6j2szr2y75.onion",
		"riseup.net":                "4cjw6cwpeaeppfqz.onion",
		"jabber.calyxinstitute.org": "ijeeynrc6x2uy5ob.onion",
		"jabber.otr.im":             "5rgdtlawqkcplz75.onion",
		"rows.io":                   "yz6yiv2hxyagvwy6.onion",
	}

	// Autoconfigure well known Tor hidden services.
	if hiddenService, ok := knownTorDomain[domain]; ok && config.UseTor {
		const torProxyURL = "socks5://127.0.0.1:9050"
		info(term, "It appears that you are using a well known server and we will use its Tor hidden service to connect.")
		config.Server = hiddenService
		config.Port = 5222
		config.Proxies = []string{torProxyURL}
		term.SetPrompt("> ")
		return true
	}

	var proxyStr string
	proxyDefaultPrompt := ", enter for none"
	if config.UseTor {
		proxyDefaultPrompt = ", which is the default"
	}
	term.SetPrompt("Proxy (i.e socks5://127.0.0.1:9050" + proxyDefaultPrompt + "): ")

	for {
		if proxyStr, err = term.ReadLine(); err != nil {
			return false
		}
		if len(proxyStr) == 0 {
			if !config.UseTor {
				break
			} else {
				proxyStr = "socks5://127.0.0.1:9050"
			}
		}
		u, err := url.Parse(proxyStr)
		if err != nil {
			alert(term, "Failed to parse "+proxyStr+" as a URL: "+err.Error())
			continue
		}
		if _, err = proxy.FromURL(u, proxy.Direct); err != nil {
			alert(term, "Failed to parse "+proxyStr+" as a proxy: "+err.Error())
			continue
		}
		break
	}

	if len(proxyStr) > 0 {
		config.Proxies = []string{proxyStr}

		info(term, "Since you selected a proxy, we need to know the server and port to connect to as a SRV lookup would leak information every time.")
		term.SetPrompt("Server (i.e. xmpp.example.com, enter to lookup using unproxied DNS): ")
		if config.Server, err = term.ReadLine(); err != nil {
			return false
		}
		if len(config.Server) == 0 {
			var port uint16
			info(term, "Performing SRV lookup")
			if config.Server, port, err = xmpp.Resolve(domain); err != nil {
				alert(term, "SRV lookup failed: "+err.Error())
				return false
			}
			config.Port = int(port)
			info(term, "Resolved "+config.Server+":"+strconv.Itoa(config.Port))
		} else {
			for {
				term.SetPrompt("Port (enter for 5222): ")
				portStr, err := term.ReadLine()
				if err != nil {
					return false
				}
				if len(portStr) == 0 {
					portStr = "5222"
				}
				if config.Port, err = strconv.Atoi(portStr); err != nil || config.Port <= 0 || config.Port > 65535 {
					info(term, "Port numbers must be 0 < port <= 65535")
					continue
				}
				break
			}
		}
	}

	term.SetPrompt("> ")

	return true
}


text:
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  OnInit,
  Optional,
  Output,
  ViewChild,
  Input,
  OnDestroy,
} from '@angular/core';
import { fromEvent, Observable, Subscription } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { IFontFamily, IWebFontList } from 'cd-interfaces';
import { OverlayInitService } from '../overlay/overlay.init.service';
import { KEYS, keyCheck } from 'cd-utils/keycodes';
import * as fontUtils from 'cd-common/utils';
import { FontWeight, FontStyle } from 'cd-metadata/fonts';
import { clamp } from 'cd-utils/numeric';
import { SearchInputComponent } from '../search-input/search-input.component';
import { ScrollBehavior } from 'cd-common/consts';

const DATA_TAG = 'data-family';
interface IFontConfig {
  apiKey: string;
  url: string;
}

@Component({
  selector: 'cd-font-picker',
  templateUrl: './font-picker.component.html',
  styleUrls: ['./font-picker.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FontPickerComponent implements OnInit, AfterViewInit, OnDestroy {
  private _filter = '';
  private _subscriptions: Subscription = new Subscription();

  public fontFamilies: ReadonlyArray<IFontFamily> = [];
  public fontFamilyLookup: ReadonlyArray<string> = [];
  public selectedFontFamily?: IFontFamily;
  public loadingPreview = false;

  @Input() config?: IFontConfig;
  @Input() existingFonts: ReadonlyArray<IFontFamily> = [];

  @Output() addFontFamily = new EventEmitter<IFontFamily>();
  @Output() close = new EventEmitter<boolean>();

  @ViewChild('overlayRef', { read: ElementRef, static: true }) overlayRef!: ElementRef;
  @ViewChild('searchRef', { read: SearchInputComponent, static: true })
  searchRef?: SearchInputComponent;
  @ViewChild('fontListRef', { read: ElementRef, static: true }) fontListRef!: ElementRef;

  get filter(): string {
    return this._filter;
  }
  set filter(filter: string) {
    this._filter = filter;
  }

  constructor(
    private _overlayInit: OverlayInitService,
    private _cdRef: ChangeDetectorRef,
    @Optional() private httpClient: HttpClient
  ) {}

  ngOnInit() {
    const { config } = this;
    if (config) {
      const url = `${config.url}?key=${config.apiKey}&prettyPrint=false`;
      this.loadFontsOptions(url);
      this._subscriptions.add(this.loadFontsOptions(url).subscribe(this.handleFontsResults));
    }
  }

  get selectedFontVariantLength(): number {
    return this.selectedFontFamily?.variants?.length || 0;
  }

  get fontList() {
    return this.fontListRef.nativeElement;
  }

  ngOnDestroy(): void {
    this._subscriptions.unsubscribe();
  }

  ngAfterViewInit() {
    const keyDown$ = fromEvent<KeyboardEvent>(this.fontList, 'keydown', { capture: true });
    this._subscriptions.add(keyDown$.subscribe(this.handleKey));
    this._overlayInit.componentLoaded();
    this.searchRef?.inputRef.nativeElement.focus();
  }

  onFilter(value: string | undefined) {
    this.filter = value || '';
  }

  handleClick(item: IFontFamily) {
    this._cdRef.markForCheck();
    this.selectedFontFamily = item;
    this.loadPreview(item);
  }

  handleFontsResults = (data: IWebFontList) => {
    const { existingFonts } = this;
    const existingKeys = new Set(existingFonts.map((item) => item.family));
    const list = data.items.filter((item) => !existingKeys.has(item.family));
    this.fontFamilies = list;
    this.fontFamilyLookup = list.map((item) => item.family);
    const [firstFont] = this.fontFamilies;
    this.selectedFontFamily = firstFont;
    this.loadPreview(firstFont);
  };

  handleKey = (e: KeyboardEvent) => {
    const { key } = e;
    if (keyCheck(key, KEYS.ArrowDown, KEYS.ArrowUp)) {
      const family = this.selectedFontFamily && this.selectedFontFamily.family;
      if (!family) return;
      e.preventDefault();
      e.stopPropagation();

      const { fontList } = this;
      const currentlyFocused = fontList.querySelector(`li[${DATA_TAG}="${family}"]`);
      const idx = currentlyFocused && [...fontList.children].indexOf(currentlyFocused);
      const increment = key === KEYS.ArrowDown ? 1 : -1;
      const next = idx + increment;
      const nextIdx = clamp(next, 0, fontList.children.length);
      const nextElem = fontList.children[nextIdx];
      const nextFamily = nextElem.getAttribute(DATA_TAG);
      const item = this.getItemByFamily(nextFamily);
      if (item) {
        this.selectedFontFamily = item;
        nextElem.querySelector('button').focus({ preventScroll: true });
        nextElem.scrollIntoView({ behavior: ScrollBehavior.Smooth });
        this.loadPreview(item);
      }
    }
  };

  onDoubleClick(item: IFontFamily) {
    this.selectedFontFamily = item;
    this.addFontFamilyToCollection();
  }

  addFontFamilyToCollection() {
    const { selectedFontFamily } = this;
    if (selectedFontFamily) {
      // Extract and store relevant details from font
      const { kind, files, version, lastModified, ...font } = selectedFontFamily;

      // This converts 'regular' -> '400' and 'italic' to '400italic'
      font.variants = font.variants.map((value) => {
        if (value === FontStyle.Italic) return FontWeight.RegularItalic;
        if (value === FontStyle.Regular) return FontWeight.Regular;
        return value;
      });

      fontUtils.loadFont(font.family, font.variants);
      this.addFontFamily.emit(font);
    }
  }

  trackByFn(_index: number, item: IFontFamily) {
    return item.family;
  }

  getItemByFamily(family: string): IFontFamily | undefined {
    return this.fontFamilies.find((font: IFontFamily) => font.family === family);
  }

  private loadFontsOptions(url: string): Observable<IWebFontList> {
    return this.httpClient.get(url, { responseType: 'json' }) as Observable<IWebFontList>;
  }

  private loadPreview(font: IFontFamily) {
    this.loadingPreview = true;
    this.selectedFontFamily = font;

    fontUtils.loadFontPreview(font).then(() => {
      this.loadingPreview = false;
      this._cdRef.markForCheck();
    });
  }
}


text:
package com.github.i49.pulp.impl.io.readers;

import static com.github.i49.pulp.impl.xml.XmlAssertions.assertOn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.github.i49.pulp.api.publication.EpubService;
import com.github.i49.pulp.api.publication.Rendition;
import com.github.i49.pulp.impl.io.containers.PackageDocumentProcessor;

/**
 * Parser for parsing a package document that contains the information about a EPUB rendition.
 */
interface PackageDocumentParser extends PackageDocumentProcessor {

	/**
	 * Probes the version of the specification.
	 *
	 * @param document the XML document to probe.
	 * @return the version of the specification.
	 */
	static String probe(Document document) {

		Element rootElement = document.getDocumentElement();

		assertOn(rootElement)
		.hasName("package", NAMESPACE_URI)
		.hasNonEmptyAttribute("version");

		return rootElement.getAttribute("version");
	}

	/**
	 * Parses the package document.
	 *
	 * @param document the package document.
	 * @param rendition the rendition to build.
	 * @param service the service which will provide API components.
	 * @param resourceFinder the finder to find the resources required by the rendition.
	 */
	void parse(Document document, Rendition rendition, EpubService service, RenditionResourceFinder resourceFinder);
}


text:
import optparse
import sys

import web_idl

# Read the WebIDL database and write a list of all event handler attributes.
#
# Reads the WebIDL database (--webidl) and writes a C++ .h file with a macro
# containing all event handler names (to --out). All attributes declared as
# EventHandler or On(BeforeUnload|Error)EventHandler types are considered
# event handlers.
#
# The macro is called EVENT_HANDLER_LIST and follows the "X macro" model of
# macro lists [1], as its used elsewhere [2] in the Chromium code base.
#
# [1] https://en.wikipedia.org/wiki/X_Macro
# [2] https://source.chromium.org/search?q=%5E%23define%5C%20%5BA-Z_%5D*LIST%5C(%20file:v8
def main(argv):
    parser = optparse.OptionParser()
    parser.add_option("--out")
    parser.add_option("--webidl")
    options, args = parser.parse_args(argv[1:])

    for option in ("out", "webidl"):
        if not getattr(options, option):
            parser.error(f"--{option} is required.")
    if args:
        parser.error("No positional arguments supported.")

    event_handlers = set()

    web_idl_database = web_idl.Database.read_from_file(options.webidl)
    for interface in web_idl_database.interfaces:
        for attribute in interface.attributes:
            if attribute.idl_type.is_event_handler:
                event_handlers.add(attribute.identifier)

    license_and_header = """\
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
"""

    with open(options.out, "w") as out:
        print(license_and_header, file=out)
        print("// Generated from WebIDL database. Don't edit, just generate.",
              file=out)
        print("//", file=out)
        print(f"// Generator: {argv[0]}", file=out)
        print("", file=out)
        print("#define EVENT_HANDLER_LIST(EH) \\", file=out)
        for event in sorted(event_handlers):
            print(f"  EH({event}) \\", file=out)
        print("\n", file=out)

    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Copyright 2017 Red Hat, Inc. and/or its affiliates.
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>kie-wb-common-forms-editor</artifactId>
    <groupId>org.kie.workbench.forms</groupId>
    <version>7.54.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>kie-wb-common-forms-editor-client</artifactId>

  <name>Kie Workbench - Common - Forms - Editor - Client</name>
  <description>Kie Workbench - Common - Forms - Editor - Client</description>

  <properties>
    <java.module.name>org.kie.wb.common.forms.editor.client</java.module.name>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.gwt</groupId>
      <artifactId>gwt-user</artifactId>
    </dependency>

    <dependency>
      <groupId>org.gwtbootstrap3</groupId>
      <artifactId>gwtbootstrap3</artifactId>
    </dependency>

    <dependency>
      <groupId>org.gwtbootstrap3</groupId>
      <artifactId>gwtbootstrap3-extras</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-common</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-ioc</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-data-binding</artifactId>
    </dependency>

    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-ui</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-project-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-project-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-services-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-message-console-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.soup</groupId>
      <artifactId>kie-soup-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-client-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-commons-editor-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-workbench-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-widgets-commons</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-layout-editor-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-layout-editor-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-runtime-plugins-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-widgets-properties-editor-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-services-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.widgets</groupId>
      <artifactId>kie-wb-common-ui</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.widgets</groupId>
      <artifactId>kie-wb-metadata-widget</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-refactoring-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-refactoring-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.profile</groupId>
      <artifactId>kie-wb-common-profile-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.screens</groupId>
      <artifactId>kie-wb-common-workbench-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-adf-engine-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-fields</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-editor-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-common-rendering-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-dynamic-forms-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-dynamic-forms-client</artifactId>
    </dependency>

    <dependency>
      <groupId>com.google.elemental2</groupId>
      <artifactId>elemental2-promise</artifactId>
    </dependency>

    <!-- Test -->
    <dependency>
      <groupId>com.google.gwt.gwtmockito</groupId>
      <artifactId>gwtmockito</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>ant</groupId>
          <artifactId>ant</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-testing-utils</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.forms</groupId>
      <artifactId>kie-wb-common-forms-fields</artifactId>
      <scope>test</scope>
      <type>test-jar</type>
    </dependency>

    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-module-junit4</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.powermock</groupId>
      <artifactId>powermock-api-mockito2</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
namespace IntergalacticTravel.Tests.TeleportStationTests
{

    using System.Collections.Generic;
    using IntergalacticTravel.Contracts;

    public class TeleportStationKid : TeleportStation
    {
        public TeleportStationKid(IBusinessOwner owner, IEnumerable<IPath> galacticMap, ILocation location)
            : base(owner, galacticMap, location)
        {
        }

        public IBusinessOwner Owner
        {
            get
            {
                return base.owner;
            }
        }

        public IEnumerable<IPath> GalacticMap
        {
            get
            {
                return base.galacticMap;
            }
        }

        public ILocation Location
        {
            get
            {
                return base.location;
            }
        }
    }
}


text:
#include "config.h"
#include "cuddObj.hh"
#include <cstdlib>
#include <iostream>
#include <sstream>
#if HAVE_WORKING_THREAD == 1
#include <thread>

/**
 * @brief Taks performed by each thread.
 */
class Task {
public:
    /** Constructor. */
    Task(int n, std::ostringstream & os) : n(n), os(os) {}
    /** Builds the hidden weight bit function and reorders the variables. */
    void operator()(void) {
        Cudd mgr;
        mgr.AutodynEnable();
        int nvars = n + 32;
        std::vector<BDD> vars;
        for (int i = 0; i != nvars; ++i) {
            vars.push_back(mgr.bddVar());
        }
        os << "Report from thread " << n << " with " << nvars << " variables: ";
        // The hidden weight bit function is built from a tally circuit and
        // a multiplexer.  First the tally circuit...
        std::vector<BDD> oldt;
        oldt.push_back(mgr.bddOne());
        std::vector<BDD> t;
        for (int i = 1; i != nvars + 1; ++i) {
            t.clear();
            t.push_back(oldt.at(0) & !vars.at(i-1));
            for (int j = 1; j != i; ++j) {
                t.push_back(vars.at(i-1).Ite(oldt.at(j-1), oldt.at(j)));
            }
            t.push_back(oldt.at(i-1) & vars.at(i-1));
            oldt = t;
        }
#if 0
        // Diagnostic print.
        for (int i = 0;  i != nvars + 1; ++i) {
            os << "t(" << i << ") = " << t.at(i).FactoredFormString()
               << std::endl;
        }
#endif
        // ...then the multiplexer.
        BDD hwb = mgr.bddZero();
        for (int i = 0; i != nvars; ++i) {
            hwb |= t.at(i+1) & vars.at(i);
        }
        mgr.ReduceHeap(CUDD_REORDER_SIFT_CONVERGE);

        int nodes = hwb.nodeCount();
        os << nodes << " nodes and ";
        int digits;
        DdApaNumber apa_minterms = hwb.ApaCountMinterm(nvars, &digits);
        os << mgr.ApaStringDecimal(digits, apa_minterms) << " minterms\n";
        free(apa_minterms);
        os << "Variable order: " << mgr.OrderString() << "\n";
        mgr.Srandom(n+11);
        os << "A random number from our generator: " << mgr.Random() << "\n";
#if 0
        // Diagnostic prints.
        hwb.summary(nvars);
        os << hwb.FactoredFormString() << std::endl;
#endif
    }
private:
    int n;
    std::ostringstream & os;
};

/**
 * @brief Class to join threads in RAII fashion.
 */
class joinThreads {
public:
    explicit joinThreads(std::vector<std::thread>& t) : threads_(t) {}
    /** It completes once all threads have been joined. */
    ~joinThreads() {
        for (std::vector<std::thread>::iterator it = threads_.begin();
             it != threads_.end(); ++it)
            if (it->joinable())
                it->join();
    }
    joinThreads(joinThreads const &) = delete;
    joinThreads& operator=(joinThreads const &) = delete;
private:
    std::vector<std::thread>& threads_; /**< vector of threads to be joined. */
};
#endif

/**
  @brief Main program for testmulti.
*/
int main(int argc, char **argv)
{
    int nthreads = 4; // default value

    // If there's an argument, it's the number of threads.
    if (argc == 2) {
        int nread;
        int retval = sscanf(argv[1], "%d%n", &nthreads, &nread);
        if (retval != 1 || argv[1][nread]) {
            std::cerr << "The argument should be an integer." << std::endl;
            return 1;
        }
    } else if (argc != 1) {
        std::cerr << "Either no arguments or one argument." << std::endl;
        return 1;
    }

#if HAVE_WORKING_THREAD == 1
    // Each thread has its own output stream, so that main can print thread
    // reports without interleaving.  We can't use an std::vector here because
    // old versions of g++ don't support move semantics (and streams can't
    // be copied).  We can't use a variable-length array either because it's
    // a g++ extension and clang++ rejects it.  Hence we use new/delete.
    std::ostringstream *oss = new std::ostringstream[nthreads];

    // Multi-threaded code in this block.
    {
        std::vector<std::thread> t;
        joinThreads joiner(t); // threads are joined by its destructor
        for (int n = 0; n != nthreads; ++n) {
            t.push_back(std::thread(Task(n, oss[n])));
        }
    }

    // Print the reports.
    for (int n = 0; n != nthreads; ++n) {
        std::cout << oss[n].str();
    }

    delete [] oss;

    return 0;
#else
    return 77; // test skipped
#endif
}


text:
RSpec.describe 'Struct.new' do
  using Polyfill(Struct: %w[.new], version: '2.5')

  context 'existing behavior' do
    let(:struct) { Struct.new(:name, :legs) }

    it 'works' do
      obj = struct.new('elefant', 4)
      expect(obj.name).to eql 'elefant'
      expect(obj.legs).to eql 4
    end
  end

  context '2.5' do
    let(:struct_with_kwa) { Struct.new(:name, :legs, keyword_init: true) }
    let(:struct_without_kwa) { Struct.new(:name, :legs, keyword_init: false) }

    context 'keyword_init: true option' do
      it 'creates a class that accepts keyword arguments to initialize' do
        obj = struct_with_kwa.new(name: 'elefant', legs: 4)
        expect(obj.name).to eql 'elefant'
        expect(obj.legs).to eql 4

        struct = Struct.new('Named', :name, :legs, keyword_init: true)
        obj = struct.new(name: 'elefant', legs: 4)
        expect(obj.name).to eql 'elefant'
        expect(obj.legs).to eql 4
      end

      context 'new class instantiation' do
        it 'accepts arguments as hash as well' do
          # rubocop:disable Style/BracesAroundHashParameters
          obj = struct_with_kwa.new({ legs: 4, name: 'elefant' })
          # rubocop:enable Style/BracesAroundHashParameters
          expect(obj.name).to eql 'elefant'
          expect(obj.legs).to eql 4
        end

        it 'raises ArgumentError when passed not declared keyword argument' do
          expect do
            struct_with_kwa.new(name: 'elefant', legs: 4, foo: 'foo', bar: 'bar')
          end.to raise_error(ArgumentError, 'unknown keywords: foo, bar')

          expect do
            struct_with_kwa.new(name: 'elefant', foo: 'foo')
          end.to raise_error(ArgumentError, 'unknown keywords: foo')
        end

        it 'raises ArgumentError when passed a list of arguments' do
          expect do
            struct_with_kwa.new('elefant', 4)
          end.to raise_error(ArgumentError, /wrong number of arguments/)
        end
      end
    end

    context 'keyword_init: false option' do
      it 'behaves like it does without :keyword_init option' do
        obj = struct_without_kwa.new('elefant', 4)
        expect(obj.name).to eql 'elefant'
        expect(obj.legs).to eql 4
      end
    end
  end
end


text:
using namespace std;

#define HEIGHT(N) (N == NULL ? 0 : N->height)
#define MAX(A, B) (A > B ? A : B)

struct node{
    int value;
    int height;
    struct node *left;
    struct node *right;
};

struct node *left_rotate(struct node *n){
    struct node *tmp = n->left;
    n->left = tmp->right;
    tmp->right = n;

    n->height = MAX(HEIGHT(n->left), HEIGHT(n->right)) + 1;
    tmp->height = MAX(HEIGHT(tmp->left), HEIGHT(tmp->right)) + 1;

    return tmp;
}

struct node *right_rotate(struct node *n){
    struct node *tmp = n->right;
    n->right = tmp->left;
    tmp->left = n;

    n->height = MAX(HEIGHT(n->left), HEIGHT(n->right)) + 1;
    tmp->height = MAX(HEIGHT(tmp->left), HEIGHT(tmp->right)) + 1;

    return tmp;
}

inline struct node * left_right_rotate(struct node *n){
    n->right = left_rotate(n->right);
    return right_rotate(n);
}

inline struct node * right_left_rotate(struct node *n){
    n->left = right_rotate(n->left);
    return left_rotate(n);
}

struct node * insert_node(struct node *root, struct node *now){
    if(root == NULL) return now;
    if(root->value > now->value){
        root->right = insert_node(root->right, now);
        if(HEIGHT(root->right) - HEIGHT(root->left) == 2){
            if(root->right->value < now->value){
                right_rotate(root);
            }else{
                left_right_rotate(root);
            }
        }
    }else if(root->value < now->value){
        root->left = insert_node(root->left, now);
        if(HEIGHT(root->left) - HEIGHT(root->right) == 2){
            if(root->left->value > now->value){
                left_rotate(root);
            }else{
                right_left_rotate(root);
            }
        }
    }
    root->height = MAX(HEIGHT(root->left), HEIGHT(root->right));
    return root;
}

struct node *init_tree(struct node *root){
    int in;
    struct node *tmp;
    cout << "Input nums:(end by 0)" << endl;
    cin >> in;
    root = new node();
    root->value = in;
    root->height = 0;
    root->left = NULL;
    root->right = NULL;
    while(cin >> in, in){
        tmp = new node();
        tmp->value = in;
        tmp->height = 0;
        tmp->left = NULL;
        tmp->right = NULL;
        insert_node(root, tmp);
    }
    cout << "Input end" << endl;
    return root;
}

int tree_depth(struct node *root){
    if(root == NULL) return 0;
    int left_depth = tree_depth(root->left);
    int right_depth = tree_depth(root->right);
    return left_depth > right_depth ? left_depth + 1 : right_depth + 1;
}

bool is_balance1(struct node *root){
    if(root == NULL) return 0;
    int left_depth = tree_depth(root->left);
    int right_depth = tree_depth(root->right);
    int diff = left_depth - right_depth;
    if(diff > 1 || diff < -1) return false;

    return is_balance1(root->left) && is_balance1(root->right);
}

bool is_balance(struct node *root, int *depth){
    if(root == NULL) return true;
    int left_depth, right_depth;
    bool b = is_balance(root->left, &left_depth);
    if(!b) return false;
    b = is_balance(root->right, &right_depth);
    if(!b) return false;

    int diff = left_depth - right_depth;
    if(diff > 1 || diff < -1) return false;
    *depth = 1 + max(left_depth, right_depth);
    return true;
}

void print_tree(struct node *root){
    if(root == NULL) return;
    cout << root->value;
    print_tree(root->left);
    print_tree(root->right);
    cout << endl;
}

class Single{
    public:
        static Single * instance();
    private:
        Single();
        ~Single();
        static Single * _instance;
};

inline Single * Single::instance(){
    if(_instance == NULL){
        _instance = new Single();
    }
    return _instance;
}

int main(){
    struct node *root = NULL;
    init_tree(root);
    print_tree(root);
    int h = 0;
    cout << "is balance:" << is_balance(root, &h) << endl;
    cout << "is balance1:" << is_balance1(root) << endl;

}


text:
/*global cordova,window,console*/
/**
 * An Image Picker plugin for Cordova
 *
 * Developed by Wymsee for Sync OnSet
 */

var ImagePicker = function() {

};

/*
 *	success - success callback
 *	fail - error callback
 *	options
 *		.maximumImagesCount - max images to be selected, defaults to 15. If this is set to 1,
 *		                      upon selection of a single image, the plugin will return it.
 *		.width - width to resize image to (if one of height/width is 0, will resize to fit the
 *		         other while keeping aspect ratio, if both height and width are 0, the full size
 *		         image will be returned)
 *		.height - height to resize image to
 *		.quality - quality of resized image, defaults to 100
 */
ImagePicker.prototype.getPictures = function(success, fail, options) {
    if (!options) {
        options = {};
    }

    var params = {
        maximumImagesCount: options.maximumImagesCount ? options.maximumImagesCount : 15,
        useOriginal: options.useOriginal ? options.useOriginal : false,
        createThumbnail: options.createThumbnail ? options.createThumbnail : false,
        saveToDataDirectory: options.saveToDataDirectory ? options.saveToDataDirectory : false,
        width: options.width ? options.width : 0,
        height: options.height ? options.height : 0,
        quality: options.quality ? options.quality : 100
    };

    return cordova.exec(success, fail, "ImagePicker", "getPictures", [params]);
};

window.imagePicker = new ImagePicker();


text:
package com.amazonaws.services.kinesisfirehose.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum HECEndpointType {

    Raw("Raw"),
    Event("Event");

    private String value;

    private HECEndpointType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return HECEndpointType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static HECEndpointType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (HECEndpointType enumEntry : HECEndpointType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}