text:
LuCI - Lua Configuration Interface

Copyright 2012 Christian Gagneraud <chris@techworks.ie>

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

$Id$
]]--

m = Map("system",
	translate("Watchcat"),
	translate("Watchcat allows configuring a periodic reboot when the " ..
		  "Internet connection has been lost for a certain period of time."
		 ))

s = m:section(TypedSection, "watchcat")
s.anonymous = true
s.addremove = true

mode = s:option(ListValue, "mode",
		translate("Operating mode"))
mode.default = "allways"
mode:value("ping", "Reboot on internet connection lost")
mode:value("allways", "Periodic reboot")

forcedelay = s:option(Value, "forcedelay",
		      translate("Forced reboot delay"),
		      translate("When rebooting the system, the watchcat will trigger a soft reboot. " ..
				"Entering a non zero value here will trigger a delayed hard reboot " ..
				"if the soft reboot fails. Enter a number of seconds to enable, " ..
				"use 0 to disable"))
forcedelay.datatype = "uinteger"
forcedelay.default = "0"

period = s:option(Value, "period",
		  translate("Period"),
		  translate("In periodic mode, it defines the reboot period. " ..
			    "In internet mode, it defines the longest period of " ..
			    "time without internet access before a reboot is engaged." ..
			    "Default unit is seconds, you can use the " ..
			    "suffix 'm' for minutes, 'h' for hours or 'd' " ..
			    "for days"))

pinghost = s:option(Value, "pinghost",
		    translate("Ping host"),
		    translate("Host address to ping"))
pinghost.datatype = "host"
pinghost.default = "8.8.8.8"
pinghost:depends({mode="ping"})

pingperiod = s:option(Value, "pingperiod",
		      translate("Ping period"),
		      translate("How often to check internet connection. " ..
				"Default unit is seconds, you can you use the " ..
				"suffix 'm' for minutes, 'h' for hours or 'd' " ..
				"for days"))
pingperiod:depends({mode="ping"})

return m


text:
using EarTrumpet.Interop.MMDeviceAPI;
using System;
using System.ComponentModel;
using System.Windows.Threading;

namespace EarTrumpet.DataModel.WindowsAudio.Internal
{
    class AudioDeviceSessionChannel : BindableBase, INotifyPropertyChanged, IAudioDeviceSessionChannel
    {
        public float Level
        {
            get => _level;
            set
            {
                if (_level != value)
                {
                    _level = value;
                    Guid dummy = Guid.Empty;
                    _session.SetChannelVolume(_index, value, ref dummy);

                    RaisePropertyChanged(nameof(Level));
                }
            }
        }

        private readonly IChannelAudioVolume _session;
        private readonly uint _index;
        private readonly Dispatcher _dispatcher;
        private float _level;

        public AudioDeviceSessionChannel(IChannelAudioVolume session, uint index, Dispatcher dispatcher)
        {
            _session = session;
            _index = index;
            _dispatcher = dispatcher;
            session.GetChannelVolume(index, out _level);
        }

        internal void SetLevel(float newLevel)
        {
            _level = newLevel;
            _dispatcher.BeginInvoke(((Action)(() =>
            {
                RaisePropertyChanged(nameof(Level));
            })));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package sous

import (
	"fmt"
	"sync"
)

// DeployStates is a wrapper around map[DeployID]*DeployState
// which is safe for concurrent read and write.
type DeployStates struct {
	mu *sync.RWMutex
	m  map[DeploymentID](*DeployState)
}

// MakeDeployStates creates a new DeployStates with capacity set.
func MakeDeployStates(capacity int) DeployStates {
	return DeployStates{
		mu: &sync.RWMutex{},
		m:  make(map[DeploymentID](*DeployState), capacity),
	}
}

func (m DeployStates) write(f func()) {
	if m.m == nil || m.mu == nil {
		panic("uninitialised DeployStates (you should use NewDeployStates)")
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	f()
}

func (m DeployStates) read(f func()) {
	if m.m == nil || m.mu == nil {
		panic("uninitialised DeployStates (you should use NewDeployStates)")
	}
	m.mu.RLock()
	defer m.mu.RUnlock()
	f()
}

// NewDeployStatesFromMap creates a new DeployStates.
// You may optionally pass any number of
// map[DeployID]*DeployStates,
// which will be merged key-wise into the new DeployStates,
// with keys from the right-most map taking precedence.
func NewDeployStatesFromMap(from ...map[DeploymentID](*DeployState)) DeployStates {
	cm := DeployStates{
		mu: &sync.RWMutex{},
		m:  map[DeploymentID](*DeployState){},
	}
	for _, m := range from {
		for k, v := range m {
			cm.m[k] = v
		}
	}
	return cm
}

// NewDeployStates creates a new DeployStates.
// You may optionally pass any number of *DeployStates,
// which will be added to this map.
func NewDeployStates(from ...(*DeployState)) DeployStates {
	m := DeployStates{
		mu: &sync.RWMutex{},
		m:  map[DeploymentID](*DeployState){},
	}
	for _, v := range from {
		if !m.Add(v) {
			panic(fmt.Sprintf("conflicting key: %q", v.ID()))
		}
	}
	return m
}

// Get returns (value, true) if k is in the map, or (zero value, false)
// otherwise.
func (m DeployStates) Get(key DeploymentID) (v *DeployState, ok bool) {
	m.read(func() {
		v, ok = m.m[key]
	})
	return
}

// Set sets the value of index k to v.
func (m DeployStates) Set(key DeploymentID, value *DeployState) {
	m.write(func() {
		m.m[key] = value
	})
}

// Filter returns a new DeployStates containing only the entries
// where the predicate returns true for the given value.
// A nil predicate is equivalent to calling Clone.
func (m DeployStates) Filter(predicate func(*DeployState) bool) DeployStates {
	if predicate == nil {
		return m.Clone()
	}
	out := map[DeploymentID](*DeployState){}
	m.read(func() {
		for k, v := range m.m {
			if predicate(v) {
				out[k] = v
			}
		}
	})
	return NewDeployStatesFromMap(out)
}

// Single returns
// (the single *DeployState satisfying predicate, true),
// if there is exactly one *DeployState satisfying predicate in
// DeployStates. Otherwise, returns (zero *DeployState, false).
func (m DeployStates) Single(predicate func(*DeployState) bool) (*DeployState, bool) {
	f := m.FilteredSnapshot(predicate)
	if len(f) == 1 {
		for _, v := range f {
			return v, true
		}
	}
	var v (*DeployState)
	return v, false
}

// Any returns
// (a single *DeployState matching predicate, true),
// if there are any *DeployStates matching predicate in
// DeployStates. Otherwise returns (zero *DeployState, false).
func (m DeployStates) Any(predicate func(*DeployState) bool) (*DeployState, bool) {
	f := m.Filter(predicate)
	for _, v := range f.Snapshot() {
		return v, true
	}
	var v (*DeployState)
	return v, false
}

// Clone returns a pairwise copy of DeployStates.
func (m DeployStates) Clone() DeployStates {
	c := NewDeployStates()
	for _, v := range m.Snapshot() {
		c.Add(v.Clone())
	}
	return c
}

// Merge returns a new DeployStates with
// all entries from this DeployStates and the other.
// If any keys in other match keys in this *DeployStates,
// keys from other will appear in the returned
// *DeployStates.
func (m DeployStates) Merge(other DeployStates) DeployStates {
	return NewDeployStatesFromMap(m.Snapshot(), other.Snapshot())
}

// Add adds a (k, v) pair into a map if it is not already there. Returns true if
// the value was added, false if not.
func (m DeployStates) Add(v *DeployState) (ok bool) {
	m.write(func() {
		k := v.ID()
		if _, exists := m.m[k]; exists {
			return
		}
		m.m[k] = v
		ok = true
	})
	return
}

// MustAdd is a wrapper around Add which panics whenever Add returns false.
func (m DeployStates) MustAdd(v *DeployState) {
	if !m.Add(v) {
		panic(fmt.Sprintf("item with ID %v already in the graph", v.ID()))
	}
}

// AddAll returns (zero DeployID, true) if all  entries from the passed in
// DeployStates have different keys and all are added to this DeployStates.
// If any of the keys conflict, nothing will be added to this
// DeployStates and AddAll will return the conflicting DeployID and false.
func (m DeployStates) AddAll(from DeployStates) (conflicting DeploymentID, success bool) {
	ss := from.Snapshot()
	var exists bool
	m.write(func() {
		for k := range ss {
			if _, exists = m.m[k]; exists {
				conflicting = k
				return
			}
		}
		for k, v := range ss {
			m.m[k] = v
		}
	})
	return conflicting, !exists
}

// Remove value for a key k if present, a no-op otherwise.
func (m DeployStates) Remove(key DeploymentID) {
	m.write(func() {
		delete(m.m, key)
	})
}

// Len returns number of elements in a map.
func (m DeployStates) Len() int {
	var l int
	m.read(func() {
		l = len(m.m)
	})
	return l
}

// Keys returns a slice containing all the keys in the map.
func (m DeployStates) Keys() []DeploymentID {
	var keys []DeploymentID
	m.read(func() {
		keys = make([]DeploymentID, len(m.m))
		i := 0
		for k := range m.m {
			keys[i] = k
			i++
		}
	})
	return keys
}

// Snapshot returns a moment-in-time copy of the current underlying
// map[DeployID]*DeployState.
func (m DeployStates) Snapshot() map[DeploymentID](*DeployState) {
	var ss map[DeploymentID](*DeployState)
	m.read(func() {
		ss = make(map[DeploymentID](*DeployState), len(m.m))
		for k, v := range m.m {
			ss[k] = v
		}
	})
	return ss
}

// FilteredSnapshot returns a moment-in-time filtered copy of the current
// underlying map[DeployID]*DeployState.
// (DeployID, *DeployState) pairs are included
// if they satisfy predicate.
func (m DeployStates) FilteredSnapshot(predicate func(*DeployState) bool) map[DeploymentID](*DeployState) {
	clone := map[DeploymentID](*DeployState){}
	m.read(func() {
		for k, v := range m.m {
			if predicate(v) {
				clone[k] = v
			}
		}
	})
	return clone
}

// GetAll returns SnapShot (it allows hy to marshal DeployStates).
func (m DeployStates) GetAll() map[DeploymentID](*DeployState) {
	return m.Snapshot()
}

// SetAll sets the internal map (it allows hy to unmarshal DeployStates).
// Note: SetAll is the only method that is not safe for concurrent access.
func (m *DeployStates) SetAll(v map[DeploymentID](*DeployState)) {
	if m.mu == nil {
		m.mu = &sync.RWMutex{}
	}
	m.m = v
}


text:
package bs.bsonify;

enum ElementType {
    NONE, START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY, FIELD_NAME, STRING_VALUE, NUMBER_TRUE_FALSE_OR_NULL_VALUE, NA_OR_EMBEDDED_VALUE
};


text:
package org.apereo.cas;

import org.apereo.cas.web.DelegatedAuthenticationWebApplicationServiceFactoryTests;
import org.apereo.cas.web.flow.DelegatedClientAuthenticationActionTests;

import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.runner.RunWith;

/**
 * This is {@link DelegatedAuthenticationTestsSuite}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@SelectClasses({
    DelegatedAuthenticationWebApplicationServiceFactoryTests.class,
    DelegatedClientAuthenticationActionTests.class
})
@RunWith(JUnitPlatform.class)
public class DelegatedAuthenticationTestsSuite {
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class HangarButton : MonoBehaviour
{
    public void Click()
    {
        if (OptionMenuClick.isPaused() == false)
        {
            SceneManager.LoadSceneAsync("Hangar", LoadSceneMode.Single);
        }
    }
}


text:
//
//  SKNDocument.m
//  SkimNotes
//
//  Created by Christiaan Hofman on 7/16/08.

#import "SKNDocument.h"
#import <SkimNotes/SkimNotes.h>
#import "SKNSkimReader.h"

@implementation SKNDocument

- (id)init {
    if (self = [super init]) {
        notes = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc {
    [notes release];
    [super dealloc];
}

- (NSString *)windowNibName {
    return @"SKNDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController {
    [super windowControllerDidLoadNib:aController];
    [aController setShouldCloseDocument:YES];
}

- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)docType error:(NSError **)outError {

#if defined(FrameworkSample)

    if ([[NSWorkspace sharedWorkspace] type:docType conformsToType:@"net.sourceforge.skim-app.skimnotes"]) {
        return [[NSFileManager defaultManager] writeSkimNotes:notes toSkimFileAtURL:absoluteURL error:outError];
    } else {
        if (outError)
            *outError = [NSError errorWithDomain:@"SKNDocumentErrorDomain" code:0 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Unable to save notes", @""), NSLocalizedDescriptionKey, nil]];
        return NO;
    }

#else

    return [super writeToURL:absoluteURL ofType:typeName error:outError];

#endif

}

- (NSData *)dataOfType:(NSString *)docType error:(NSError **)outError {
    NSData *data = nil;
    if ([[NSWorkspace sharedWorkspace] type:docType conformsToType:@"net.sourceforge.skim-app.skimnotes"]) {
        data = [NSKeyedArchiver archivedDataWithRootObject:notes];
    }
    if (data == nil && outError)
        *outError = [NSError errorWithDomain:@"SKNDocumentErrorDomain" code:0 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Unable to save notes", @""), NSLocalizedDescriptionKey, nil]];
    return data;
}

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)docType error:(NSError **)outError {
    NSArray *array = nil;
    NSError *error = nil;
    NSWorkspace *ws = [NSWorkspace sharedWorkspace];
    NSFileManager *fm = [NSFileManager defaultManager];

#if defined(FrameworkSample)

    if ([ws type:docType conformsToType:@"com.adobe.pdf"]) {
        array = [fm readSkimNotesFromExtendedAttributesAtURL:absoluteURL error:&error];
    } else if ([ws type:docType conformsToType:@"net.sourceforge.skim-app.pdfd"]) {
        array = [fm readSkimNotesFromPDFBundleAtURL:absoluteURL error:&error];
    } else if ([ws type:docType conformsToType:@"net.sourceforge.skim-app.skimnotes"]) {
        array = [fm readSkimNotesFromSkimFileAtURL:absoluteURL error:&error];
    }

#elif defined(AgentSample)

    if ([ws type:docType conformsToType:@"com.adobe.pdf"] ||
        [ws type:docType conformsToType:@"net.sourceforge.skim-app.pdfd"] ||
        [ws type:docType conformsToType:@"net.sourceforge.skim-app.skimnotes"]) {
        array = [[SKNSkimReader sharedReader] SkimNotesAtURL:absoluteURL];
    }

#elif defined(ToolSample)

    if ([ws type:docType conformsToType:@"com.adobe.pdf"]) {
        NSString *path = [absoluteURL path];
        NSString *tmpPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
        NSString *binPath = [[NSBundle mainBundle] pathForResource:@"skimnotes" ofType:nil];
        NSArray *arguments = [NSArray arrayWithObjects:@"get", path, tmpPath, nil];

        NSTask *task = [[NSTask alloc] init];
        [task setCurrentDirectoryPath:NSTemporaryDirectory()];
        [task setLaunchPath:binPath];
        [task setArguments:arguments];
        [task setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];
        [task setStandardError:[NSFileHandle fileHandleWithNullDevice]];

        BOOL success = YES;

        @try {
            [task launch];
            [task waitUntilExit];
            array = [NSKeyedUnarchiver unarchiveObjectWithFile:tmpPath];
        }
        @catch(id exception) {
            if([task isRunning])
                [task terminate];
            NSLog(@"%@ %@ failed", [task description], [task launchPath]);
            success = NO;
        }

        if (success && [task terminationStatus] == 0 && array == nil)
            array = [NSArray array];

        [task release];
        task = nil;
        [fm removeFileAtPath:tmpPath handler:nil];
    } else if ([ws type:docType conformsToType:@"net.sourceforge.skim-app.pdfd"]) {
        NSString *bundlePath = [absoluteURL path];
        NSString *filename = [[[bundlePath lastPathComponent] stringByDeletingPathExtension] stringByAppendingPathComponent:@"skim"];
        NSString *skimPath = [bundlePath stringByAppendingPathComponent:filename];
        if ([fm fileExistsAtPath:skimPath] == NO && [fm fileExistsAtPath:bundlePath]) {
            NSArray *filenames = [fm subpathsAtPath:bundlePath];
            NSUInteger idx = [[filenames valueForKey:@"pathExtension"] indexOfObject:@"skim"];
            if (idx != NSNotFound) {
                filename = [filenames objectAtIndex:idx];
                skimPath = [bundlePath stringByAppendingPathComponent:filename];
            }
        }
        array = [NSKeyedUnarchiver unarchiveObjectWithFile:skimPath];
    } else if ([ws type:docType conformsToType:@"net.sourceforge.skim-app.skimnotes"]) {
        array = [NSKeyedUnarchiver unarchiveObjectWithFile:[absoluteURL path]];
    }

#endif

    if (array) {
        [self setNotes:array];
    } else if (outError) {
        *outError = error ? error : [NSError errorWithDomain:@"SKNDocumentErrorDomain" code:0 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Unable to read notes", @""), NSLocalizedDescriptionKey, nil]];
    }

    return array != nil;
}

- (NSArray *)notes {
    return notes;
}

- (void)setNotes:(NSArray *)newNotes {
    [notes setArray:newNotes];
}

@end


text:
package org.jetbrains.wip.protocol;

import org.jetbrains.jsonProtocol.RequestImpl;

import java.io.IOException;

public abstract class WipRequest extends RequestImpl {
  public WipRequest() {
    try {
      writer.name(BasicConstants.Property.METHOD).value(getMethodName());
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  protected final String getIdKeyName() {
    return "id";
  }

  @Override
  protected final String argumentsKeyName() {
    return "params";
  }
}


text:
package cn.enilu.flash.dao;

import cn.enilu.flash.BaseApplicationStartTest;
import cn.enilu.flash.bean.entity.test.Boy;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.service.test.BoyService;
import cn.enilu.flash.utils.JsonUtil;
import cn.enilu.flash.utils.Lists;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author :enilu
 * @date :Created in 2020/5/12 18:14
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SearchFilterTest extends BaseApplicationStartTest {
    @Autowired
    private BoyService boyService;

    /**
     * 准备测试数据
     */
    @Test
    public void test_00_prepareData() {
        for (int i = 0; i < 10; i++) {
            Boy boy = new Boy();
            boy.setBirthday(i % 3 == 0 ? "199" + i + "-02-10" : null);
            boy.setHasGirFriend(i % 3 == 0);
            boy.setAge(30 - i);
            boy.setName("张三" + i);
            boyService.insert(boy);
        }
    }

    @Test
    public void test_01_isNull() {
        List<Boy> list = boyService.queryAll(SearchFilter.build("birthday", SearchFilter.Operator.ISNULL));
        System.out.println(JsonUtil.toJson(list));
        Assert.assertTrue(!list.isEmpty());
    }

    @Test
    public void test_02_isNotNull() {
        List<Boy> list = boyService.queryAll(SearchFilter.build("birthday", SearchFilter.Operator.ISNOTNULL));
        System.out.println(JsonUtil.toJson(list));
        Assert.assertTrue(!list.isEmpty());
    }
    @Test
    public void test_02_Or() {
        List<SearchFilter> filters = Lists.newArrayList();

        filters.add(SearchFilter.build("birthday","", SearchFilter.Join.or));
        List<Boy> list = boyService.queryAll(SearchFilter.build("birthday","", SearchFilter.Join.or));
        System.out.println(JsonUtil.toJson(list));
        Assert.assertTrue(!list.isEmpty());
    }
}


text:
`<macro-carousel-nav-button>` is a Web Component used internally by `<macro-carousel>` to display the previous / next navigation buttons.

Other docs:

- [`<macro-carousel>` docs](./macro-carousel.md)
- [`<macro-carousel-pagination-indicator>` docs](./macro-carousel-pagination-indicator.md)

## Properties (all reflected to attributes in kebab-case)

**`disabled`**: `boolean` = `false`

When disabled, this element can't be clicked / pressed

## Styling

| Custom property | Description | Default |
| --- | --- | --- |
| `--macro-carousel-navigation-color` | The color of the icon in the previous/next buttons | `#000` |
| `--macro-carousel-navigation-color-focus` | The color of the icon in the previous/next buttons when the button is focused / active / hovered | `var(--macro-carousel-navigation-color);` |
| `--macro-carousel-navigation-color-background` | The background color for the previous/next buttons | `transparent` |
| `--macro-carousel-navigation-color-background-focus` | The background color for the previous/next buttons when they are focused / active / hovered | `#f0f0f0` |
| `--macro-carousel-navigation-button-size` | The size of the previous/next buttons | `48px` |
| `--macro-carousel-navigation-icon-size` | The size of the icon in the previous/next buttons | `24px` |
| `--macro-carousel-navigation-icon-mask` | The shape of the icon in the previous/next buttons to be used as a valid value for the `mask-image` CSS property | `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23000'%3E %3Cpath d='M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z'/%3E %3C/svg%3E")` |

## Events

**`macro-carousel-nav-button-clicked`**: `CustomEvent`


text:
package com.suscipio_solutions.consecro_mud.Abilities.Poisons;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.StdAbility;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.HealthCondition;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Food;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Item;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Weapon;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Wearable;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMStrings;
import com.suscipio_solutions.consecro_mud.core.interfaces.Drink;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;

@SuppressWarnings("rawtypes")
public class Poison extends StdAbility implements HealthCondition
{
	@Override public String ID() { return "Poison"; }
	private final static String localizedName = CMLib.lang().L("Poison");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Poisoned)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override protected int canAffectCode(){return CAN_MOBS|CAN_ITEMS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override public boolean putInCommandlist(){return false;}
	private static final String[] triggerStrings =I(new String[] {"POISONSTING"});
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int classificationCode(){return Ability.ACODE_POISON;}
	@Override public int usageType(){return USAGE_MOVEMENT|USAGE_MANA;}
	protected int POISON_TICKS(){return 0;} // 0 means no adjustment!
	protected int POISON_DELAY(){return 3;}
	protected String POISON_DONE(){return "The poison runs its course.";}
	protected String POISON_START(){return "^G<S-NAME> turn(s) green.^?";}
	protected String POISON_START_TARGETONLY(){return "";}
	protected boolean POISON_AFFECTTARGET(){return true;}
	protected String POISON_AFFECT(){return "<S-NAME> cringe(s) as the poison courses through <S-HIS-HER> blood.";}
	protected String POISON_CAST(){return "^F^<FIGHT^><S-NAME> attempt(s) to poison <T-NAMESELF>!^</FIGHT^>^?";}
	protected String POISON_FAIL(){return "<S-NAME> attempt(s) to poison <T-NAMESELF>, but fail(s).";}
	protected int POISON_DAMAGE(){return (invoker!=null)?CMLib.dice().roll(1,invoker().phyStats().level(),1):0;}
	protected boolean processing=false;

	protected int poisonTick=3;

	@Override
	public String getHealthConditionDesc()
	{
		if(name().toUpperCase().endsWith("S"))
			return "Suffering from "+name();
		else
			return "Suffering from "+name()+" poisoning.";
	}

	protected boolean catchIt(MOB mob, Physical target)
	{
		MOB poisoner=invoker;
		if(poisoner==null) poisoner=mob;
		if((poisoner==null)&&(target instanceof MOB)) poisoner=(MOB)target;
		if((target!=null)&&(target instanceof MOB)&&(target.fetchEffect(ID())==null))
		{
			final MOB targetMOB=(MOB)target;
			if(POISON_START_TARGETONLY().length()>0)
				targetMOB.tell(POISON_START_TARGETONLY());
			final String startMsg=CMStrings.replaceAll(POISON_START(),"<S-","<T-");
			final CMMsg msg=CMClass.getMsg(poisoner,targetMOB,this,CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_POISON,startMsg);
			if((POISON_START_TARGETONLY().length()>0)
			||((targetMOB.location()!=null)
				&&(targetMOB.location().okMessage(targetMOB,msg))))
			{
				targetMOB.location().send(targetMOB,msg);
				if((POISON_AFFECTTARGET()&&(msg.value()<=0)))
				{
					maliciousAffect(poisoner,target,
									(affected instanceof Item)?affected.phyStats().level():0,
									POISON_TICKS(),-1);
					return true;
				}
				return false;
			}
		}
		return false;
	}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID))
			return false;

		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;
		if(mob==null) return false;
		if((--poisonTick)<=0)
		{
			poisonTick=POISON_DELAY();
			if(POISON_AFFECT().length()>0)
				mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,POISON_AFFECT()+CMLib.protocol().msp("poisoned.wav",10));
			if(invoker==null) invoker=mob;
			if(POISON_DAMAGE()!=0)
			{
				CMLib.combat().postDamage(invoker,mob,this,POISON_DAMAGE(),CMMsg.MASK_ALWAYS|CMMsg.TYP_POISON,-1,null);
				if((!mob.isInCombat())&&(mob!=invoker)&&(mob.location()!=null)&&(mob.location().isInhabitant(invoker))&&(CMLib.flags().canBeSeenBy(invoker,mob)))
					CMLib.combat().postAttack(mob,invoker,mob.fetchWieldedItem());
			}
		}
		return true;
	}

	@Override
	public void affectCharStats(MOB affected, CharStats affectableStats)
	{
		if((affected==null)||(!ID().equals("Poison"))) return;
		affectableStats.setStat(CharStats.STAT_CONSTITUTION,affectableStats.getStat(CharStats.STAT_CONSTITUTION)-5);
		affectableStats.setStat(CharStats.STAT_STRENGTH,affectableStats.getStat(CharStats.STAT_STRENGTH)-5);
		if(affectableStats.getStat(CharStats.STAT_CONSTITUTION)<=0)
			affectableStats.setStat(CharStats.STAT_CONSTITUTION,1);
		if(affectableStats.getStat(CharStats.STAT_STRENGTH)<=0)
			affectableStats.setStat(CharStats.STAT_STRENGTH,1);
	}

	@Override
	public void unInvoke()
	{
		if(affected!=null)
		{
			if(affected instanceof MOB)
			{
				final MOB mob=(MOB)affected;

				super.unInvoke();
				if((canBeUninvoked())&&(POISON_DONE().length()>0))
					mob.tell(POISON_DONE());
			}
			else
			if(invoker!=null)
				super.unInvoke();
		}
	}

	@Override
	public void executeMsg(final Environmental myHost, final CMMsg msg)
	{
		if(affected==null) return;
		if(affected instanceof Item)
		{
			if(!processing)
			{
				final Item myItem=(Item)affected;
				if(myItem.owner()==null) return;
				processing=true;
				if(msg.amITarget(myItem))
					switch(msg.sourceMinor())
					{
					case CMMsg.TYP_DRINK:
						if(myItem instanceof Drink)
						{
							catchIt(msg.source(),msg.source());
							if(((((Drink)myItem).liquidRemaining()<0)
								||((((Drink)myItem).liquidRemaining()-((Drink)myItem).thirstQuenched())<=0))
							&&(!((Drink)myItem).disappearsAfterDrinking()))
								affected.delEffect(this);
						}
						break;
					case CMMsg.TYP_EAT:
						if(myItem instanceof Food)
							catchIt(msg.source(),msg.source());
						break;
					}
				else
				if(msg.tool()==affected)
					switch(msg.targetMinor())
					{
					case CMMsg.TYP_DAMAGE:
						if((msg.source()!=msg.target())
						&&(msg.target()!=null)
						&&(myItem instanceof Weapon)
						&&(msg.target() instanceof MOB))
						{
							tickDown--;
							catchIt(msg.source(),(MOB)msg.target());
						}
						break;
					case CMMsg.TYP_FILL:
						if((msg.target() instanceof Drink)
						&&(affected instanceof Drink))
						{
							((Drink)msg.target()).addEffect((Ability)this.copyOf());
							if((((Drink)affected).liquidRemaining()-((Drink)msg.target()).amountTakenToFillMe((Drink)affected))<=0)
								affected.delEffect(this);
						}
						break;
					}
			}
			processing=false;
		}
		super.executeMsg(myHost,msg);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Environmental target=this.getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_UNWORNONLY);
		if(target==null) return false;
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;
		boolean success=proficiencyCheck(mob,0,auto);
		if(success)
		{
			final String str=auto?"":POISON_CAST();
			final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_POISON|(auto?CMMsg.MASK_ALWAYS:0),str);
			CMLib.color().fixSourceFightColor(msg);
			Room R=mob.location();
			if((target instanceof MOB)&&(((MOB)target).location()!=null))
				R=((MOB)target).location();
			if(R.okMessage(mob,msg))
			{
				R.send(mob,msg);
				if(msg.value()<=0)
				{
					if(target instanceof MOB)
					{
						if(POISON_START_TARGETONLY().length()>0)
							((MOB)target).tell(POISON_START_TARGETONLY());
						else
							R.show((MOB)target,null,CMMsg.MSG_OK_VISUAL,POISON_START());
						if(POISON_AFFECTTARGET())
							success=maliciousAffect(mob,(MOB)target,asLevel,POISON_TICKS(),-1)!=null;
						else
							success=true;
					}
					else
					if(target instanceof Physical)
						success=maliciousAffect(mob,(Physical)target,asLevel,100,-1)!=null;
				}
				else
					success=false;
			}
			else
				success=false;
		}
		else
			return maliciousFizzle(mob,target,POISON_FAIL());

		return success;

	}

}


text:
id: 5e9a093a74c4063ca6f7c15b
title: Selezione condizionale con Panda e modifica dei DataFrame
challengeType: 11
videoId: BFlH0fN5xRQ
bilibiliIds:
  aid: 505598518
  bvid: BV1vg411c72y
  cid: 409113534
dashedName: pandas-conditional-selection-and-modifying-dataframes
---

# --description--

*Invece di usare notebooks.ai come mostrato nel video, puoi usare Google Colab.*

Altre risorse:

-   [Notebook su GitHub](https://github.com/ine-rmotr-curriculum/freecodecamp-intro-to-pandas)
-   [Come aprire Notebooks da GitHub usando Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)

# --question--

## --text--

Cosa verrà visualizzato nella console con il seguente codice?

```py
import pandas as pd

certificates_earned = pd.DataFrame({
    'Certificates': [8, 2, 5, 6],
    'Time (in months)': [16, 5, 9, 12]
})
names = ['Tom', 'Kris', 'Ahmad', 'Beau']

certificates_earned.index = names
longest_streak = pd.Series([13, 11, 9, 7], index=names)
certificates_earned['Longest streak'] = longest_streak

print(certificates_earned)
```

## --answers--

Tom      13
Kris     11
Ahmad     9
Beau      7
Name: Longest streak, dtype: int64

---

      Certificates  Time (in months)  Longest streak
Tom               8                16              13
Kris              2                 5              11
Ahmad             5                 9               9
Beau              6                12               7

---

      Certificates   Longest streak
Tom               8               13
Kris              2               11
Ahmad             5                9
Beau              6                7

## --video-solution--

2


text:
package com.brettonw.bedrock;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class Base_Test extends Base {

    public Base_Test () {
    }

    @Test
    public void testBase () {
        assertTrue (true);
        assertFalse (false);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Threading.Tasks;
using Azure.AI.Language.Conversations.Models;
using Azure.Core.TestFramework;
using NUnit.Framework;

namespace Azure.AI.Language.Conversations.Tests.Samples
{
    public partial class ConversationAnalysisClientSamples
    {
        [SyncOnly]
        [RecordedTest]
        public void AnalyzeConversationWithOptions()
        {
            ConversationAnalysisClient client = Client;

            #region Snippet:ConversationAnalysis_AnalyzeConversationWithOptions

#if SNIPPET
            AnalyzeConversationOptions options = new AnalyzeConversationOptions(
                "Menu",
                "production",
                "We'll have 2 plates of seared salmon nigiri.");
            Response<AnalyzeConversationResult> response = client.AnalyzeConversation(options);
#else
            AnalyzeConversationOptions options = new AnalyzeConversationOptions(
                TestEnvironment.ProjectName,
                TestEnvironment.DeploymentName,
                "We'll have 2 plates of seared salmon nigiri.");
            Response<AnalyzeConversationResult> response = client.AnalyzeConversation(options);
#endif

            Console.WriteLine($"Top intent: {response.Value.Prediction.TopIntent}");

            #endregion

            Assert.That(response.GetRawResponse().Status, Is.EqualTo(200));
            Assert.That(response.Value.Prediction.TopIntent, Is.EqualTo("Order"));
        }

        [AsyncOnly]
        [RecordedTest]
        public async Task AnalyzeConversationWithOptionsAsync()
        {
            ConversationAnalysisClient client = Client;

            #region Snippet:ConversationAnalysis_AnalyzeConversationWithOptionsAsync

#if SNIPPET
            AnalyzeConversationOptions options = new AnalyzeConversationOptions(
                "Menu",
                "production",
                "We'll have 2 plates of seared salmon nigiri.");
            Response<AnalyzeConversationResult> response = await client.AnalyzeConversationAsync(options);
#else
            AnalyzeConversationOptions options = new AnalyzeConversationOptions(
                TestEnvironment.ProjectName,
                TestEnvironment.DeploymentName,
                "We'll have 2 plates of seared salmon nigiri.");
            Response<AnalyzeConversationResult> response = await client.AnalyzeConversationAsync(options);
#endif

            Console.WriteLine($"Top intent: {response.Value.Prediction.TopIntent}");
            #endregion

            Assert.That(response.GetRawResponse().Status, Is.EqualTo(200));
            Assert.That(response.Value.Prediction.TopIntent, Is.EqualTo("Order"));
        }
    }
}


text:
// Copyright © 2015 ~ 2017 Sunsoft Studio, All rights reserved.
// Umizoo is a framework can help you develop DDD and CQRS style applications.
//
// Created by young.han with Visual Studio 2017 on 2017-08-09.

using System;
using System.Collections.Generic;
using System.Linq;
using Umizoo.Configurations;
using Umizoo.Infrastructure;
using Umizoo.Infrastructure.Composition;
using Umizoo.Infrastructure.Composition.Interception;
using Umizoo.Seeds;

namespace Umizoo.Messaging.Handling
{
    /// <summary>
    ///     The command consumer.
    /// </summary>
    public class CommandConsumer : MessageConsumer<ICommand>, IInitializer
    {
        private readonly Dictionary<Type, HandlerDescriptor> _commandHandlerDescriptors;
        private readonly IMessageBus<IPublishableException> _exceptionBus;
        private readonly IRepository _repository;
        private readonly IMessageBus<IResult> _resultBus;
        private readonly ITextSerializer _serializer;
        private readonly HandlerPipelineManager _pipelineManager;

        /// <summary>
        ///     Initializes a new instance of the <see cref="CommandConsumer" /> class.
        /// </summary>
        public CommandConsumer(
            IMessageBus<IPublishableException> exceptionBus,
            IMessageBus<IResult> resultBus,
            IRepository repository,
            ITextSerializer serializer,
            IMessageReceiver<Envelope<ICommand>> commandReceiver)
            : base(commandReceiver, CheckHandlerMode.OnlyOne, ProcessingFlags.Command)
        {
            _exceptionBus = exceptionBus;
            _resultBus = resultBus;
            _repository = repository;
            _serializer = serializer;

            _commandHandlerDescriptors = new Dictionary<Type, HandlerDescriptor>();
            _pipelineManager = new HandlerPipelineManager();
        }

        public void Initialize(IObjectContainer container, IEnumerable<Type> types)
        {
            BasicTypes.CommandTypes.Values.ForEach(commandType => {
                var commandHandlers =
                    container.ResolveAll(typeof(ICommandHandler<>).MakeGenericType(commandType)).ToList();
                switch (commandHandlers.Count) {
                    case 0:
                        break;
                    case 1:
                        _commandHandlerDescriptors[commandType] = new HandlerDescriptor(commandHandlers[0], handlerType => handlerType.GetMethod("Handle", new[] { typeof(ICommandContext), commandType }), HandlerStyle.Special);
                        break;
                    default:
                        throw new SystemException(string.Format(
                            "Found more than one handler for this type('{0}') with ICommandHandler<>.",
                            commandType.FullName));
                }
                if (commandHandlers.Count == 0) {
                    Initialize(container, commandType);
                }
                var handlerDescriptor = GetHandlerDescriptors(commandType).First();
                var callHandlers = HandlerAttributeHelper.GetHandlersFor(handlerDescriptor.Method, container);
                _pipelineManager.InitializePipeline(handlerDescriptor.Method, callHandlers);
            });
        }

        protected override IEnumerable<HandlerDescriptor> GetHandlerDescriptors(Type messageType)
        {
            HandlerDescriptor handlerDescriptor;
            if (_commandHandlerDescriptors.TryGetValue(messageType, out handlerDescriptor)) {
                yield return handlerDescriptor;
            }

            yield return base.GetHandlerDescriptors(messageType).First();
        }

        private object[] CreateParameters(HandlerStyle handlerStyle, Type commandType, Envelope<ICommand> envelope)
        {
            switch (handlerStyle) {
                case HandlerStyle.Special:
                    return new object[] { new CommandContext(_resultBus, _repository, envelope), envelope.Body };
                case HandlerStyle.Senior:
                    return new object[] { Convert(commandType, envelope) };
                case HandlerStyle.Simple:
                    return new object[] { envelope.Body };
                default:
                    return new object[0];
            }
        }

        protected override void OnMessageReceived(Envelope<ICommand> envelope)
        {
            var commandType = envelope.Body.GetType();
            var traceInfo = (TraceInfo)envelope.Items[StandardMetadata.TraceInfo];
            var handlerDescriptor = GetHandlerDescriptors(commandType).First();

            var methodInvocation = new MethodInvocation(handlerDescriptor.Target, handlerDescriptor.Method, CreateParameters(handlerDescriptor.HandlerStyle, commandType, envelope));
            methodInvocation.InvocationContext[StandardMetadata.TraceInfo] = traceInfo;
            methodInvocation.InvocationContext[StandardMetadata.MessageId] = envelope.MessageId;

            try {
                var methodReturn = _pipelineManager.GetPipeline(handlerDescriptor.Method).Invoke(methodInvocation,
                    delegate (IMethodInvocation input, GetNextHandlerDelegate getNext) {
                        handlerDescriptor.Invode(input.Arguments.Cast<object>().ToArray());
                        if(handlerDescriptor.HandlerStyle == HandlerStyle.Special) {
                            ((CommandContext)input.Arguments[0]).Commit();
                            return input.CreateMethodReturn(CommandResult.CommandExecuted);
                        }
                        return input.CreateMethodReturn(null);
                    });
                NotifyResult(traceInfo, methodReturn.Exception ?? methodReturn.ReturnValue);
            }
            catch (Exception ex) {
                NotifyResult(traceInfo, ex);
            }
        }

        private void NotifyResult(TraceInfo traceInfo, object result)
        {
            var commandResult = result as ICommandResult;

            // 如果自己设置了返回结果直接发送
            if (commandResult != null) {
                _resultBus.Send(commandResult, traceInfo);
                return;
            }

            var publishableException = result as IPublishableException;

            // 如果出现了可发布异常则将异常转换成返回结果发送
            if (publishableException != null) {
                _exceptionBus.Publish(publishableException);

                commandResult = new CommandResult(HandleStatus.Failed,
                    publishableException.Message, publishableException.ErrorCode) {
                    Result = _serializer.Serialize(publishableException.Data),
                    ReplyType = CommandReturnMode.CommandExecuted
                };
                _resultBus.Send(commandResult, traceInfo);
                return;
            }

            var ex = result as Exception;

            // 如果出现了系统异常则将异常转换成返回结果发送
            if (ex != null) {
                commandResult = new CommandResult(HandleStatus.Failed, ex.Message) {
                    Result = _serializer.Serialize(ex.Data),
                    ReplyType = CommandReturnMode.CommandExecuted
                };
                _resultBus.Send(commandResult, traceInfo);
            }
        }
    }
}


text:
import test from 'ava'

test.beforeEach(t => {
  t.context.req = {
    query: {},
    params: {}
  }

  t.context.res = {
    status () { return this },
    json () {}
  }

  t.context.next = function () {}

  t.context.model = {
    find () { return this },
    findById () { return this },
    limit () { return this },
    skip () { return this },
    sort () { return this },
    then () { return this },
    catch () {}
  }
})

test.todo('getProjects')

test.todo('getProject')


text:
package org.eclipse.dd.di.provider;

import java.util.Collection;
import java.util.List;

import org.eclipse.bpmn2.di.BpmnDiFactory;

import org.eclipse.dd.di.DiPackage;
import org.eclipse.dd.di.DocumentRoot;

import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;

import org.eclipse.emf.common.util.ResourceLocator;

import org.eclipse.emf.ecore.EStructuralFeature;

import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;

import org.eclipse.securebpmn2.provider.bpmn2EditPlugin;

/**
 * This is the item provider adapter for a {@link org.eclipse.dd.di.DocumentRoot} object.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public class DocumentRootItemProvider extends ItemProviderAdapter implements
		IEditingDomainItemProvider, IStructuredItemContentProvider,
		ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource {
	/**
	 * This constructs an instance from a factory and a notifier.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public DocumentRootItemProvider(AdapterFactory adapterFactory) {
		super(adapterFactory);
	}

	/**
	 * This returns the property descriptors for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
		if (itemPropertyDescriptors == null) {
			super.getPropertyDescriptors(object);

		}
		return itemPropertyDescriptors;
	}

	/**
	 * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
	 * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
	 * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Collection<? extends EStructuralFeature> getChildrenFeatures(
			Object object) {
		if (childrenFeatures == null) {
			super.getChildrenFeatures(object);
			childrenFeatures
					.add(DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__EDGE);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__LABEL);
			childrenFeatures
					.add(DiPackage.Literals.DOCUMENT_ROOT__LABELED_EDGE);
			childrenFeatures
					.add(DiPackage.Literals.DOCUMENT_ROOT__LABELED_SHAPE);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__NODE);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__PLANE);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__SHAPE);
			childrenFeatures.add(DiPackage.Literals.DOCUMENT_ROOT__STYLE);
		}
		return childrenFeatures;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected EStructuralFeature getChildFeature(Object object, Object child) {
		// Check the type of the specified child object and return the proper feature to use for
		// adding (see {@link AddCommand}) it as a child.

		return super.getChildFeature(object, child);
	}

	/**
	 * This returns DocumentRoot.gif.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object getImage(Object object) {
		return overlayImage(object,
				getResourceLocator().getImage("full/obj16/DocumentRoot"));
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected boolean shouldComposeCreationImage() {
		return true;
	}

	/**
	 * This returns the label text for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public String getText(Object object) {
		return getString("_UI_DocumentRoot_type");
	}

	/**
	 * This handles model notifications by calling {@link #updateChildren} to update any cached
	 * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public void notifyChanged(Notification notification) {
		updateChildren(notification);

		switch (notification.getFeatureID(DocumentRoot.class)) {
		case DiPackage.DOCUMENT_ROOT__DIAGRAM_ELEMENT:
		case DiPackage.DOCUMENT_ROOT__DIAGRAM:
		case DiPackage.DOCUMENT_ROOT__EDGE:
		case DiPackage.DOCUMENT_ROOT__LABEL:
		case DiPackage.DOCUMENT_ROOT__LABELED_EDGE:
		case DiPackage.DOCUMENT_ROOT__LABELED_SHAPE:
		case DiPackage.DOCUMENT_ROOT__NODE:
		case DiPackage.DOCUMENT_ROOT__PLANE:
		case DiPackage.DOCUMENT_ROOT__SHAPE:
		case DiPackage.DOCUMENT_ROOT__STYLE:
			fireNotifyChanged(new ViewerNotification(notification,
					notification.getNotifier(), true, false));
			return;
		}
		super.notifyChanged(notification);
	}

	/**
	 * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
	 * that can be created under this object.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected void collectNewChildDescriptors(
			Collection<Object> newChildDescriptors, Object object) {
		super.collectNewChildDescriptors(newChildDescriptors, object);

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT,
				BpmnDiFactory.eINSTANCE.createBPMNEdge()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT,
				BpmnDiFactory.eINSTANCE.createBPMNLabel()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT,
				BpmnDiFactory.eINSTANCE.createBPMNPlane()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT,
				BpmnDiFactory.eINSTANCE.createBPMNShape()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM,
				BpmnDiFactory.eINSTANCE.createBPMNDiagram()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__EDGE,
				BpmnDiFactory.eINSTANCE.createBPMNEdge()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__LABEL,
				BpmnDiFactory.eINSTANCE.createBPMNLabel()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__LABELED_EDGE,
				BpmnDiFactory.eINSTANCE.createBPMNEdge()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__LABELED_SHAPE,
				BpmnDiFactory.eINSTANCE.createBPMNShape()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__NODE,
				BpmnDiFactory.eINSTANCE.createBPMNLabel()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__NODE,
				BpmnDiFactory.eINSTANCE.createBPMNPlane()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__NODE,
				BpmnDiFactory.eINSTANCE.createBPMNShape()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__PLANE,
				BpmnDiFactory.eINSTANCE.createBPMNPlane()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__SHAPE,
				BpmnDiFactory.eINSTANCE.createBPMNShape()));

		newChildDescriptors.add(createChildParameter(
				DiPackage.Literals.DOCUMENT_ROOT__STYLE,
				BpmnDiFactory.eINSTANCE.createBPMNLabelStyle()));
	}

	/**
	 * This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public String getCreateChildText(Object owner, Object feature,
			Object child, Collection<?> selection) {
		Object childFeature = feature;
		Object childObject = child;

		boolean qualify = childFeature == DiPackage.Literals.DOCUMENT_ROOT__DIAGRAM_ELEMENT
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__EDGE
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__LABELED_EDGE
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__LABEL
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__NODE
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__PLANE
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__LABELED_SHAPE
				|| childFeature == DiPackage.Literals.DOCUMENT_ROOT__SHAPE;

		if (qualify) {
			return getString("_UI_CreateChild_text2", new Object[] {
					getTypeText(childObject), getFeatureText(childFeature),
					getTypeText(owner) });
		}
		return super.getCreateChildText(owner, feature, child, selection);
	}

	/**
	 * Return the resource locator for this item provider's resources.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public ResourceLocator getResourceLocator() {
		return bpmn2EditPlugin.INSTANCE;
	}

}


text:
function f = populate(f, op, data, pref)
%POPULATE   Populate a TRIGTECH class with values.
%   F = F.POPULATE(OP) returns a TRIGTECH representation populated with values
%   F.VALUES of the function OP evaluated on an equally spaced grid. The field
%   F.ISHAPPY indicates whether the representation is deemed 'happy'.
%   Essentially this means that such an interpolant is a sufficiently accurate
%   approximation to OP. If F.ISHAPPY is FALSE, then POPULATE was not able to
%   obtain a happy result.
%
%   OP should be vectorized (i.e., accept a vector input), and output a vector
%   of the same length. Furthermore, OP may be an array-valued function, in
%   which case it should accept a vector of length N and return a matrix of size
%   NxM.
%
%   F.POPULATE(OP, VSCALE, HSCALE) enforces that the happiness check is relative
%   to the initial vertical scale VSCALE and horizontal scale HSCALE. These
%   values default to 0 and 1 respectively. During refinement, VSCALE updates
%   itself to be the largest magnitude values to which (each of the columns in)
%   OP evaluated to.
%
%   F.POPULATE(OP, VSCALE, HSCALE, PREF) enforces any additional preferences
%   specified in the preference structure PREF (see TRIGTECH.TECHPREF).
%
%   F.POPULATE(VALUES, ...) (or F.POPULATE({VALUES, COEFFS}, ...)) populates F
%   non-adaptively with the VALUES (and COEFFS) passed. These values are still
%   tested for happiness in the same way as described above, but the length of
%   the representation is not altered.
%
% See also TRIGTECH, TECHPREF, HAPPINESSCHECK.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

%%%%%%%%%%%%%%%%%%%%%%%%%% Non-adaptive construction. %%%%%%%%%%%%%%%%%%%%%%%%%%
% Values (and possibly coefficients) have been given.
if ( isnumeric(op) || iscell(op) )
    if ( isnumeric(op) )
        % OP is just the values.
        f.values = op;
        f.coeffs = f.vals2coeffs(op);
    else
        % OP is a cell {values, coeffs}
        f.coeffs = op{2};
        f.values = f.coeffs2vals(f.coeffs);
    end

    % We're always happy if given discrete data:
    f.ishappy = true;

    % Threshold to determine if f is real or not.
    vscl = max(data.vscale, vscale(f));
    f.isReal = max(abs(imag(f.values))) <= 3*(eps*vscl);
    f.values(:,f.isReal) = real(f.values(:,f.isReal));

    return
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%% Adaptive construction. %%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Initialise empty values to pass to refine:
f.values = [];
% Check a random value of op in (-1,1) to see if the result is complex and
% if the value is a NaN or Inf.
pseudoRand = 0.376989633393435;
rndVal = feval(op, (2*pseudoRand - 1));

if ( any(isnan(rndVal)) || any(isinf(rndVal)) )
    error('CHEBFUN:TRIGTECH:populate:isNan','Cannot handle functions that evaluate to Inf or NaN.');
end

f.isReal = false(size(rndVal));
for k = 1:numel(rndVal)
    f.isReal(k) = isreal(rndVal(k));
end

% Loop until ISHAPPY or GIVEUP:
while ( 1 )

    % Call the appropriate refinement routine: (in PREF.REFINEMENTFUNCTION)
    [f.values, giveUp] = f.refine(op, f.values, pref);

    % We're giving up! :(
    if ( giveUp )
        break
    end

    % Update vertical scale: (Only include sampled finite values)
    valuesTemp = f.values;
    valuesTemp(~isfinite(f.values)) = 0;
    data.vscale = max(data.vscale, max(abs(valuesTemp)));

    % Compute the trigonometric coefficients:
    coeffs = f.vals2coeffs(f.values);

    % Check for happiness:
    f.coeffs = coeffs;
    [ishappy, cutoff] = happinessCheck(f, op, f.values, data, pref);

    % We're happy! :)
    if ( ishappy )
        f = prolong(f,cutoff); % chop coefficients to length cutoff
        break
    end

end

%%%%%%%%%%%%%%%%%%%%%%%%%% Assign to TRIGTECH object. %%%%%%%%%%%%%%%%%%%%%%%%%%
f.ishappy = ishappy;

% Force the values to be real if the imaginary part is zero
f.values(:,f.isReal) = real(f.values(:,f.isReal));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Ouput. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if ( ishappy )
    % We're done, and can return.
    return
end

end


text:
/**
 * Created by MIC on 2015/11/17.
 */
import * as libtess from "libtess";
import RendererOptions from "./RendererOptions";
import ShaderManager from "./ShaderManager";
import FilterManager from "./FilterManager";
import RenderTarget2D from "./targets/RenderTarget2D";
import WebGLUtils from "./WebGLUtils";
import IDisposable from "../mic/IDisposable";
import BlendMode from "../flash/display/BlendMode";
import VirtualDom from "../mic/VirtualDom";
import CommonUtil from "../mic/CommonUtil";
import FrameImage from "./FrameImage";

const gl = VirtualDom.WebGLRenderingContext;

/**
 * The WebGL $renderer, main provider of the rendering services.
 * @implements {IDisposable}
 */
export default class WebGLRenderer implements IDisposable {

    /**
     * Creates a new {@link WebGLRenderer}.
     * @param canvas {HTMLCanvasElement} If canvas is not null, the new {@link WebGLRenderer} will use it as target.
     * @param width {Number} The width for presentation of the $renderer.
     * @param height {Number} The height for presentation of the $renderer.
     * @param options {RendererOptions} Options for initializing the newly created {@link WebGLRenderer}.
     */
    constructor(options: RendererOptions, canvas: HTMLCanvasElement = null, width?: number, height?: number) {
        this.__initialize(options, canvas, width, height);
    }

    /**
     * Clear the screen.
     */
    clear(): void {
        if (this.screenRenderTarget !== null) {
            this.screenRenderTarget.clear();
        }
    }

    /**
     * Disposes the {@link WebGLRenderer} and related resources.
     */
    dispose(): void {
        if (!this._isInitialized) {
            return;
        }
        this.screenRenderTarget.dispose();
        this.filterManager.dispose();
        this.shaderManager.dispose();
        this._filterManager = null;
        this._shaderManager = null;
        this._screenRenderTarget = null;
        this._context = null;
        if (!CommonUtil.isUndefinedOrNull(this.view)) {
            this.view.parentNode.removeChild(this.view);
        }
        this._view = null;
    }

    beginDrawMaskObject(): void {
        const context = this.context;
        context.stencilFunc(gl.ALWAYS, 1, 0xff);
        context.stencilMask(0xff);
        context.enable(gl.STENCIL_TEST);
        context.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
        context.colorMask(false, false, false, false);
        this._isStencilTestEnabled = true;
    }

    beginDrawMaskedObjects(): void {
        const context = this.context;
        context.stencilFunc(gl.EQUAL, 1, 0xff);
        context.stencilMask(0);
        context.enable(gl.STENCIL_TEST);
        context.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
        context.colorMask(true, true, true, true);
        this._isStencilTestEnabled = true;
    }

    beginDrawNormalObjects(): void {
        const context = this.context;
        context.disable(gl.STENCIL_TEST);
        context.stencilMask(0);
        context.stencilOp(gl.KEEP, gl.KEEP, gl.REPLACE);
        context.colorMask(true, true, true, true);
        this._isStencilTestEnabled = false;
    }

    get isStencilTestEnabled(): boolean {
        return this._isStencilTestEnabled;
    }

    /**
     * Returns current $render target of the {@link WebGLRenderer}.
     * @returns {RenderTarget2D} Current $render target of the {@link WebGLRenderer}.
     */
    get currentRenderTarget(): RenderTarget2D {
        return this._currentRenderTarget;
    }

    /**
     * Switches current $render target to a specified {@link RenderTarget2D}.
     * @param v {RenderTarget2D} The {@link RenderTarget2D} that will be used. Null means using the default first-time
     * $render target of the {@link WebGLRenderer}. The default value is null.
     */
    set currentRenderTarget(v: RenderTarget2D) {
        if (v === this._currentRenderTarget && v) {
            return;
        }
        const t = this._currentRenderTarget = v ? v : this._screenRenderTarget;
        t.activate();
    }

    /**
     * Returns the output <canvas> for displaying the contents rendered.
     * @returns {HTMLCanvasElement} The output <canvas>.
     */
    get view(): HTMLCanvasElement {
        return this._view;
    }

    /**
     * Returns the {@link WebGLRenderingContext} attached to the {@link WebGLRenderer}.
     * @returns {WebGLRenderingContext} The {@link WebGLRenderingContext} attached to the {@link WebGLRenderer}.
     */
    get context(): WebGLRenderingContext {
        return this._context;
    }

    /**
     * Returns the {@link ShaderManager} used by the {@link WebGLRenderer}.
     * @returns {ShaderManager} The {@link ShaderManager} used by the {@link WebGLRenderer}.
     */
    get shaderManager(): ShaderManager {
        return this._shaderManager;
    }

    /**
     * Returns the {@link FilterManager} used by the {@link WebGLRenderer}.
     * @returns {FilterManager} The {@link FilterManager} used by the {@link WebGLRenderer}.
     */
    get filterManager(): FilterManager {
        return this._filterManager;
    }

    /**
     * Returns the tessellator used by the {@link WebGLRenderer}.
     * @returns {libtess.GluTesselator} The tessellator used by the {@link WebGLRenderer}.
     */
    get tessellator(): libtess.GluTesselator {
        return this._tessellator;
    }

    /**
     * Returns the final output of the {@link WebGLRenderer}. This target is always a root $render target, which directly
     * renders to the attached <canvas>. If FXAA is enabled, the copying process from {@link WebGLRenderer.currentRenderTarget}
     * to this target performs a FXAA filtering. If not, it is a simple replicating process.
     * @returns {RenderTarget2D} The output of the {@link WebGLRenderer}.
     */
    get screenRenderTarget(): RenderTarget2D {
        return this._screenRenderTarget;
    }

    /**
     * Creates a new {@link RenderTarget2D} as a buffer. {@link RenderTarget2D}s should be only instanted through this
     * factory method, and be released using {@link WebGLRenderer.releaseRenderTarget}.
     * @param [image] {FrameImage} See {@link RenderTarget2D.image}
     * for more information.
     * @returns {RenderTarget2D} The created {@link RenderTarget2D}.
     */
    createRenderTarget(image: FrameImage = null): RenderTarget2D {
        return new RenderTarget2D(this, image, false);
    }

    /**
     * Creates a new {@link RenderTarget2D} as an output to the screen. {@link RenderTarget2D}s should be only instanted
     * through this factory method, and be released using {@link WebGLRenderer.releaseRenderTarget}.
     * @param [image] {FrameImage} See {@link RenderTarget2D.image}
     * for more information.
     * @returns {RenderTarget2D} The created {@link RenderTarget2D}.
     */
    createRootRenderTarget(image: FrameImage = null): RenderTarget2D {
        return new RenderTarget2D(this, image, true);
    }

    /**
     * Releases a {@link RenderTarget2D} created by the {@link WebGLRenderer}.
     * @param target {RenderTarget2D} The {@link RenderTarget2D} to be released.
     */
    releaseRenderTarget(target: RenderTarget2D): void {
        if (!CommonUtil.isUndefinedOrNull(target)) {
            target.dispose();
        }
    }

    /**
     * Set current blend mode. Blend modes affects how the visual contents are rendered.
     * @param blendMode {String} See {@link BlendMode} for more information.
     * @see {@link BlendMode}
     */
    set blendMode(blendMode: string) {
        if (!this._isInitialized) {
            return;
        }
        if (this._blendMode === blendMode) {
            return;
        }

        const config: number[] = BMS[blendMode] || BMS[BlendMode.NORMAL];
        const glc = this._context;
        if (config[0] >= 0) {
            glc.blendEquation(gl.FUNC_ADD);
        } else {
            glc.blendEquation(gl.FUNC_SUBTRACT);
        }
        glc.blendFunc(config[1], config[2]);
        this._blendMode = blendMode;
    }

    /**
     * @returns {String}
     */
    get blendMode(): string {
        return this._blendMode;
    }

    /**
     * The default {@link RendererOptions} for instantiating a {@link WebGLRenderer}.
     * @type {RendererOptions}
     */
    static DEFAULT_OPTIONS: RendererOptions = {
        antialias: true,
        depth: false,
        transparent: true
    };

    /**
     * Initializes the newly created {@link WebGLRenderer}.
     * @param options {RendererOptions} Initialization options.
     * @param [canvas] {HTMLCanvasElement} Base canvas. If not specified, then a new canvas will be created using
     *                                     parameters width and height.
     * @param [width] {Number} The width, in pixels.
     * @param [height] {Number} The height, in pixels.
     * @private
     */
    private __initialize(options: RendererOptions, canvas: HTMLCanvasElement = null, width?: number, height?: number) {
        if (this._isInitialized) {
            return;
        }
        this._isInitialized = true;
        this._options = CommonUtil.deepClone(options);

        if (!canvas) {
            canvas = VirtualDom.createElement<HTMLCanvasElement>("canvas");
            canvas.className = "glantern-view";
        }
        if (!CommonUtil.isUndefined(width)) {
            canvas.width = width;
        }
        if (!CommonUtil.isUndefined(height)) {
            canvas.height = height;
        }

        const attributes: WebGLContextAttributes = Object.create(null);
        attributes.alpha = options.transparent;
        attributes.antialias = options.antialias;
        attributes.premultipliedAlpha = true;
        attributes.depth = false;
        this._context = WebGLUtils.setupWebGL(canvas, attributes);
        this._view = canvas;

        const glc = this._context;
        glc.disable(gl.DEPTH_TEST);
        glc.disable(gl.CULL_FACE);
        glc.enable(gl.BLEND);
        this.blendMode = BlendMode.NORMAL;

        this._screenRenderTarget = this.createRootRenderTarget();

        canvas.addEventListener("webglcontextlost", this.__onContextLost.bind(this));
        canvas.addEventListener("webglcontextrestored", this.__onContextRestored.bind(this));

        this._tessellator = new libtess.GluTesselator();
        this._shaderManager = new ShaderManager(this);
        this._filterManager = new FilterManager(this);

        this.currentRenderTarget = null;

        this.__initializeTessellator();
    }

    /**
     * Initializes the tessellator.
     * @private
     */
    private __initializeTessellator(): void {
        const tess = this._tessellator;
        tess.gluTessCallback(libtess.gluEnum.GLU_TESS_VERTEX_DATA,
            (data: number[], polyVertArray: number[][]): void => {
                polyVertArray[polyVertArray.length - 1].push(data[0], data[1]);
            });
        tess.gluTessCallback(libtess.gluEnum.GLU_TESS_BEGIN_DATA,
            (type: number, vertexArrays: number[][]): void => {
                if (type !== libtess.primitiveType.GL_TRIANGLES) {
                    console.warn('{TESS} expected TRIANGLES but got type: ' + type);
                }
                vertexArrays.push([]);
            });
        tess.gluTessCallback(libtess.gluEnum.GLU_TESS_ERROR,
            (errorCode: number): void => {
                console.warn('{TESS} error number: ', errorCode);
            });
        tess.gluTessCallback(libtess.gluEnum.GLU_TESS_COMBINE,
            (coords: number[], data: any, weight: number): number[] => {
                return [coords[0], coords[1]];
            });
        tess.gluTessCallback(libtess.gluEnum.GLU_TESS_EDGE_FLAG,
            (flag: any): void => {
                // Do nothing
            });
    }

    /**
     * The event handler for handling the lost of active {@link WebGLRenderingContext}.
     * @param ev {Event} Event parameters.
     */
    private __onContextLost(ev: Event): void {
    }

    /**
     * The event handler for handling the restoration of active {@link WebGLRenderingContext}.
     * @param ev {Event} Event parameters.
     */
    private __onContextRestored(ev: Event): void {
    }

    private _currentRenderTarget: RenderTarget2D = null;
    private _blendMode: string = null;
    private _screenRenderTarget: RenderTarget2D = null;
    private _filterManager: FilterManager = null;
    private _shaderManager: ShaderManager = null;
    private _tessellator: libtess.GluTesselator = null;
    private _isStencilTestEnabled: boolean = false;
    private _context: WebGLRenderingContext = null;
    private _view: HTMLCanvasElement;
    private _options: RendererOptions = null;
    private _isInitialized: boolean = false;

}

const BMS: {[k: string]: number[]} = Object.create(null);
BMS[BlendMode.ADD] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.ALPHA] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.DARKEN] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.DIFFERENCE] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.ERASE] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.HARDLIGHT] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.INVERT] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.LAYER] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.LIGHTEN] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.MULTIPLY] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.NORMAL] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.OVERLAY] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.SCREEN] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.SHADER] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
BMS[BlendMode.SUBTRACT] = [1, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];


text:
package org.spring.batch.infrastructure.readers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.spring.batch.infrastructure.model.Transaction;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ItemStreamReader;

/**
 * Created by iurii.dziuban on 18.07.2016.
 */
public class ParamForFutureStepReader implements ItemStreamReader<Transaction> {

    private static final Log LOGGER = LogFactory.getLog(ParamForFutureStepReader.class);

    private int numberOfTransactionsToRead = 2;

    private StepExecution stepExecution;

    @BeforeStep
    public void saveStepExecution(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }

    @Override
    public Transaction read() {
        if (numberOfTransactionsToRead == 0) {
            return null;
        }
        Transaction transaction = new Transaction();
        transaction.setId(numberOfTransactionsToRead);
        transaction.setName("ParamForStepReader item");
        numberOfTransactionsToRead--;
        ExecutionContext stepContext = this.stepExecution.getExecutionContext();
        stepContext.put("Name", "Iurii");
        return transaction;
    }

    @Override
    public void open(ExecutionContext executionContext) throws ItemStreamException {
        LOGGER.info("ParamForStepReader open connection invoked");
    }

    @Override
    public void update(ExecutionContext executionContext) throws ItemStreamException {
        LOGGER.info("ParamForStepReader update invoked to persist state");
    }

    @Override
    public void close() throws ItemStreamException {
        LOGGER.info("ParamForStepReader close connection invoked");
    }
}


text:
<?php namespace ChicoRei\Packages\Restify\Exceptions;

/**
 * Class StoreResourceException
 *
 * @package ChicoRei\Packages\Restify\Exceptions
 */
class StoreResourceException extends ResourceException
{

}


text:
load('lib/jspec.js')
load('lib/jspec.xhr.js')
load('spec/helpers.js')
load('spec/spec.grammar-less.js')

JSpec
.exec('spec/spec.grammar.js')
.exec('spec/spec.js')
.exec('spec/spec.matchers.js')
.exec('spec/spec.utils.js')
.exec('spec/spec.fixtures.js')
.exec('spec/spec.shared-behaviors.js')
.exec('spec/spec.modules.js')
.exec('spec/spec.xhr.js')
.run({ formatter : JSpec.formatters.Terminal, failuresOnly : false })
.report()


text:
# Card

http://www.getmdl.io/components/index.html#cards-section

## Usage

```javascript
// import { Card } from 'material-design-react';
import Card from 'material-design-react/card';

let myCard = (
  <Card shadow="2">
    <Card.Title border>
      <Card.TitleText>Look, a Card!</Card.TitleText>
      <Card.SubtitleText>It is, indeed.</CardSubtitleText>
    </Card.Title>

    <Card.Media>
      {/* ... */}
    </Card.Media>

    <Card.SupportingText>
      Some text to support the obvious.
    </Card.SupportingText>

    <Card.Actions border>
      <Button ripple>Do it!</Button>
    </Card.Actions>

    <Card.Menu>
      <Button icon className="material-icons">add</Button>
    </Card.Menu>
  </Card>
);
```

You may also use a shorthand with properties.

```javascript
let myCard = (
  <Card
    shadow="2"
    title="Look, a Card!"
    titleLevel="3"
    subtitle="It is, indeed."
    supporting="Some text to support the obvious."
    actions={[<Button>Act on it.</Button>, <Button accent>Do it!</Button>]}
    actionsBorder />
);
```

## Properties

Property | Type | Default | Effect | Remarks
-------- | -----| ------- | ------ | -------
shadow | one of: `2`, `3`, `4`, `6`, `8`,`16` | undefined | Assigns shadow with variable depths | Depths 5 and 7 don't exist
title | node | undefined | Adds title text | -
titleLevel | one of: `1`, `2`, `3`, `4`, `5`, `6` | `1` | Sets title's heading level | Sets html elements `<h1>` through `<h6>`
titleBorder | bool| undefined | Adds border to title container | -
subtitle | node | undefined | Adds subtitle | -
supporting | node | undefined | Adds supporting text | -
media | node | undefined | Adds media content | -
actions | node | undefined | Adds actions | -
actionsBorder | bool | undefined | Adds border to actions container | -
menu | node | undefined | Adds menu | Usually a mdl/mdr icon button (plus menu)

## Children

* [Title](./title/README.md)
* [TitleText](./title-text/README.md)
* [SubtitleText](./subtitle-text/README.md)
* [SupportingText](./supporting-text/README.md)
* [Media](./media/README.md)
* [Actions](./actions/README.md)
* [Menu](./menu/README.md)

## Notes

When using `Card` with props the order in which children are rendered is as follows:

1. `title`
2. `subtitle`
3. `supporting`
4. `media`
5. `children` (prop or actual)
6. `actions`
7. `menu`

If your use case seeks a different order, use `Card` with children instead or mix as needed (as `children` will be rendered in any case).


text:
package org.locationtech.geowave.analytic.param;

import org.apache.hadoop.fs.Path;

public class InputParameters {
  public enum Input implements ParameterEnum<Object> {
    INPUT_FORMAT(FormatConfiguration.class, "ifc", "Input Format Class", true, true),
    HDFS_INPUT_PATH(Path.class, "iip", "Input HDFS File Path", false, true);

    private final ParameterHelper<Object> helper;

    private Input(
        final Class baseClass,
        final String name,
        final String description,
        final boolean isClass,
        final boolean hasArg) {
      helper = new BasicParameterHelper(this, baseClass, name, description, isClass, hasArg);
    }

    @Override
    public Enum<?> self() {
      return this;
    }

    @Override
    public ParameterHelper<Object> getHelper() {
      return helper;
    }
  }
}


text:
package yuku.alkitabconverter.util;

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;

public class Usfm2Usfx {
	static final String TAG = Usfm2Usfx.class.getSimpleName();

	public static int convert(String nfi, String nfo) {

		final String nfiString = Paths.get(Paths.get("").toAbsolutePath().toString()).relativize(Paths.get(nfi)).toString();
		final String nfoString = Paths.get(Paths.get("").toAbsolutePath().toString()).relativize(Paths.get(nfo)).toString();

		new File(nfo).delete();
		try {
			// patch dulu
			final String[] command = {"mono", new File("./prog/wordsend/usfm2usfx.exe").getAbsolutePath(), "-o", nfoString, nfiString};
			System.out.println("Command: " + Arrays.toString(command));

			Process p = new ProcessBuilder(command).redirectErrorStream(true).start();
			Scanner sc = new Scanner(p.getInputStream());
			while (sc.hasNextLine()) {
				System.out.println(sc.nextLine());
			}
			sc.close();
			return p.waitFor();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}


text:
'use strict';

const $ = require('../../js/lib/jquery.js');

module.exports = {
	project: null,
	trees: null,
	treeCategories: null,
	variables: null,
	nodes: [],
	getNodeCoordinates(treeId, nodeId) {
		const node = this.getNodeByID(treeId, nodeId);

		return {
			x: node.editor.x,
			y: node.editor.y
		};
	},
	addNode(treeId, x, y) {
		const currentTree = this.getTreeByID(treeId);

		let newId = 0;
		if (currentTree.nodes.length > 0) {
			newId = currentTree.nodes[currentTree.nodes.length - 1].id + 1;
		}

		currentTree.nodes.push({
			id: newId,
			editor: {
				x: x || 0,
				y: y || 0
			}
		});

		return newId;
	},
	changeNode(state, nodeElement, newType) {
		const dataNodeId = nodeElement.data('id');
		const dataNode = this.getNodeByID(state.currentTree, dataNodeId);

		this.unlink(state, dataNodeId);
		delete dataNode.conditions;
		delete dataNode.elements;
		dataNode.type = newType;
	},
	updateNode(state, nodeElement, nodes) {
		const dataNodeId = nodeElement.data('id');
		const dataNode = this.getNodeByID(state.currentTree, dataNodeId);

		if (typeof dataNode !== 'undefined') {
			dataNode.type = nodeElement.find('select.nodetype option:selected').val();
			const nodeType = nodes.getNodeById(dataNode.type).type;

			dataNode.elements = {};
			$.each(nodeElement.find('.controls [data-binding]'), (i, e) => {
				switch ($(e).prop('tagName')) {
					case 'INPUT':
						dataNode.elements[$(e).data('binding')] = $(e).val();
						break;
					case 'TEXTAREA':
						this.setText(state.currentLanguage, `$T${state.currentTree}N${dataNodeId}E${i}`, $(e).val());
						dataNode.elements[$(e).data('binding')] = `$T${state.currentTree}N${dataNodeId}E${i}`;
						break;
					case 'SELECT':
						dataNode.elements[$(e).data('binding')] = ($(e).find('option:selected').val() === 'placeholder') ? '' : $(e).find('option:selected').val();
						break;
					default:
						break;
				}
			});

			if (nodeType === 'branch') {
				dataNode.nodetype = 'branch';
				dataNode.conditions = dataNode.conditions || [];
				$.each(nodeElement.find('.conditions .branch .value'), (i, e) => {
					dataNode.conditions[i] = dataNode.conditions[i] || {};
					dataNode.conditions[i].variable = $(e).parent().find('select[data-variable-get] option:selected').val();
					dataNode.conditions[i].condition = $(e).find('select[data-condition] option:selected').val();

					const validation = $(e).parent().find('select[data-variable-get] option:selected').data('validation');

					if (validation === 'int') {
						dataNode.conditions[i].value = $(e).find('input[data-int]').val();
					} else if (validation === 'string') {
						dataNode.conditions[i].value = $(e).find('input[data-string]').val();
					} else if (validation === 'bool') {
						dataNode.conditions[i].value = $(e).find('select[data-bool] option:selected').val();
					} else if (validation === 'enum') {
						dataNode.conditions[i].value = $(e).find('select[data-enum] option:selected').val();
					}
				});
			} else if (nodeType === 'set') {
				dataNode.nodetype = 'set';
				dataNode.set = {
					variable: nodeElement.find('.set select[data-variable-set] option:selected').val(),
					operation: nodeElement.find('.set .value select[data-operation] option:selected').val()
				};

				const validation = nodeElement.find('.set select[data-variable-set] option:selected').data('validation');
				if (validation === 'int') {
					dataNode.set.value = nodeElement.find('.set .value input[data-int]').val();
				} else if (validation === 'string') {
					dataNode.set.value = nodeElement.find('.set .value input[data-string]').val();
				} else if (validation === 'bool') {
					dataNode.set.value = nodeElement.find('.set .value select[data-bool] option:selected').val();
				} else if (validation === 'enum') {
					dataNode.set.value = nodeElement.find('.set .value select[data-enum] option:selected').val();
				}
			} else {
				dataNode.nodetype = 'normal';
			}
		}
	},
	removeNode(state, id) {
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].id === state.currentTree) {
				const tree = this.trees[i];
				for (let j = 0; j < tree.nodes.length; j++) {
					if (tree.nodes[j].id === id) {
						tree.nodes[j] = undefined;
					}
				}
			}
		}

		// this removes the undefined nodes
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].id === state.currentTree) {
				this.trees[i].nodes = this.trees[i].nodes.filter(Boolean);
			}
		}

		this.trees[state.currentTree].nodes.forEach(node => {
			if (typeof node.conditions !== 'undefined' && node.conditions.length > 0) {
				for (const condition of node.conditions) {
					if (typeof condition.link !== 'undefined' && condition.link === id) {
						condition.link = -1;
					}
				}
			}
		});
	},
	// removes all links from/to this node
	unlink(state, id) {
		if (typeof this.trees[state.currentTree] !== 'undefined') {
			this.trees[state.currentTree].nodes.forEach(node => {
				if (typeof node.conditions !== 'undefined' && node.conditions.length > 0) {
					for (const condition of node.conditions) {
						if (condition !== null && typeof condition.link !== 'undefined' && condition.link === id) {
							condition.link = -1;
						}
					}
				}
			});
		}
	},
	link(state, nodes) {
		const nodeFrom = this.getNodeByID(state.currentTree, state.link.linkingFrom.data('id'));
		nodeFrom.conditions = nodeFrom.conditions || [];
		nodeFrom.conditions[state.link.linkIndex] = {};
		nodeFrom.conditions[state.link.linkIndex].link = state.link.linkTarget.data('id');
		this.updateNode(state, state.link.linkingFrom, nodes);
	},
	bumpLinks(state, id, elseLinked) {
		const nodeFrom = this.getNodeByID(state.currentTree, id);
		if (typeof nodeFrom.conditions === 'undefined') {
			nodeFrom.conditions = [];
		} else if (elseLinked) {
			nodeFrom.conditions[nodeFrom.conditions.length] = nodeFrom.conditions[nodeFrom.conditions.length - 1];
			nodeFrom.conditions[nodeFrom.conditions.length - 2] = undefined;
		} else {
			nodeFrom.conditions.push(undefined);
		}
	},
	getText(language, key) {
		for (let i = 0; i < this.translations.length; i++) {
			if (this.translations[i][language] !== undefined) {
				const lang = this.translations[i][language];
				for (let j = 0; j < lang.length; j++) {
					if (lang[j].flag === key) {
						return lang[j].content;
					}
				}
			}
		}
	},
	setText(language, key, text) {
		for (let i = 0; i < this.translations.length; i++) {
			if (this.translations[i][language] !== undefined) {
				const lang = this.translations[i][language];
				if (lang.length > 0) {
					for (let j = 0; j < lang.length; j++) {
						if (lang[j].flag === key) {
							lang[j].content = text;
							return;
						} else if (lang[j].flag !== key && j === lang.length - 1) {
							lang.push({flag: key, content: text});
							return;
						}
					}
				} else {
					lang.push({flag: key, content: text});
				}
			}
		}
	},
	getNodeByID(treeId, nodeId) {
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].id === treeId) {
				const tree = this.trees[i];
				for (let j = 0; j < tree.nodes.length; j++) {
					if (tree.nodes[j] !== undefined && tree.nodes[j].id === nodeId) {
						return tree.nodes[j];
					}
				}
			}
		}
	},
	getTreeByID(treeId) {
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].id === treeId) {
				return this.trees[i];
			}
		}
	},
	getVariableByID(variableId) {
		for (let i = 0; i < this.variables.length; i++) {
			if (this.variables[i].id === variableId) {
				return this.variables[i];
			}
		}
	},
	addVariable(displayName, validation, get, set) {
		let id = 0;
		if (this.variables.length > 0) {
			id = this.variables[this.variables.length - 1].id + 1;
		}

		this.variables.push({
			displayName,
			validation,
			set,
			get,
			id
		});

		return id;
	},
	removeVariable(variableId) {
		for (let i = 0; i < this.variables.length; i++) {
			if (this.variables[i].id === variableId) {
				this.variables[i] = undefined;
			}
		}

		// filters out the undefined variables
		this.variables = this.variables.filter(Boolean);
	},
	duplicateVariableExists(variableName) {
		for (let i = 0; i < this.variables.length; i++) {
			if (this.variables[i].displayName === variableName) {
				return true;
			}
		}

		return false;
	},
	getVariableValuesById(id) {
		const values = this.getVariableByID(parseInt(id, 10)).values;
		return (typeof values === 'undefined') ? [] : values;
	},
	addVariableValue(id, value, displayName) {
		const variable = this.getVariableByID(parseInt(id, 10));
		variable.values = variable.values || [];
		variable.values.push({
			value,
			displayName
		});
	},
	duplicateVariableValueExists(id, value, displayName) {
		const values = this.getVariableValuesById(id);
		value = (isNaN(parseInt(value, 10))) ? value : parseInt(value, 10);
		for (const val of values) {
			if (val.value === value || val.displayName === displayName) {
				return true;
			}
		}

		return false;
	},
	removeVariableValue(id, value) {
		value = (isNaN(parseInt(value, 10))) ? value : parseInt(value, 10);
		for (let i = 0; i < this.variables.length; i++) {
			if (this.variables[i].id === parseInt(id, 10)) {
				for (let j = 0; j < this.variables[i].values.length; j++) {
					if (this.variables[i].values[j].value === value) {
						this.variables[i].values[j] = undefined;
					}
				}

				// filters out the undefined variables
				this.variables[i].values = this.variables[i].values.filter(Boolean);
			}
		}
	},
	addTree(treeName, catId) {
		let newId = 0;
		if (this.trees.length > 0) {
			newId = this.trees[this.trees.length - 1].id + 1;
		}

		this.trees.push({
			id: newId,
			categoryId: catId,
			displayName: treeName,
			nodes: []
		});

		$('section#nodes').append(`<section class='tree' data-id='${newId}'></section>`);
		$(`select.trees optgroup[data-tree-category-id="${catId}"]`).append(`<option data-tree="${newId}">${treeName}</option>`);
		$('select.trees').trigger('chosen:updated');

		return newId;
	},
	removeTree(state, treeId) {
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].id === treeId) {
				this.trees[i] = undefined;
			}
		}

		// filters out the undefined variables
		this.trees = this.trees.filter(Boolean);

		// remove tree refs
		$(`select.trees option[data-tree="${treeId}"]`).remove();
		$(`#nodes .tree[data-id="${treeId}"]`).remove();

		// invalidate the current tree if we just deleted it
		if (state.currentTree === treeId) {
			$("select.trees").val('').trigger('change');
		}

		$("select.trees").trigger("chosen:updated");
	},
	duplicateTreeExists(treeName, categoryId) {
		for (let i = 0; i < this.trees.length; i++) {
			if (this.trees[i].categoryId === parseInt(categoryId, 10) && this.trees[i].displayName.toLowerCase() === treeName.toLowerCase()) {
				return true;
			}
		}

		return false;
	}
};


text:
package org.schema.api.model.thing.creativeWork.article.scholarlyArticle;

import org.schema.api.model.thing.creativeWork.article.scholarlyArticle.ScholarlyArticle;

public class MedicalScholarlyArticle extends ScholarlyArticle
{
}


text:
+++
date = "2017-01-21T13:38:21-06:00"
title = "Statistical Significance vs Economic Significance"
draft = true
image = ""
+++


text:
using UnityEngine;
using System.Collections;

public class LocalCarController : MonoBehaviour
{

    void Update()
    {
        gameObject.GetComponent<CarController>().mySpeed = Input.GetAxis("Vertical");
        gameObject.GetComponent<CarController>().mySteer = Input.GetAxis("Horizontal");
        gameObject.GetComponent<CarController>().myBrake = Input.GetAxis("Brake");
    }
}


text:
package de.craften.plugins.educraft.environment;

import de.craften.plugins.educraft.EduCraft;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.world.StructureGrowEvent;

import java.util.Iterator;
import java.util.List;

/**
 * Fire and griefing protection for environments.
 */
public class EnvironmentProtection implements Listener {
    /**
     * Gets the environment at the given location.
     *
     * @param location location to get the environment at
     * @return the environment at the given location or null if none exists
     */
    private static EduCraftEnvironment getEnvironment(Location location) {
        for (EduCraftEnvironment environment : EduCraft.getPlugin(EduCraft.class).getEnvironments()) {
            if (environment.contains(location)) {
                return environment;
            }
        }
        return null;
    }

    /**
     * Checks if the given location is in any environment.
     *
     * @param location location to check
     * @return true if the given location is in any environment, false if not
     */
    private static boolean isInEnvironment(Location location) {
        return getEnvironment(location) != null;
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockPlace(BlockPlaceEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getBlockPlaced().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockBreak(BlockBreakEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) {
        Block block = event.getBlockClicked().getRelative(event.getBlockFace());
        if (!event.getPlayer().isOp() && isInEnvironment(block.getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerBucketFill(PlayerBucketFillEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getBlockClicked().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerInteract(PlayerInteractEvent event) {
        if (event.getClickedBlock() != null && !event.getPlayer().isOp() && isInEnvironment(event.getClickedBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockSpread(BlockSpreadEvent event) {
        if (isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockForm(BlockFormEvent event) {
        if (isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockDamage(BlockDamageEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockFade(BlockFadeEvent event) {
        if (isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockFromTo(BlockFromToEvent event) {
        if (isInEnvironment(event.getBlock().getLocation()) && !isInEnvironment(event.getToBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockPistonExtend(BlockPistonExtendEvent event) {
        boolean first = isInEnvironment(event.getBlock().getLocation());
        for (Block b : event.getBlocks()) {
            if (isInEnvironment(b.getRelative(event.getDirection()).getLocation()) != first) {
                event.setCancelled(true);
                return;
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockPistonRetract(BlockPistonRetractEvent event) {
        boolean first = isInEnvironment(event.getBlock().getLocation());
        for (Block b : event.getBlocks()) {
            if (isInEnvironment(b.getRelative(event.getDirection()).getLocation()) != first) {
                event.setCancelled(true);
                return;
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onStructureGrow(StructureGrowEvent event) {
        boolean inEnvironment = isInEnvironment(event.getLocation());
        List<BlockState> blocks = event.getBlocks();

        Iterator<BlockState> it = blocks.iterator();
        while (it.hasNext()) {
            if (isInEnvironment(it.next().getLocation()) != inEnvironment) {
                it.remove();
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onEntityExplode(EntityExplodeEvent event) {
        if (isInEnvironment(event.getLocation())) {
            event.setCancelled(false);

            List<Block> blocks = event.blockList();
            Iterator<Block> it = blocks.iterator();
            while (it.hasNext()) {
                if (!isInEnvironment(it.next().getLocation())) {
                    it.remove();
                }
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onBlockIgnite(BlockIgniteEvent event) {
        if (!isInEnvironment(event.getBlock().getLocation())) {
            if (event.getPlayer() == null || !event.getPlayer().isOp()) {
                event.setCancelled(true);
            }
        } else if (event.getIgnitingBlock() != null && isInEnvironment(event.getIgnitingBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onEntityDamage(EntityDamageEvent event) {
        EduCraftEnvironment environment = getEnvironment(event.getEntity().getLocation());
        if (environment != null) {
            if (event.getEntity().equals(environment.getEntity().getEntity())) {
                if (event.getCause() == EntityDamageEvent.DamageCause.FIRE || event.getCause() == EntityDamageEvent.DamageCause.FIRE_TICK) {
                    event.getEntity().setFireTicks(0); //don't let the bot burn
                }
                event.setCancelled(true); //prevent bot from getting any damage
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onHangingPlace(HangingPlaceEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onHangingBreakByEntity(HangingBreakByEntityEvent event) {
        if (!event.getRemover().isOp() && isInEnvironment(event.getEntity().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getRightClicked().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onAttack(EntityDamageByEntityEvent event) {
        if (!event.getDamager().isOp() && isInEnvironment(event.getEntity().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerShearEntity(PlayerShearEntityEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getEntity().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerEggThrow(PlayerEggThrowEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getEgg().getLocation())) {
            event.setHatching(false);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onEntityChangeBlock(EntityChangeBlockEvent event) {
        if (event.getEntity() instanceof Player && !event.getEntity().isOp() && isInEnvironment(event.getBlock().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onArmorStandManipulated(PlayerArmorStandManipulateEvent event) {
        if (!event.getPlayer().isOp() && isInEnvironment(event.getRightClicked().getLocation())) {
            event.setCancelled(true);
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    public void onEntityDeath(EntityDeathEvent event) {
        if (isInEnvironment(event.getEntity().getLocation())) {
            event.getDrops().clear();
        }
    }
}