text:
package org.javaan.model;

import static junit.framework.TestCase.assertNull;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;
import java.util.Set;

import org.junit.Assert;
import org.junit.Test;

public class TestClassContext {

	private static final Package PACKAGEABC = new Package("a.b.c");
	private static final Package PACKAGEDEF = new Package("d.e.f");

	private static final Clazz CLASSA = new Clazz(PACKAGEABC + ".A");
	private static final Clazz CLASSB = new Clazz(PACKAGEABC + ".B");
	private static final Clazz CLASSC = new Clazz(PACKAGEDEF + ".C");
	private static final Clazz CLASSD = new Clazz("D");
	private static final Clazz CLASSX = new Clazz("X");
	private static final Clazz CLASSY = new Clazz(PACKAGEDEF + ".Y");

	private static final Interface INTERFACEA = new Interface(PACKAGEABC + ".IA");
	private static final Interface INTERFACEB = new Interface(PACKAGEABC + ".IB");
	private static final Interface INTERFACEC = new Interface(PACKAGEDEF + ".IC");
	private static final Interface INTERFACED = new Interface("ID");
	private static final Interface INTERFACEX = new Interface("IX");
	private static final Interface INTERFACEY = new Interface(PACKAGEDEF + ".IY");

	private static final Method CLASSA_METHODA = new Method(CLASSA, "methoda");
	private static final Method CLASSA_METHODB = new Method(CLASSA, "methodb");
	private static final Method CLASSA_METHODC = new Method(CLASSA, "methodc");
	private static final Method CLASSB_METHODC = new Method(CLASSB, "methodc");

	private static final Method INTERFACEA_METHODA = new Method(INTERFACEA, "methoda");
	private static final Method INTERFACEA_METHODB = new Method(INTERFACEA, "methodb");
	private static final Method INTERFACEA_METHODC = new Method(INTERFACEA, "methodc");
	private static final Method INTERFACEB_METHODC = new Method(INTERFACEB, "methodc");

	@Test
	public void testAddClass() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
		context.addClass(CLASSB);
		context.addClass(CLASSC);
		Set<Clazz> classes = context.getClasses();
		assertNotNull(classes);
		assertEquals(3, classes.size());
		assertTrue(classes.contains(CLASSA));
		assertTrue(classes.contains(CLASSB));
		assertTrue(classes.contains(CLASSC));
		assertSame(CLASSA, context.get(CLASSA.getName()));
		assertSame(CLASSB, context.get(CLASSB.getName()));
		assertSame(CLASSC, context.get(CLASSC.getName()));
		Set<Package> packages = context.getPackages();
		assertNotNull(packages);
		assertEquals(2, packages.size());
		assertTrue(packages.contains(PACKAGEABC));
		assertTrue(packages.contains(PACKAGEDEF));
		classes = context.getClassesOfPackage(PACKAGEABC);
		assertNotNull(classes);
		assertEquals(2, classes.size());
		assertTrue(classes.contains(CLASSA));
		assertTrue(classes.contains(CLASSB));
		classes = context.getClassesOfPackage(PACKAGEDEF);
		assertNotNull(classes);
		assertEquals(1, classes.size());
		assertTrue(classes.contains(CLASSC));
		assertEquals(PACKAGEABC, context.getPackageOfType(CLASSA));
	}

	@Test
	public void testAddSuperClass() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
		context.addClass(CLASSB);
		context.addClass(CLASSX);
		context.addClass(CLASSY);
		context.addSuperClass(CLASSB, CLASSA);
		context.addSuperClass(CLASSX, CLASSY);

		assertTrue(context.containsClass(CLASSY));
		Assert.assertNull(context.getSuperClass(CLASSA));
		assertEquals(CLASSA, context.getSuperClass(CLASSB));
		Assert.assertNull(context.getSuperClass(CLASSY));
		assertEquals(CLASSY, context.getSuperClass(CLASSX));
		assertSame(CLASSA, context.get(CLASSA.getName()));
		assertSame(CLASSB, context.get(CLASSB.getName()));
		assertSame(CLASSX, context.get(CLASSX.getName()));
		assertSame(CLASSY, context.get(CLASSY.getName()));
		assertEquals(PACKAGEDEF, context.getPackageOfType(CLASSY));
	}

	@Test
	public void testGetSuperClasses() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
        context.addClass(CLASSB);
        context.addClass(CLASSC);
		context.addSuperClass(CLASSB, CLASSA);
		context.addSuperClass(CLASSC, CLASSB);

		List<Clazz> superClasses = context.getSuperClassHierarchy(CLASSC);
		assertNotNull(superClasses);
		assertEquals(3, superClasses.size());
		assertEquals(CLASSC, superClasses.get(0));
		assertEquals(CLASSB, superClasses.get(1));
		assertEquals(CLASSA, superClasses.get(2));
	}

	@Test
	public void testGetDirectSpecializationOfClass() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
        context.addClass(CLASSB);
        context.addClass(CLASSC);
        context.addClass(CLASSD);
		context.addSuperClass(CLASSB, CLASSA);
		context.addSuperClass(CLASSC, CLASSB);
		context.addSuperClass(CLASSD, CLASSA);

		Set<Clazz> spec = context.getDirectSpecializationsOfClass(CLASSA);
		assertNotNull(spec);
		assertEquals(2, spec.size());
		assertTrue(spec.contains(CLASSB));
		assertTrue(spec.contains(CLASSD));

		spec = context.getDirectSpecializationsOfClass(CLASSD);
		assertNotNull(spec);
		assertEquals(0, spec.size());
	}

	@Test
	public void testGetSpecializationOfClass() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
        context.addClass(CLASSB);
        context.addClass(CLASSC);
		context.addSuperClass(CLASSB, CLASSA);
		context.addSuperClass(CLASSC, CLASSB);

		Set<Clazz> spec = context.getSpecializationsOfClass(CLASSA);
		assertNotNull(spec);
		assertEquals(2, spec.size());
		assertTrue(spec.contains(CLASSB));
		assertTrue(spec.contains(CLASSC));

		spec = context.getSpecializationsOfClass(CLASSC);
		assertNotNull(spec);
		assertEquals(0, spec.size());
	}

	@Test
	public void testAddInterface() {
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
		context.addInterface(INTERFACEB);
		context.addInterface(INTERFACEC);
		Set<Interface> interfaces = context.getInterfaces();
		assertNotNull(interfaces);
		assertEquals(3, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEA));
		assertTrue(interfaces.contains(INTERFACEB));
		assertTrue(interfaces.contains(INTERFACEC));
		assertSame(INTERFACEA, context.get(INTERFACEA.getName()));
		assertSame(INTERFACEB, context.get(INTERFACEB.getName()));
		assertSame(INTERFACEC, context.get(INTERFACEC.getName()));
		Set<Package> packages = context.getPackages();
		assertNotNull(packages);
		assertEquals(2, packages.size());
		assertTrue(packages.contains(PACKAGEABC));
		assertTrue(packages.contains(PACKAGEDEF));
		interfaces = context.getInterfacesOfPackage(PACKAGEABC);
		assertNotNull(interfaces);
		assertEquals(2, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEA));
		assertTrue(interfaces.contains(INTERFACEB));
		interfaces = context.getInterfacesOfPackage(PACKAGEDEF);
		assertNotNull(interfaces);
		assertEquals(1, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEC));
		assertEquals(PACKAGEABC, context.getPackageOfType(INTERFACEA));
	}

	@Test
	public void testAddSuperInterfaces() {
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
		context.addInterface(INTERFACEB);
		context.addInterface(INTERFACEC);
		context.addInterface(INTERFACED);
		context.addInterface(INTERFACEX);
		context.addInterface(INTERFACEY);
		context.addSuperInterface(INTERFACEB, INTERFACEA);
		context.addSuperInterface(INTERFACEB, INTERFACEC);
		context.addSuperInterface(INTERFACEC, INTERFACED);
		context.addSuperInterface(INTERFACEX, INTERFACEY);

		Set<Interface> interfaces = context.getSuperInterfaces(INTERFACEA);
		assertNotNull(interfaces);
		assertEquals(0, interfaces.size());

		interfaces = context.getSuperInterfaces(INTERFACEB);
		assertNotNull(interfaces);
		assertEquals(3, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEA));
		assertTrue(interfaces.contains(INTERFACEC));
		assertTrue(interfaces.contains(INTERFACED));

		assertTrue(context.containsInterface(INTERFACEY));
		interfaces = context.getSuperInterfaces(INTERFACEX);
		assertNotNull(interfaces);
		assertEquals(1, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEY));
		assertSame(INTERFACEA, context.get(INTERFACEA.getName()));
		assertSame(INTERFACEB, context.get(INTERFACEB.getName()));
		assertSame(INTERFACEC, context.get(INTERFACEC.getName()));
		assertSame(INTERFACED, context.get(INTERFACED.getName()));
		assertSame(INTERFACEX, context.get(INTERFACEX.getName()));
		assertSame(INTERFACEY, context.get(INTERFACEY.getName()));
		assertEquals(PACKAGEDEF, context.getPackageOfType(INTERFACEY));
	}

	@Test
	public void testSpecializationOfInterface() {
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
        context.addInterface(INTERFACEB);
        context.addInterface(INTERFACEC);
		context.addSuperInterface(INTERFACEB, INTERFACEA);
		context.addSuperInterface(INTERFACEC, INTERFACEB);

		Set<Interface> interfaces = context.getSpecializationOfInterface(INTERFACEA);
		assertNotNull(interfaces);
		assertEquals(2, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEB));
		assertTrue(interfaces.contains(INTERFACEC));

		interfaces = context.getSpecializationOfInterface(INTERFACEC);
		assertNotNull(interfaces);
		assertEquals(0, interfaces.size());
	}

	@Test(expected = IllegalArgumentException.class)
	public void testAddInterfaceOfClassUnknownClass() {
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
		context.addInterfaceOfClass(CLASSA, INTERFACEA);
		fail("Exepect Exception");
	}

	@Test(expected = IllegalArgumentException.class)
	public void testAddInterfaceOfClassUnknownInterface() {
		ClassContext context = new ClassContext();
		context.addClass(CLASSA);
		context.addInterfaceOfClass(CLASSA, INTERFACEA);
		fail("Exepect Exception");
	}

	@Test
	public void testGetInterfacesOfClass() {
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
		context.addInterface(INTERFACEB);
		context.addInterface(INTERFACEC);
		context.addInterface(INTERFACEX);
		context.addInterface(INTERFACEY);
		context.addSuperInterface(INTERFACEA, INTERFACEB);
		context.addSuperInterface(INTERFACEB, INTERFACEC);
		context.addSuperInterface(INTERFACEX, INTERFACEY);

		context.addClass(CLASSA);
        context.addClass(CLASSB);
        context.addClass(CLASSC);
        context.addClass(CLASSD);
		context.addSuperClass(CLASSA, CLASSB);
		context.addSuperClass(CLASSB, CLASSC);
		context.addSuperClass(CLASSC, CLASSD);

		context.addInterfaceOfClass(CLASSA, INTERFACEA);
		context.addInterfaceOfClass(CLASSC, INTERFACEX);

		Set<Interface> interfaces = context.getInterfacesOfClass(CLASSD);
		assertNotNull(interfaces);
		assertEquals(0, interfaces.size());

		interfaces = context.getInterfacesOfClass(CLASSA);
		assertNotNull(interfaces);
		assertEquals(5, interfaces.size());
		assertTrue(interfaces.contains(INTERFACEA));
		assertTrue(interfaces.contains(INTERFACEB));
		assertTrue(interfaces.contains(INTERFACEC));
		assertTrue(interfaces.contains(INTERFACEX));
		assertTrue(interfaces.contains(INTERFACEY));
	}

	@Test
	public void testGetImplementations() {
		/*
			interfaces:
			- ia --> ib --> ix
			- ic

			classes:
			classa
			classd --> classc --> classb

			direct implementations:
			classa --> ia, ic
			classb --> ia

		 */
		ClassContext context = new ClassContext();
		context.addInterface(INTERFACEA);
        context.addInterface(INTERFACEB);
        context.addInterface(INTERFACEC);
        context.addInterface(INTERFACEX);
		context.addSuperInterface(INTERFACEA, INTERFACEB);
		context.addSuperInterface(INTERFACEB, INTERFACEX);
		context.addClass(CLASSA);
		context.addClass(CLASSB);
        context.addClass(CLASSC);
        context.addClass(CLASSD);
		context.addSuperClass(CLASSC, CLASSB);
		context.addSuperClass(CLASSD, CLASSC);
		context.addInterfaceOfClass(CLASSA, INTERFACEA);
		context.addInterfaceOfClass(CLASSA, INTERFACEC);
		context.addInterfaceOfClass(CLASSB, INTERFACEA);

		Set<Clazz> classes = context.getImplementations(INTERFACEA);
		assertNotNull(classes);
		assertEquals(4, classes.size());
		assertTrue(classes.contains(CLASSA));
		assertTrue(classes.contains(CLASSB));
		assertTrue(classes.contains(CLASSC));
		assertTrue(classes.contains(CLASSD));

		classes = context.getImplementations(INTERFACEB);
		assertNotNull(classes);
		assertEquals(4, classes.size());
		assertTrue(classes.contains(CLASSA));
		assertTrue(classes.contains(CLASSB));
		assertTrue(classes.contains(CLASSC));
		assertTrue(classes.contains(CLASSD));

		classes = context.getImplementations(INTERFACEC);
		assertNotNull(classes);
		assertEquals(1, classes.size());
		assertTrue(classes.contains(CLASSA));

		classes = context.getImplementations(INTERFACEX);
		assertNotNull(classes);
		assertEquals(4, classes.size());
		assertTrue(classes.contains(CLASSA));
		assertTrue(classes.contains(CLASSB));
		assertTrue(classes.contains(CLASSC));
		assertTrue(classes.contains(CLASSD));
	}

	@Test(expected = IllegalArgumentException.class)
	public void testAddMethodMissingType() {
		new ClassContext().addMethod(CLASSA_METHODA);
		fail("Exoecting illegal argument exception");
	}

	@Test
	public void testGetMethods() {
		ClassContext context = new ClassContext();

		context.addClass(CLASSA);
		context.addInterface(INTERFACEA);

		context.addMethod(CLASSA_METHODA);
		context.addMethod(INTERFACEA_METHODA);

		Set<Method> methods = context.getMethods();
		assertNotNull(methods);
		assertEquals(2, methods.size());
		assertTrue(methods.contains(CLASSA_METHODA));
		assertTrue(methods.contains(INTERFACEA_METHODA));
	}

	@Test
	public void testGetMethodsOfType() {
		ClassContext context = new ClassContext();

		context.addClass(CLASSA);
		context.addClass(CLASSB);
		context.addInterface(INTERFACEA);

		context.addMethod(CLASSA_METHODA);
		context.addMethod(CLASSA_METHODB);
		context.addMethod(CLASSA_METHODC);

		context.addMethod(INTERFACEA_METHODA);
		context.addMethod(INTERFACEA_METHODB);
		context.addMethod(INTERFACEA_METHODC);

		List<Method> methods = context.getMethods(CLASSB);
		assertNull(methods);

		methods = context.getMethods(CLASSA);
		assertNotNull(methods);
		assertEquals(3, methods.size());
		assertTrue(methods.contains(CLASSA_METHODA));
		assertTrue(methods.contains(CLASSA_METHODB));
		assertTrue(methods.contains(CLASSA_METHODC));

		methods = context.getMethods(INTERFACEA);
		assertNotNull(methods);
		assertEquals(3, methods.size());
		assertTrue(methods.contains(INTERFACEA_METHODA));
		assertTrue(methods.contains(INTERFACEA_METHODB));
		assertTrue(methods.contains(INTERFACEA_METHODC));

		assertSame(CLASSA_METHODA, context.getMethod(CLASSA, "methoda"));
		assertSame(INTERFACEA_METHODA, context.getMethod(INTERFACEA, "methoda"));
	}

	@Test
	public void testGetVirtualMethodsOfType() {
		ClassContext context = new ClassContext();

		context.addClass(CLASSA);
        context.addClass(CLASSB);
		context.addSuperClass(CLASSB, CLASSA);
		context.addInterface(INTERFACEA);
        context.addInterface(INTERFACEB);
		context.addSuperInterface(INTERFACEB, INTERFACEA);

		context.addMethod(CLASSA_METHODA);
		context.addMethod(CLASSA_METHODC);
		context.addMethod(INTERFACEA_METHODA);
		context.addMethod(INTERFACEA_METHODB);
		context.addMethod(INTERFACEA_METHODC);
		context.addMethod(INTERFACEB_METHODC);
		context.addMethod(CLASSA_METHODB);
		context.addMethod(CLASSB_METHODC);

		Set<Method> methods = context.getVirtualMethods(CLASSB);
		assertNotNull(methods);
		assertEquals(4, methods.size());
		assertTrue(methods.contains(CLASSA_METHODA));

		methods = context.getVirtualMethods(INTERFACEB);
		assertNotNull(methods);
		assertEquals(4, methods.size());
		assertTrue(methods.contains(INTERFACEA_METHODA));

		assertSame(CLASSA_METHODA, context.getVirtualMethod(CLASSB, "methoda"));
		assertSame(INTERFACEA_METHODA, context.getVirtualMethod(INTERFACEB, "methoda"));
		assertSame(INTERFACEB_METHODC, context.getVirtualMethod(INTERFACEB, "methodc"));
		assertSame(CLASSB_METHODC, context.getVirtualMethod(CLASSB, "methodc"));
	}
}


text:
@implementation MMSierraCloseButtonCell

- (void)drawImage:(NSImage *)image withFrame:(NSRect)frame inView:(NSView *)controlView {
    static NSImage *closeImage = nil;
    static NSImage *editedImage = nil;

    if (!closeImage) {
        closeImage = [[NSImage alloc] initByReferencingFile:[[NSBundle bundleForClass:[self class]] pathForImageResource:@"MMSierraTabClose"]];
    }

    if (!editedImage) {
        editedImage = [[NSImage alloc] initByReferencingFile:[[NSBundle bundleForClass:[self class]] pathForImageResource:@"MMSierraTabEdited"]];
    }

    NSView *tabButtonView = controlView.superview;
    if (![tabButtonView isKindOfClass:[NSButton class]]) return;
    MMTabBarButton *tabButton = (MMTabBarButton *)tabButtonView;

    NSImage *customImage = nil;
    NSRect customFrame = NSMakeRect(4.0f, 4.0f, 8.0f, 8.0f);
    if (tabButton.isEdited) {
        customImage = editedImage;
    } else {
        customImage = closeImage;
    }

    CGFloat opacity = 1.0f;
    if (controlView.window.isKeyWindow || controlView.window.isMainWindow) {
        if (self.isHighlighted) {
            opacity = 0.470f;
        } else if (self.mouseHovered) {
            opacity = 0.475f;
        } else {
            opacity = 0.45f;
        }
    } else {
        if (self.mouseHovered) {
            opacity = 0.400f;
        } else {
            opacity = 0.350f;
        }
    }

    [customImage drawInRect:customFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:opacity respectFlipped:YES hints:nil];
}

- (NSRect)topBorderRectWithFrame:(NSRect)frame {
    return NSMakeRect(frame.origin.x, 0, frame.size.width, 1.0f);
}

- (NSRect)leftBorderRectWithFrame:(NSRect)frame {
    return NSMakeRect(frame.origin.x, 0, 1.0f, frame.size.height - 1.0f);
}

- (NSRect)fillRectWithFrame:(NSRect)frame {
    return NSMakeRect(frame.origin.x + 1, frame.origin.y + 1, frame.size.width - 1.0f, frame.size.height - 2.0f);
}

- (void)drawActiveBezelWithFrame:(NSRect)frame inView:(NSView *)controlView {
    NSGradient *fillGradient = nil;

    NSView *tabButtonView = controlView.superview;
    if (![tabButtonView isKindOfClass:[NSButton class]]) return;
    NSButton *tabButton = (NSButton *)tabButtonView;

    if (tabButton.state == NSOnState) {
        if (self.isHighlighted) {
            fillGradient = [MMSierraCloseButtonCell selectedMouseDownFillGradient];
        } else {
            fillGradient = [MMSierraCloseButtonCell selectedHoverFillGradient];
        }
    } else {
        if (self.isHighlighted) {
            fillGradient = [MMSierraCloseButtonCell unselectedMouseDownFillGradient];
        } else {
            fillGradient = [MMSierraCloseButtonCell unselectedHoverFillGradient];
        }
    }

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame radius:2.0f capMask:MMBezierShapeAllCaps];
    [fillGradient drawInBezierPath:path angle:90.0f];
}

- (void)drawInactiveBezelWithFrame:(NSRect)frame inView:(NSView *)controlView {
    if (self.isHighlighted) {
        [[MMSierraCloseButtonCell inactiveSelectedFillColor] set];
    } else {
        [[MMSierraCloseButtonCell inactiveUnselectedFillColor] set];
    }

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame radius:2.0f capMask:MMBezierShapeAllCaps];
    [path fill];
}

- (void)drawBezelWithFrame:(NSRect)frame inView:(NSView *)controlView {
    // no bezel if not hovering
    if (!self.mouseHovered) return;

    if (controlView.window.isKeyWindow || controlView.window.isMainWindow) {
        [self drawActiveBezelWithFrame:frame inView:controlView];
    } else {
        [self drawInactiveBezelWithFrame:frame inView:controlView];
    }
}

#pragma mark - fill gradients

+ (NSGradient *)selectedHoverFillGradient {
    static NSGradient *gradient = nil;
    if (!gradient) {
        gradient = [[NSGradient alloc] initWithColors:
                    @[
                      [NSColor colorWithCalibratedWhite:0.718 alpha:1.0],
                      [NSColor colorWithCalibratedWhite:0.702 alpha:1.0]
                      ]];
    }
    return gradient;
}

+ (NSGradient *)selectedMouseDownFillGradient {
    static NSGradient *gradient = nil;
    if (!gradient) {
        gradient = [[NSGradient alloc] initWithColors:
                    @[
                      [NSColor colorWithCalibratedWhite:0.667 alpha:1.0],
                      [NSColor colorWithCalibratedWhite:0.651 alpha:1.0]
                      ]];
    }
    return gradient;
}

+ (NSGradient *)unselectedHoverFillGradient {
    static NSGradient *gradient = nil;
    if (!gradient) {
        gradient = [[NSGradient alloc] initWithColors:
                    @[
                      [NSColor colorWithCalibratedWhite:0.584 alpha:1.0],
                      [NSColor colorWithCalibratedWhite:0.569 alpha:1.0]
                      ]];
    }
    return gradient;
}

+ (NSGradient *)unselectedMouseDownFillGradient {
    static NSGradient *gradient = nil;
    if (!gradient) {
        gradient = [[NSGradient alloc] initWithColors:
                    @[
                      [NSColor colorWithCalibratedWhite:0.541 alpha:1.0],
                      [NSColor colorWithCalibratedWhite:0.525 alpha:1.0]
                      ]];
    }
    return gradient;
}

#pragma mark - inactive windows

+ (NSColor *)inactiveSelectedFillColor {
    static NSColor *color = nil;
    if (!color) {
        color = [NSColor colorWithCalibratedWhite:0.871 alpha:1.0];
    }
    return color;
}

+ (NSColor *)inactiveUnselectedFillColor {
    static NSColor *color = nil;
    if (!color) {
        color = [NSColor colorWithCalibratedWhite:0.792 alpha:1.0];
    }
    return color;
}

@end

redpajama_set_name: RedPajamaGithub


text:
control "static_file" do
  describe "static_file.txt" do
    subject do
      file(::File.join(attribute("output_root_module_directory"), "static_file.txt"))
    end

    its("content") { should eq "abc" }
  end
end


text:
<?php

namespace ZendTest\Mvc\Controller\TestAsset;

use Zend\Mvc\Controller\AbstractActionController;

class ControllerWithTypeHintedConstructorParameter extends AbstractActionController
{
    public $sample;

    public function __construct(SampleInterface $sample)
    {
        $this->sample = $sample;
    }
}


text:
package org.web3j.abi.datatypes.generated;

import java.math.BigInteger;

import org.web3j.abi.datatypes.Fixed;

/**
 *
Auto generated code.

 * Do not modifiy!

 * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.

 */
public class Fixed112x64 extends Fixed {
    public static final Fixed112x64 DEFAULT = new Fixed112x64(BigInteger.ZERO);

    public Fixed112x64(BigInteger value) {
        super(112, 64, value);
    }

    public Fixed112x64(int mBitSize, int nBitSize, BigInteger m, BigInteger n) {
        super(112, 64, m, n);
    }
}


text:
"""
wpython.py
==========
                                    __   __
              .--.--.--.-----.--.--|  |_|  |--.-----.-----.
              |  |  |  |  _  |  |  |   _|     |  _  |     |
              |________|   __|___  |____|__|__|_____|__|__|
                       |__|  |_____|

With wpython you can launch scripts residing in virtual environments
without the need of activating the venv.

When you want to execute a script in a venv, what do you usually do?
Activate the venv, execute the script, deactivate the venv. But what if
you want to call a venv'ed script in batch mode from another script?

Each venv has its own Python interpreter. When you execute a script in the
venv, this Python interpreter is used to run the script. If you don't
want to activate the venv, then you need to provide the path of this
Python interpreter. Example:

    /path/to/venv/bin/python /path/to/script.py

wpython reduces it to:

    wpython /path/to/script.py

wpython figures out the path of the Python interpreter in the venv
and passes /path/to/script.py to this local interpreter.

Requirements
------------
wpython relies on the excellent unipath library, which provides a sane
way to work with files and directories.
It comes bundled with wpython or you can install it system-wide.

Tested with
-----------
It was tested under Linux with Python 2 and Python 3.

Usage
-----
1) Put wpython.py somewhere in your PATH.
   Tip: I put two symbolic links on it: wpython and wpy.

2) In the root of your venv'ed project directory create a file called ".venv".
   The content of this file should be the path of the directory
   where the virtual env. is created by the commands virtualenv or
   virtualenvwrapper.
   This path can be either absolute or relative.
   You can also rename ".venv", see the VENV_FILE constant in the source below.

virtualenvwrapper example
-------------------------
Say we have our project directory here: `/home/jabba/python/wpython_demo`.
In this folder launch this command:

    mkvirtualenv wpython_demo

It creates the virtual environment here: `/home/jabba/.virtualenvs/wpython_demo.`
Then create the file `/home/jabba/python/wpython_demo/.venv` with this content:

    /home/jabba/.virtualenvs/wpython_demo

Say you have a `demo.py` file in this wpython_demo project. Launch it like this:

    $ cd /home/jabba/python/wpython_demo
    $ wpython demo.py

Notice that we didn't have to activate the virtual environment.

virtualenv example
------------------
Say you put your virtual environment in the root of the project folder
under a subdirectory called "venv". In this case the content of the ".venv"
file can be a relative path:

    $ cat .venv
    venv

You launch a script the same way as explained for virtualenvwrapper.

Extra feature
-------------
With wpython you can also launch scripts that are not in the project's
root folder but deep in a subfolder. You still need just one ".venv" file
in the project's root. If wpython doesn't find the file `.venv` in the folder
of the script to be launched, it will start stepping back to the parent
folders. It will use the first `.venv` file it finds.

Author:
-------
Laszlo Szathmary, alias Jabba Laci, 2014 (jabba.laci@gmail.com)
https://github.com/jabbalaci

ASCII logo made with http://patorjk.com/software/taag
"""

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

import shlex
import sys
from subprocess import call

from unipath import Path

VENV_FILE = '.venv'  # rename it if you want
DEBUG = True         # you can also switch debug mode off with the -s option

def my_call(python_path, prg, args):
    """
    Pass the script and its arguments to the Python interpreter in the venv.
    """
    cmd = "{pp} {prg} {args}".format(pp=python_path,
                                     prg=prg,
                                     args=' '.join(args))
    args = shlex.split(cmd)
    call(args)

def find_venv_file(folder):
    """
    Find the .venv file. If necessary, go up to the parent folders.
    """
    venv_file = Path(folder, VENV_FILE)
    while not (venv_file.isfile() or folder == "/"):
        folder = folder.parent
        venv_file = Path(folder, VENV_FILE)
    #
    if venv_file.isfile():
        if DEBUG:
            print("# venv file: {f}".format(f=venv_file), file=sys.stderr)
        return venv_file
    # else
    print("Error: {f} file is missing.".format(f=VENV_FILE), file=sys.stderr)
    sys.exit(1)

def print_usage(help=False):
    print("Usage: wpython  script_in_virtualenvwrapper.py  [arg]...")
    if help:
        print("""
Options:
    -h, --help:        this help
    -s:                silent mode (no debug info)
        """.strip())

def check_args(args):
    """
    Process options passed to wpython.
    """
    global DEBUG

    if args[0] in ("-h", "--help"):
        print_usage(help=True)
        sys.exit(0)

    if args[0] == "-s":
        # silent mode, no debug info
        DEBUG = False
        args = args[1:]

    # Treat all options above. This part below is for the unknown options:
    if len(args) == 0:
        print_usage()
        sys.exit(1)

    if args[0].startswith("-"):
        print("Error: unknown option: {o}".format(o=args[0]), file=sys.stderr)
        sys.exit(1)

    return args

def main():
    """
    Controller.
    """
    args = sys.argv[1:]
    if len(args) == 0:
        print_usage()
        sys.exit(0)

    args = check_args(args)

    prg = args[0]    # script in venv
    args = args[1:]  # arguments of the script in venv

    p = Path(prg).absolute()
    venv_file = find_venv_file(p.parent)

    venv_dir = Path(venv_file.read_file().strip())
    # .venv can also contain a relative path
    if not venv_dir.isabsolute():
        venv_dir = Path(venv_file.parent, venv_dir).norm()

    if not venv_dir.isdir():
        print("Error: {vd} is not a directory.".format(vd=venv_dir),
              file=sys.stderr)
        sys.exit(1)
    #
    python_path = Path(venv_dir, "bin/python")
    if not python_path.isfile():
        print("Error: {pp} is missing.".format(pp=python_path),
              file=sys.stderr)
        sys.exit(1)

    if DEBUG:
        print("# venv dir:  {d}".format(d=venv_dir), file=sys.stderr)

    my_call(python_path, prg, args)

##############################################################################

if __name__ == "__main__":
    main()


text:
package io.fabric8.webui.jclouds

import org.codehaus.jackson.annotate.JsonProperty
import io.fabric8.webui.{Services, BaseResource}

/**
 *
 */
class ComputeProviderResource(_id: String, provider_or_metadata: String) extends BaseResource {

  @JsonProperty
  def id = _id

  @JsonProperty
  def name = {
    _type match {
      case "provider" => Services.compute_providers.find(_.getId.equals(id)).get.getName()
      case "api" => Services.compute_apis.find(_.getId.equals(id)).get.getName()
      case _ => ""
    }
  }

  @JsonProperty
  def _type = provider_or_metadata

}


text:
<?php

namespace Roeder\Pagarme\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class UpgradeData implements UpgradeDataInterface
{

    /**
     * {@inheritdoc}
     */
    public function upgrade(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();
        if (version_compare($context->getVersion(), "1.0.0", "<")) {
        //upgrade script
        }
        $setup->endSetup();
    }
}


text:
.. _shard:

Shards
============

The Nationstates package has multiple ways to represent shards, Strings and the :class:`Shard` Object.

Using Strings
-------------

Strings can be used to represent simpler shards.

    >>> import nationstates as ns
    >>> api = ns.Nationstates(UniqueAndDescriptiveUserAgent)
    >>> r = api.world().get_shards("numnations")

Shard Object
------------

The :class:`Shard` Object was built to allow more complicated shards. They allow you to attach parameters to the shard as well as just plainly representing a shard. It is recommended for more dynamic/advanced usage of the module.

    >>> import nationstates as ns
    >>> api = ns.Nationstates(UniqueAndDescriptiveUserAgent)
    >>> happenings = ns.Shard("happenings", view="region.the_pacific", filter="founding")
    >>> r = api.world().get_shards(happenings)


text:
require "spec_helper"

module WordpressClient
  describe Connection do
    subject(:connection) {
      Connection.new(url: "http://example.com/", username: "jane", password: "doe")
    }

    let(:base_url) { "http://example.com/wp/v2" }
    let(:model) { class_double(Post, parse: model_instance) }
    let(:model_instance) { instance_double(Post) }

    it "is constructed with a url, username and a password" do
      connection = Connection.new(url: "http://example.com/wp-json", username: "x", password: "x")
      expect(connection.url).to eq('http://example.com/wp-json')
    end

    it "does not show password when inspected" do
      connection = Connection.new(url: "/", username: "x", password: "secret")
      expect(connection.to_s).to_not include "secret"
      expect(connection.inspect).to_not include "secret"
    end

    describe "get" do
      it "can get a single model" do
        stub_get("#{base_url}/foo?some_param=12", returns: {title: "Foo"})
        expect(model).to receive(:parse).with("title" => "Foo").and_return(model_instance)
        expect(connection.get(model, "foo", some_param: 12)).to eq model_instance
      end

      it "can get several models" do
        stub_get("#{base_url}/foos?some_param=12&page=1&per_page=1", returns: ["result"], total: 1)

        expect(model).to receive(:parse).with("result").and_return(model_instance)

        expect(
          connection.get_multiple(model, "foos", some_param: 12, page: 1, per_page: 1).to_a
        ).to eq [model_instance]
      end

      it "paginates the result when fetching multiple models" do
        stub_get("#{base_url}/foos?page=4&per_page=15", returns: ["result"], total: 62)
        collection = connection.get_multiple(model, "foos", page: 4, per_page: 15)

        expect(collection).to be_instance_of(PaginatedCollection)
        expect(collection.total).to eq 62
        expect(collection.current_page).to eq 4
        expect(collection.per_page).to eq 15
      end

      it "raises WordpressClient::TimeoutError when requests time out" do
        stub_request(:get, /./).to_timeout
        expect { connection.get(model, "foo") }.to raise_error(TimeoutError)
        expect { connection.get_multiple(model, "foo") }.to raise_error(TimeoutError)
      end

      it "raises ServerError if response is invalid JSON" do
        stub_get(/./, body: "[")
        expect { connection.get(model, "foo") }.to raise_error(ServerError, /parse/)
        expect { connection.get_multiple(model, "foo") }.to raise_error(ServerError, /parse/)
      end

      it "raises ServerError if response is not application/json" do
        stub_get(/./, content_type: "text/plain")
        expect { connection.get(model, "foo") }.to raise_error(ServerError, /plain/)
        expect { connection.get_multiple(model, "foo") }.to raise_error(ServerError, /plain/)
      end

      it "raises NotFoundError if response is 404" do
        stub_get(/./, status: 404)
        expect { connection.get(model, "foo") }.to raise_error(NotFoundError)
        expect { connection.get_multiple(model, "foo") }.to raise_error(NotFoundError)
      end
    end

    describe "creating" do
      it "can create models" do
        stub_successful_post_with_redirect(
          "#{base_url}/foos", {title: "Bar"}, redirects_to: "#{base_url}/foos/1"
        )
        stub_get("#{base_url}/foos/1", returns: {id: 1, title: "Bar"})

        expect(model).to receive(:parse).with(
          "id" => 1, "title" => "Bar"
        ).and_return(model_instance)

        response = connection.create(model, "foos", title: "Bar")
        expect(response).to eq model_instance
      end

      it "can ignore the response" do
        stub_successful_post_with_redirect(
          "#{base_url}/foos", {title: "Bar"}, redirects_to: "#{base_url}/foos/1"
        )

        response = connection.create_without_response("foos", title: "Bar")
        expect(response).to be true
      end

      it "can pass extra parameters when following redirect" do
        stub_successful_post_with_redirect(
          "#{base_url}/foos", {title: "Bar"}, redirects_to: "#{base_url}/foos/1"
        )
        redirect = stub_get("#{base_url}/foos/1?extra=param", returns: {})

        connection.create(model, "foos", {title: "Bar"}, redirect_params: {extra: "param"})
        expect(redirect).to have_been_made
      end

      it "raises NotFoundError if response is 400 with rest_post_invalid_id as error code" do
        stub_failing_post(/./, returns: json_fixture("invalid-post-id.json"), status: 400)

        expect { connection.create(model, "foo", {}) }.to raise_error(NotFoundError, /post id/i)
        expect { connection.create_without_response("foo", {}) }.to raise_error(NotFoundError)
      end

      it "raises ValidationError on any other 400 responses" do
        stub_failing_post(/./, returns: json_fixture("validation-error.json"), status: 400)

        expect {
          connection.create(model, "foo", {})
        }.to raise_error(ValidationError, /status is not one of/)

        expect {
          connection.create_without_response("foo", {})
        }.to raise_error(ValidationError, /status is not one of/)
      end
    end

    describe "patching" do
      it "can patch models" do
        stub_patch("#{base_url}/foos/1", {title: "Bar"}, returns: {id: 1, title: "Bar"})

        expect(model).to receive(:parse).with(
          "id" => 1, "title" => "Bar"
        ).and_return(model_instance)

        response = connection.put(model, "foos/1", title: "Bar")
        expect(response).to eq model_instance
      end

      it "can ignore responses" do
        stub_patch("#{base_url}/foos/1", {title: "Bar"}, returns: {id: 1, title: "Bar"})
        response = connection.put_without_response("foos/1", title: "Bar")
        expect(response).to be true
      end

      it "raises NotFoundError if response is 400 with rest_post_invalid_id as error code" do
        stub_patch(/./, {}, returns: json_fixture("invalid-post-id.json"), status: 400)
        expect { connection.put(model, "foo", {}) }.to raise_error(NotFoundError, /post id/i)
        expect { connection.put_without_response("foo", {}) }.to raise_error(NotFoundError)
      end

      it "raises ValidationError on any other 400 responses" do
        stub_patch(/./, {}, returns: json_fixture("validation-error.json"), status: 400)

        expect {
          connection.put(model, "foo", {})
        }.to raise_error(ValidationError, /status is not one of/)

        expect {
          connection.put_without_response("foo", {})
        }.to raise_error(ValidationError, /status is not one of/)
      end
    end

    describe "deleting" do
      it "can delete paths" do
        encoding = "".encoding

        stub_request(:delete, "#{base_url}/foos/1").with(
          headers: {"content-type" => "application/json; charset=#{encoding}"},
          body: {"force" => true}.to_json,
        ).to_return(
          headers: {"content-type" => "application/json; charset=utf-8"},
          body: {status: "Heyhoo! Nice one!"}.to_json,
        )

        response = connection.delete("foos/1", force: true)
        expect(response).to be true
      end

      it "raises ValidationError on 400 responses" do
        stub_request(:delete, /./).to_return(
          status: 400,
          body: "{}",
          headers: {"content-type" => "application/json; charset=utf-8"},
        )

        expect {
          connection.delete("foo", {})
        }.to raise_error(ValidationError)
      end
    end

    describe "uploading" do
      it "posts the given IO and returns the resulting model" do
        stub_request(:post, "#{base_url}/files").with(
          headers: {
            "content-length" => "11",
            "content-type" => "text/plain",
            "content-disposition" => 'attachment; filename="foo.txt"',
          },
          body: "hello world",
        ).to_return(
          status: 201, # Created
          headers: {"Location" => "#{base_url}/files/67"}
        )
        stub_get("#{base_url}/files/67", returns: {id: 67})

        model_instance = double("some model instance")
        model = double("some model")

        expect(model).to receive(:parse).with("id" => 67).and_return model_instance

        result = connection.upload(
          model, "files", StringIO.new("hello world"), mime_type: "text/plain", filename: "foo.txt"
        )

        expect(result).to eq model_instance
      end
    end

    def stub_get(
      path,
      returns: {},
      status: 200,
      body: returns.to_json,
      total: nil,
      content_type: "application/json"
    )
      headers = {"content-type" => "#{content_type}; charset=utf-8"}
      headers["X-WP-Total"] = total.to_s if total

      stub_request(:get, path).with(basic_auth: ['jane', 'doe']).to_return(status: status, body: body, headers: headers)
    end

    def stub_successful_post_with_redirect(path, data, redirects_to:)
      stub_request(:post, path).with(
        basic_auth: ['jane', 'doe'],
        headers: {"content-type" => "application/json; charset=#{"".encoding}"},
        body: data.to_json,
      ).to_return(
        status: 201, # Created
        headers: {"Location" => redirects_to}
      )
    end

    def stub_failing_post(path, returns:, status:)
      stub_request(:post, path).with(
        basic_auth: ['jane', 'doe']
      ).to_return(
        status: status,
        body: returns.to_json,
        headers: {"content-type" => "application/json; charset=utf-8"},
      )
    end

    def stub_patch(path, data, returns:, status: 200)
      stub_request(:put, path).with(
        basic_auth: ['jane', 'doe'],
        headers: {"content-type" => "application/json; charset=#{"".encoding}"},
        body: data.to_json,
      ).to_return(
        status: status,
        headers: {"content-type" => "application/json; charset=utf-8"},
        body: returns.to_json,
      )
    end
  end
end


text:
A thread-safe Minecraft server's RCON implementation for C# and Mono.

Example usage: Change the "ABC" player's game mode
```C#
  using System;
  using MinecraftServerRCON;

  namespace RCONTest
  {
	class Program
	{
		using(var rcon = RCONClient.INSTANCE)
		{
	    		rcon.setupStream("127.0.0.1", password: "123");
	    		answer = rcon.sendMessage(RCONMessageType.Command, "gamemode creative ABC");
	    		Console.WriteLine(answer.RemoveColorCodes());
		}
	}
  }
```

## Setup
The fasted way to use this library is to use NuGet: https://www.nuget.org/packages/RCONServer/. Further, you can also download the library from the [releases](https://github.com/SommerEngineering/MinecraftServerRCONSharp/releases) page.


text:
using System;
using System.Collections.Generic;
using System.Text;
using V3 = Neo4j.Driver.Internal.IO.MessageSerializers.V3;
using V4_1 =  Neo4j.Driver.Internal.IO.MessageSerializers.V4_1;

namespace Neo4j.Driver.Internal.Protocol
{
    class BoltProtocolV4_1MessageFormat : BoltProtocolV4_0MessageFormat
    {

        #region Message Constants

        #endregion

        internal BoltProtocolV4_1MessageFormat()
        {
            RemoveHandler<V3.HelloMessageSerializer>();
            AddHandler<V4_1.HelloMessageSerializer>();
        }
    }
}


text:
<?php

namespace WikiRenderer\Markup\Trac;

/**
 * Parse a line of a table.
 */
class TableRow extends \WikiRenderer\InlineTagWithSeparator
{
    protected $generatorName = 'tablecell';
    protected $isTextLineTag = true;
    protected $attribute = array('$$');
    protected $separators = array('||');

    /**
     * @var \WikiRenderer\Generator\InlineBagGenerator
     */
    protected $row;

    public function __construct(\WikiRenderer\Config $config, \WikiRenderer\Generator\DocumentGeneratorInterface $generator)
    {
        parent::__construct($config, $generator);
        $this->row = new \WikiRenderer\Generator\InlineBagGenerator($generator->getConfig());
    }

    protected $hasStartHeader = false;
    protected $hasEndHeader = false;
    protected $cell = array();

    public function addContentString($wikiContent)
    {
        if ($wikiContent === '') {
            return;
        }
        $this->hasEndHeader = false;
        $this->lastWord = null;

        $filteredWikiContent = $wikiContent;
        if ($this->wikiContentArr[$this->separatorCount] === ''
            && $wikiContent[0] == '=') {
            $this->hasStartHeader = true;

            if (substr($wikiContent, -1) == '=') {
                $this->hasEndHeader = true;
                $filteredWikiContent = substr($wikiContent, 1, -1);
            } else {
                $filteredWikiContent = substr($wikiContent, 1);
            }
        } elseif ($this->wikiContentArr[$this->separatorCount] !== ''
                 && substr($wikiContent, -1) == '=') {
            $this->hasEndHeader = true;
            $filteredWikiContent = substr($wikiContent, 0, -1);
        }

        $this->wikiContentArr[$this->separatorCount] .= $wikiContent;
        $this->cell[] = $this->convertWords($filteredWikiContent);
    }

    public function addContentGenerator($wikiContent, \WikiRenderer\Generator\InlineGeneratorInterface $childGenerator)
    {
        if ($wikiContent === '') {
            return;
        }
        $this->hasEndHeader = false;
        $this->lastWord = null;

        $this->wikiContentArr[$this->separatorCount] .= $wikiContent;
        $this->cell[] = $childGenerator;
    }

    /**
     * called by the inline parser, when it found a separator.
     * @param string $token
     */
    public function addSeparator($token)
    {
        $this->wikiContent .= $this->wikiContentArr[$this->separatorCount];

        if (count($this->cell) === 0) {
            $this->generator->setColSpan($this->generator->getColSpan() + 1);
        } else {
            if ($this->hasStartHeader && $this->hasEndHeader) {
                $this->generator->setIsHeader(true);
            } elseif ($this->hasStartHeader) {
                // no header, we revert the '=' removal
                $words = $this->documentGenerator->getInlineGenerator('words');
                $words->addRawContent('=');
                array_unshift($this->cell, $words);
            } elseif ($this->hasEndHeader) {
                // no header, we revert the '=' removal
                $words = $this->documentGenerator->getInlineGenerator('words');
                $words->addRawContent('=');
                array_push($this->cell, $words);
            }

            foreach ($this->cell as $gen) {
                $this->generator->addContent($gen);
            }
            $this->row->addGenerator($this->generator);
            $this->generator = $this->documentGenerator->getInlineGenerator($this->generatorName);
            ++$this->separatorCount;
            $this->contents[$this->separatorCount] = '';
            $this->wikiContentArr[$this->separatorCount] = '';
        }
        $this->hasStartHeader = $this->hasEndHeader = false;
        $this->cell = array();
        $this->currentSeparator = $token;
        $this->wikiContent .= $token;
    }

    public function getContent()
    {
        // don't add the "pseudo" cell which is after the last separator
        if (!$this->generator->isEmpty()) {
            $this->row->addGenerator($this->generator);
        }

        return $this->row;
    }

    public function isOtherTagAllowed()
    {
        return true;
    }

    public function __clone()
    {
        $this->generator = clone $this->generator;
        $this->row = clone $this->row;
    }
}


text:
layout: post
status: publish
published: true
title: La famosa técnica del F8.
author:
  display_name: Litze
  login: Litze
  email: luis@becodemyfriend.com
  url: http://www.twitter.com/luislitze
author_login: Litze
author_email: luis@becodemyfriend.com
author_url: http://www.twitter.com/luislitze
wordpress_id: 341
wordpress_url: http://www.becodemyfriend.com/?p=341
date: '2010-11-24 16:18:09 +0000'
date_gmt: '2010-11-24 15:18:09 +0000'
categories:
- Empresa
tags:
- Agilismo
- Marketing
---

"Hay que romper el hielo..."

Es lo primero que todos pensamos cuando subimos a hablar en público.

La técnica del F8 facilita esta labor. Y tú también puedes hacerla si sigues estos breves consejos:

1. Ten tu exposición lo suficientemente preparada como para no hacer el ridículo.

2. Levántate cuando sea tu turno y dirígete con paso firme hacia la tarima.

3. Mantén siempre un semblante serio y confiado.

4. Deja que todos se abrumen con tu elevada presencia.

5. Ahora simplemente ejecuta un acto que demuestre una torpeza e inseguridad extremas. A continuación algunos ejemplos:

· Simula que no sabes preparar el ordenador para la presentación.

· Exhibe a través del proyector una imagen graciosa o ridícula.

· Deja caer con disimulo todos los papeles de tu carpeta, maldice en todos los idiomas que conozcas y tómate tu tiempo en recogerlos del suelo.

· Simula que el micrófono te da calambres al acercártelo.

6. La audiencia desconectará de lo que realmente les ha llevado allí y tendrán un par de minutos de pausa.

7. Seguidamente estarán inexplicablemente más receptivos.

8. Haz tu exposición!  Intenta que sea mejor que las mías. Sino, estás perdido =)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of aux in UD_English-PUD</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_English-PUD: Relations: aux

This relation is universal.
There are 1 language-specific subtypes of aux: <tt>aux:pass</tt>.

410 nodes (2%) are attached to their parents as aux.

409 instances of aux (100%) are right-to-left (child precedes parent).
Average distance between parent and child is 1.66585365853659.

The following 7 pairs of parts of speech are connected with aux: <tt>VERB</tt>-<tt>AUX</tt> (371; 90% instances), <tt>ADJ</tt>-<tt>AUX</tt> (19; 5% instances), <tt>NOUN</tt>-<tt>AUX</tt> (13; 3% instances), <tt>AUX</tt>-<tt>AUX</tt> (4; 1% instances), <tt>ADV</tt>-<tt>AUX</tt> (1; 0% instances), <tt>PRON</tt>-<tt>AUX</tt> (1; 0% instances), <tt>PROPN</tt>-<tt>AUX</tt> (1; 0% instances).

# visual-style 3	bgColor:blue
# visual-style 3	fgColor:white
# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 4 3 aux	color:blue
1	"	"	PUNCT	``	_	4	punct	4:punct	SpaceAfter=No
2	I	I	PRON	PRP	Case=Nom|Number=Sing|Person=1|PronType=Prs	4	nsubj	4:nsubj	SpaceAfter=No
3	'm	be	AUX	VBP	Mood=Ind|Tense=Pres|VerbForm=Fin	4	aux	4:aux	_
4	going	go	VERB	VBG	Tense=Pres|VerbForm=Part	0	root	0:root	_
5	to	to	ADP	IN	_	6	case	6:case	_
6	jail	jail	NOUN	NN	Number=Sing	4	obl	4:obl:to	_
7	either	either	DET	DT	_	8	det	8:det	_
8	way	way	NOUN	NN	Number=Sing	4	obl:npmod	4:obl:npmod	SpaceAfter=No
9	,	,	PUNCT	,	_	4	punct	4:punct	_
10	hope	hope	VERB	VBP	Mood=Ind|Tense=Pres|VerbForm=Fin	4	parataxis	4:parataxis	_
11	it	it	PRON	PRP	Case=Nom|Gender=Neut|Number=Sing|Person=3|PronType=Prs	13	nsubj	13:nsubj	_
12	was	be	AUX	VBD	Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin	13	cop	13:cop	_
13	worth	worth	ADJ	JJ	Degree=Pos	10	ccomp	10:ccomp	_
14	it	it	PRON	PRP	Case=Acc|Gender=Neut|Number=Sing|Person=3|PronType=Prs	13	obj	13:obj	SpaceAfter=No
15	.	.	PUNCT	.	_	4	punct	4:punct	SpaceAfter=No
16	"	"	PUNCT	''	_	4	punct	4:punct	_

# visual-style 7	bgColor:blue
# visual-style 7	fgColor:white
# visual-style 9	bgColor:blue
# visual-style 9	fgColor:white
# visual-style 9 7 aux	color:blue
1	Not	not	ADV	RB	Polarity=Neg	2	advmod	2:advmod	_
2	all	all	DET	DT	_	3	det	3:det	_
3	transformations	transformation	NOUN	NNS	Number=Plur	9	nsubj	9:nsubj	_
4	in	in	ADP	IN	_	6	case	6:case	_
5	the	the	DET	DT	Definite=Def|PronType=Art	6	det	6:det	_
6	region	region	NOUN	NN	Number=Sing	3	nmod	3:nmod:in	_
7	have	have	AUX	VBP	Mood=Ind|Tense=Pres|VerbForm=Fin	9	aux	9:aux	_
8	been	be	AUX	VBN	Tense=Past|VerbForm=Part	9	cop	9:cop	_
9	successful	successful	ADJ	JJ	Degree=Pos	0	root	0:root	SpaceAfter=No
10	.	.	PUNCT	.	_	9	punct	9:punct	_

# visual-style 4	bgColor:blue
# visual-style 4	fgColor:white
# visual-style 8	bgColor:blue
# visual-style 8	fgColor:white
# visual-style 8 4 aux	color:blue
1	Today	today	NOUN	NN	Number=Sing	8	obl:tmod	8:obl:tmod	SpaceAfter=No
2	,	,	PUNCT	,	_	8	punct	8:punct	_
3	Khanzir	Khanzir	PROPN	NNP	Number=Sing	8	nsubj	8:nsubj	_
4	may	may	AUX	MD	VerbForm=Fin	8	aux	8:aux	_
5	be	be	AUX	VB	VerbForm=Inf	8	cop	8:cop	_
6	a	a	DET	DT	Definite=Ind|PronType=Art	8	det	8:det	_
7	lonely	lonely	ADJ	JJ	Degree=Pos	8	amod	8:amod	_
8	pig	pig	NOUN	NN	Number=Sing	0	root	0:root	SpaceAfter=No
9	,	,	PUNCT	,	_	8	punct	8:punct	_
10	but	but	CCONJ	CC	_	15	cc	15:cc	_
11	he	he	PRON	PRP	Case=Nom|Gender=Masc|Number=Sing|Person=3|PronType=Prs	15	nsubj	15:nsubj	_
12	is	be	AUX	VBZ	Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin	15	cop	15:cop	SpaceAfter=No
13	n't	n't	ADV	RB	Polarity=Neg	15	advmod	15:advmod	_
14	always	always	ADV	RB	_	15	advmod	15:advmod	_
15	alone	alone	ADJ	JJ	Degree=Pos	8	conj	8:conj:but	SpaceAfter=No
16	.	.	PUNCT	.	_	8	punct	8:punct	_

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
#define NETCORE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Foundatio.Force.DeepCloner.Helpers
{
	internal static class DeepClonerExprGenerator
	{
		internal static object GenerateClonerInternal(Type realType, bool asObject)
		{
			return GenerateProcessMethod(realType, asObject && realType.IsValueType());
		}

		// slow, but hardcore method to set readonly field
		internal static void ForceSetField(FieldInfo field, object obj, object value)
		{
			var fieldInfo = field.GetType().GetPrivateField("m_fieldAttributes");

			// TODO: think about it
			// nothing to do :( we should a throw an exception, but it is no good for user
			if (fieldInfo == null)
				return;
			var ov = fieldInfo.GetValue(field);
			if (!(ov is FieldAttributes))
				return;
			var v = (FieldAttributes)ov;

			fieldInfo.SetValue(field, v & ~FieldAttributes.InitOnly);
			field.SetValue(obj, value);
			fieldInfo.SetValue(field, v);
		}

		private static object GenerateProcessMethod(Type type, bool unboxStruct)
		{
			if (type.IsArray)
			{
				return GenerateProcessArrayMethod(type);
			}

			if (type.FullName != null && type.FullName.StartsWith("System.Tuple`"))
			{
				// if not safe type it is no guarantee that some type will contain reference to
				// this tuple. In usual way, we're creating new object, setting reference for it
				// and filling data. For tuple, we will fill data before creating object
				// (in constructor arguments)
				var genericArguments = type.GenericArguments();
				// current tuples contain only 8 arguments, but may be in future...
				// we'll write code that works with it
				if (genericArguments.Length < 10 && genericArguments.All(DeepClonerSafeTypes.CanReturnSameObject))
				{
					return GenerateProcessTupleMethod(type);
				}
			}

			var methodType = unboxStruct || type.IsClass() ? typeof(object) : type;

			var expressionList = new List<Expression>();

			ParameterExpression from = Expression.Parameter(methodType);
			var fromLocal = from;
			var toLocal = Expression.Variable(type);
			var state = Expression.Parameter(typeof(DeepCloneState));

			if (!type.IsValueType())
			{
				var methodInfo = typeof(object).GetPrivateMethod("MemberwiseClone");

				// to = (T)from.MemberwiseClone()
				expressionList.Add(Expression.Assign(toLocal, Expression.Convert(Expression.Call(from, methodInfo), type)));

				fromLocal = Expression.Variable(type);
				// fromLocal = (T)from
				expressionList.Add(Expression.Assign(fromLocal, Expression.Convert(from, type)));

				// added from -> to binding to ensure reference loop handling
				// structs cannot loop here
				// state.AddKnownRef(from, to)
				expressionList.Add(Expression.Call(state, typeof(DeepCloneState).GetMethod("AddKnownRef"), from, toLocal));
			}
			else
			{
				if (unboxStruct)
				{
					// toLocal = (T)from;
					expressionList.Add(Expression.Assign(toLocal, Expression.Unbox(from, type)));
					fromLocal = Expression.Variable(type);
					// fromLocal = toLocal; // structs, it is ok to copy
					expressionList.Add(Expression.Assign(fromLocal, toLocal));
				}
				else
				{
					// toLocal = from
					expressionList.Add(Expression.Assign(toLocal, from));
				}
			}

			List<FieldInfo> fi = new List<FieldInfo>();
			var tp = type;
			do
			{
#if !NETCORE
				// don't do anything with this dark magic!
				if (tp == typeof(ContextBoundObject)) break;
#else
				if (tp.Name == "ContextBoundObject") break;
#endif

				fi.AddRange(tp.GetDeclaredFields());
				tp = tp.BaseType();
			}
			while (tp != null);

			foreach (var fieldInfo in fi)
			{
				if (!DeepClonerSafeTypes.CanReturnSameObject(fieldInfo.FieldType))
				{
					var methodInfo = fieldInfo.FieldType.IsValueType()
										? typeof(DeepClonerGenerator).GetPrivateStaticMethod("CloneStructInternal")
																	.MakeGenericMethod(fieldInfo.FieldType)
										: typeof(DeepClonerGenerator).GetPrivateStaticMethod("CloneClassInternal");

					var get = Expression.Field(fromLocal, fieldInfo);

					// toLocal.Field = Clone...Internal(fromLocal.Field)
					var call = (Expression)Expression.Call(methodInfo, get, state);
					if (!fieldInfo.FieldType.IsValueType())
						call = Expression.Convert(call, fieldInfo.FieldType);

					// should handle specially
					// todo: think about optimization, but it rare case
					if (fieldInfo.IsInitOnly)
					{
						// var setMethod = fieldInfo.GetType().GetMethod("SetValue", new[] { typeof(object), typeof(object) });
						// expressionList.Add(Expression.Call(Expression.Constant(fieldInfo), setMethod, toLocal, call));
						var setMethod = typeof(DeepClonerExprGenerator).GetPrivateStaticMethod("ForceSetField");
						expressionList.Add(Expression.Call(setMethod, Expression.Constant(fieldInfo), Expression.Convert(toLocal, typeof(object)), Expression.Convert(call, typeof(object))));
					}
					else
					{
						expressionList.Add(Expression.Assign(Expression.Field(toLocal, fieldInfo), call));
					}
				}
			}

			expressionList.Add(Expression.Convert(toLocal, methodType));

			var funcType = typeof(Func<,,>).MakeGenericType(methodType, typeof(DeepCloneState), methodType);

			var blockParams = new List<ParameterExpression>();
			if (from != fromLocal) blockParams.Add(fromLocal);
			blockParams.Add(toLocal);

			return Expression.Lambda(funcType, Expression.Block(blockParams, expressionList), from, state).Compile();
		}

		private static object GenerateProcessArrayMethod(Type type)
		{
			var elementType = type.GetElementType();
			var rank = type.GetArrayRank();

			MethodInfo methodInfo;

			// multidim or not zero-based arrays
			if (rank != 1 || type != elementType.MakeArrayType())
			{
				if (rank == 2 && type == elementType.MakeArrayType())
				{
					// small optimization for 2 dim arrays
					methodInfo = typeof(DeepClonerGenerator).GetPrivateStaticMethod("Clone2DimArrayInternal").MakeGenericMethod(elementType);
				}
				else
				{
					methodInfo = typeof(DeepClonerGenerator).GetPrivateStaticMethod("CloneAbstractArrayInternal");
				}
			}
			else
			{
				var methodName = "Clone1DimArrayClassInternal";
				if (DeepClonerSafeTypes.CanReturnSameObject(elementType)) methodName = "Clone1DimArraySafeInternal";
				else if (elementType.IsValueType()) methodName = "Clone1DimArrayStructInternal";
				methodInfo = typeof(DeepClonerGenerator).GetPrivateStaticMethod(methodName).MakeGenericMethod(elementType);
			}

			ParameterExpression from = Expression.Parameter(typeof(object));
			var state = Expression.Parameter(typeof(DeepCloneState));
			var call = Expression.Call(methodInfo, Expression.Convert(from, type), state);

			var funcType = typeof(Func<,,>).MakeGenericType(typeof(object), typeof(DeepCloneState), typeof(object));

			return Expression.Lambda(funcType, call, from, state).Compile();
		}

		private static object GenerateProcessTupleMethod(Type type)
		{
			ParameterExpression from = Expression.Parameter(typeof(object));
			var state = Expression.Parameter(typeof(DeepCloneState));

			var local = Expression.Variable(type);
			var assign = Expression.Assign(local, Expression.Convert(from, type));

			var funcType = typeof(Func<object, DeepCloneState, object>);

			var tupleLength = type.GenericArguments().Length;

			var constructor = Expression.Assign(local, Expression.New(type.GetPublicConstructors().First(x => x.GetParameters().Length == tupleLength),
				type.GetPublicProperties().OrderBy(x => x.Name)
					.Where(x => x.CanRead && x.Name.StartsWith("Item") && char.IsDigit(x.Name[4]))
					.Select(x => Expression.Property(local, x.Name))));

			return Expression.Lambda(funcType, Expression.Block(new[] { local },
				assign, constructor, Expression.Call(state, typeof(DeepCloneState).GetMethod("AddKnownRef"), from, local),
					from),
				from, state).Compile();
		}

	}
}


text:
package com.planet_ink.coffee_mud.Commands;

import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.AccountStats.Agent;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.AchievementLibrary.Achievement;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Achievements extends StdCommand
{
	private final String[]	access	= I(new String[] { "ACHIEVEMENTS" });

	@Override
	public String[] getAccessWords()
	{
		return access;
	}

	private enum ValidLists
	{
		WON, ALL, NOW
	}

	private enum ValidParms
	{
		ANNOUNCE, ALL, WON, NOW, PLAYER, ACCOUNT, CHARACTER
	}

	private Tattooable getTattooable(Agent agent, MOB mob)
	{
		switch(agent)
		{
		case PLAYER:
			return mob;
		case ACCOUNT:
			if(mob.playerStats()!=null)
				return mob.playerStats().getAccount();
			return null;
		}
		return null;
	}

	private AccountStats getStatter(Agent agent, MOB mob)
	{
		switch(agent)
		{
		case PLAYER:
			return mob.playerStats();
		case ACCOUNT:
			if(mob.playerStats()!=null)
				return mob.playerStats().getAccount();
			return null;
		}
		return null;
	}

	private List<Achievement> getLowestNumberedTattoos(final Agent agent, final Set<String> WonList)
	{
		List<Achievement> useList = new LinkedList<Achievement>();
		HashSet<String> ignoredStarters = new HashSet<String>();
		for(Enumeration<Achievement> a=CMLib.achievements().achievements(agent);a.hasMoreElements();)
		{
			final Achievement A=a.nextElement();
			final String tattooName = A.getTattoo();
			if(WonList.contains(A.getTattoo()))
				useList.add(A);
			else
			if((tattooName.length()>1)
			&& Character.isDigit(tattooName.charAt(tattooName.length()-1)))
			{
				int x=tattooName.length()-1;
				while((x>0) && Character.isDigit(tattooName.charAt(x)))
					x--;
				final String starter = tattooName.substring(0,x+1);
				if(!ignoredStarters.contains(starter))
				{
					ignoredStarters.add(starter);
					useList.add(A);
				}
			}
			else
				useList.add(A);
		}
		return useList;
	}

	@Override
	public boolean execute(final MOB mob, List<String> commands, int metaFlags) throws java.io.IOException
	{
		String rest = CMParms.combine(commands,1);
		final PlayerStats pStats = mob.playerStats();
		if (pStats == null)
		{
			mob.tell(L("You don't have any achievements."));
			return false;
		}

		if(CMLib.achievements().evaluateAchievements(mob))
		{
			CMLib.s_sleep(4000);
			// yes, I know, but if I call tick down, or some other
			// async method, I'll get a freaking prompt.
		}

		MOB whoM=mob;
		final List<String> parms = CMParms.parseSpaces(rest.toUpperCase(), true);
		if(parms.size()>0)
		{
			final String lastParm=CMStrings.capitalizeAndLower(parms.get(parms.size()-1));
			if(CMLib.players().playerExists(lastParm))
			{
				whoM=CMLib.players().getLoadPlayer(lastParm);
				parms.remove(parms.size()-1);
			}
			else
			{
				if(CMath.s_valueOf(ValidParms.class,lastParm.toUpperCase().trim()) == null)
				{
					mob.tell(L("There is no such player as '@x1'.",lastParm));
					return false;
				}
			}
		}
		List<AccountStats.Agent> agents = new LinkedList<AccountStats.Agent>();
		boolean announce=false;
		ValidLists list = ValidLists.WON;
		for(int p=parms.size()-1;p>=0;p--)
		{
			ValidParms V = (ValidParms)CMath.s_valueOf(ValidParms.class,parms.get(p).toUpperCase().trim());
			if(V!=null)
			{
				switch(V)
				{
				case ANNOUNCE:
					announce=true;
					break;
				case NOW:
				case WON:
				case ALL:
					list = ValidLists.valueOf(V.name());
					break;
				case CHARACTER:
				case PLAYER:
					if(!agents.contains(AccountStats.Agent.PLAYER))
						agents.add(AccountStats.Agent.PLAYER);
					break;
				case ACCOUNT:
					if(!agents.contains(AccountStats.Agent.ACCOUNT))
						agents.add(AccountStats.Agent.ACCOUNT);
					break;
				}
			}
		}
		if(agents.size()==0)
		{
			agents.add(AccountStats.Agent.ACCOUNT);
			agents.add(AccountStats.Agent.PLAYER);
		}

		String prefix = "";
		if(whoM != mob)
		{
			prefix=whoM.Name()+L("'s ");
		}

		Set<String> WonList = new HashSet<String>();
		for(Agent agent : agents)
		{
			final Tattooable T = getTattooable(agent, whoM);
			if(T!=null)
			{
				for(Enumeration<Achievement> a=CMLib.achievements().achievements(agent);a.hasMoreElements();)
				{
					final Achievement A=a.nextElement();
					if(T.findTattoo(A.getTattoo())!=null)
						WonList.add(A.getTattoo());
				}
			}
		}
		final String done=L("DONE!");

		switch(list)
		{
		case ALL:
			prefix += prefix=L("All ");
			break;
		case NOW:
			prefix += L("Progress in ");
			break;
		case WON:
			break;
		}

		StringBuilder finalResponse = new StringBuilder();
		for(Agent agent : agents)
		{
			AccountStats stat = getStatter(agent,whoM);
			if(stat != null)
			{
				List<String> AchievedList = new Vector<String>();
				switch(list)
				{
				case ALL:
				{
					final List<Achievement> useList = getLowestNumberedTattoos(agent,WonList);
					int padding=done.length()+1;
					for(Iterator<Achievement> a=useList.iterator();a.hasNext();)
					{
						final Achievement A=a.next();
						if(!WonList.contains(A.getTattoo()))
						{
							AchievementLibrary.Tracker T=stat.getAchievementTracker(A, whoM);
							final int score = (T==null) ? 0 : T.getCount(whoM);
							final int targetScore = A.getTargetCount();
							if(targetScore != Integer.MIN_VALUE)
							{
								final int len = (""+score+"/"+targetScore).length();
								if(len >= padding)
									padding = len+1;
							}
						}
					}
					for(Iterator<Achievement> a=useList.iterator();a.hasNext();)
					{
						final Achievement A=a.next();
						if(WonList.contains(A.getTattoo()))
							AchievedList.add(CMStrings.padRight("^H"+done+"^?", padding)+": "+A.getDisplayStr());
						else
						{
							AchievementLibrary.Tracker T=pStats.getAchievementTracker(A, whoM);
							int score = (T==null) ? 0 : T.getCount(whoM);
							int targetScore = A.getTargetCount();
							if(targetScore == Integer.MIN_VALUE)
								AchievedList.add(CMStrings.padRight("^w", padding)+"^?: "+A.getDisplayStr());
							else
								AchievedList.add(CMStrings.padRight("^w"+score+"/"+targetScore, padding)+"^?: "+A.getDisplayStr());
						}
					}
					break;
				}
				case NOW:
				{
					int padding=done.length()+1;
					final List<Achievement> useList = getLowestNumberedTattoos(agent,WonList);
					for(Iterator<Achievement> a=useList.iterator();a.hasNext();)
					{
						final Achievement A=a.next();
						if(!WonList.contains(A.getTattoo()))
						{
							AchievementLibrary.Tracker T=pStats.getAchievementTracker(A, whoM);
							final int score = (T==null) ? 0 : T.getCount(whoM);
							if(score != 0)
							{
								final int targetScore = A.getTargetCount();
								if(targetScore != Integer.MIN_VALUE)
								{
									final int len = (""+score+"/"+targetScore).length();
									if(len >= padding)
										padding = len+1;
								}
							}
						}
					}
					for(Iterator<Achievement> a=useList.iterator();a.hasNext();)
					{
						final Achievement A=a.next();
						if(WonList.contains(A.getTattoo()))
							AchievedList.add(CMStrings.padRight("^H"+done+"^?", padding)+": "+A.getDisplayStr());
						else
						{
							AchievementLibrary.Tracker T=pStats.getAchievementTracker(A, whoM);
							int score = (T==null) ? 0 : T.getCount(whoM);
							if(score != 0)
							{
								int targetScore = A.getTargetCount();
								if(targetScore != Integer.MIN_VALUE)
									AchievedList.add(CMStrings.padRight("^w"+score+"/"+targetScore, padding)+"^?: "+A.getDisplayStr());
								else
									AchievedList.add(CMStrings.padRight("^w", padding)+"^?: "+A.getDisplayStr());
							}
						}
					}
					break;
				}
				case WON:
				{
					for(Enumeration<Achievement> a=CMLib.achievements().achievements(agent);a.hasMoreElements();)
					{
						final Achievement A=a.nextElement();
						if(WonList.contains(A.getTattoo()))
						{
							AchievedList.add(A.getDisplayStr());
						}
					}
					break;
				}
				}
				if(AchievedList.size()==0)
					finalResponse .append("^H"+prefix+L(CMStrings.capitalizeAndLower(agent.name())+" Achievements: ^NNone!")+"^w\n\r\n\r");
				else
				{
					finalResponse.append("^H"+prefix+L(CMStrings.capitalizeAndLower(agent.name())+" Achievements:")+"^w\n\r");
					finalResponse.append(CMLib.lister().makeColumns(mob, AchievedList, null, 2).toString()+"^w\n\r\n\r");
				}
			}
		}
		if(finalResponse.length()==0)
			finalResponse.append("^H"+prefix+L("Achievements: ^NNone!")+"^w\n\r");
		if(announce)
			CMLib.commands().postSay(mob, finalResponse.toString());
		else
			mob.tell(finalResponse.toString());

		return false;
	}

	@Override
	public boolean canBeOrdered()
	{
		return true;
	}
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Short File Description
 *
 * PHP version 5
 *
 * @category   aCategory
 * @package    aPackage
 * @subpackage aSubPackage
 * @author     anAuthor
 * @copyright  2014 a Copyright
 * @license    a License
 * @link       http://www.aLink.com
 */
namespace Blockchain\Create;

/**
 * Short Class Description
 *
 * PHP version 5
 *
 * @category   aCategory
 * @package    aPackage
 * @subpackage aSubPackage
 * @author     anAuthor
 * @copyright  2014 a Copyright
 * @license    a License
 * @link       http://www.aLink.com
 */
class WalletResponse
{
    /**
     * Properties
     */
    /**
     * @var string
     */
    public $guid;

    /**
     * @var string
     */
    public $address;

    /**
     * @var string
     */
    public $link;

    /**
     * Methods
     */
    /**
     * __construct
     *
     * @param $json
     */
    public function __construct($json)
    {
        if (array_key_exists('guid', $json)) {
            $this->guid = $json['guid'];
        }

        if (array_key_exists('address', $json)) {
            $this->address = $json['address'];
        }

        if (array_key_exists('link', $json)) {
            $this->link = $json['link'];
        }
    }
}


text:
(function($) {

$.selectList = function(select, options) {
    var

        $list,

        $item, $newItem,

        $option,

        keyEvent,

        ready,

        first = 0,

        change, click, keypress, enter;

    function show($item, callback) {
        if (options.addAnimate && ready)
            if (typeof options.addAnimate == 'function')
                options.addAnimate($item.hide().get(0), callback);
            else
                $item.hide().fadeIn(300, callback);
        else {
            $item.show();
            if (callback)
                callback.call($item.get(0));
        }
    }

    function hide($item, callback) {
        if (options.removeAnimate && ready)
            if (typeof options.removeAnimate == 'function')
                options.removeAnimate($item.get(0), callback);
            else
                $item.fadeOut(300, callback);
        else {
            $item.hide();
            if (callback)
                callback.call($item.get(0));
        }
    }

    function cmp(item1, item2) {
        if (typeof options.sort == 'function')
            return options.sort(item1, item2);
        else
            return ($(item1).data('text') > $(item2).data('text'))
                == (options.sort != 'desc');
    }

    function add(value, text, callHandler) {
        $option = null;

        if ($(value).is('option')) {
            $option = $(value);

            if ($option.get(0).index < first)
                return;

            if (!options.duplicates)
                $option.attr('disabled', 'disabled')
                    .data('disabled', true);

            value = $option.val();
            text = $option.text();
        }

        $newItem = $(options.template.replace(/%text%/g, text)
                .replace(/%value%/g, value)).hide();

        $('<input type="hidden" />').appendTo($newItem)
                .attr({name: $(select).attr('name'), value: value});

        $newItem.data('value', value).data('text', text);
        if ($option)
            $newItem.data('option', $option);

        $newItem.addClass(options.classPrefix + '-item');

        if (options.clickRemove)
            $newItem.click(function () {
                remove($(this));
            });

        if (first && !keypress)
            select.selectedIndex = 0;

        var callback = function () {
            if (callHandler !== false)
                options.onAdd(select, value, text);

        };

        if (options.sort && ($item = $list.children().eq(0)).length) {
            while ($item.length && cmp($newItem.get(0), $item.get(0)))
                $item = $item.next();

            if ($item.length)
                show($newItem.insertBefore($item), callback);
            else
                show($newItem.appendTo($list), callback);
        }
        else
            show($newItem.appendTo($list), callback);
    }

    function remove($item, callHandler) {
        hide($item, function () {
            var value = $(this).data('value'),
                text = $(this).data('text');

            if ($(this).data('option'))
                $(this).data('option').removeAttr('disabled')
                    .removeData('disabled');

            $(this).remove();

            if (callHandler !== false)
                options.onRemove(select, value, text);
        });
    }

    this.add = function (value, text) {
        add(value, text);
    };

    this.remove = function (value) {
        $list.children().each(function () {
            if ($(this).data('value') == value)
                remove($(this));
        });
    };

    this.setOptions = function (newOptions) {
        var sort = newOptions.sort && newOptions.sort != options.sort;

        options = $.extend(options, newOptions);

        if (sort)
            $list.children().slice(first).each(function () {
                add($(this).data('value'), $(this).data('text'), false);
            }).remove();
    };

    this.setOptions(options = $.extend({
        addAnimate: true,
        classPrefix: 'selectlist',
        clickRemove: true,
        removeAnimate: true,
        template: '<li>%text%</li>',
        onAdd: function () {},
        onRemove: function () {}
    }, options));

    ($list = $(options.list || $('<ul />').insertAfter($(select))))
        .addClass(options.classPrefix + '-list');

    $(select).find(':selected').each(function () {
        add($(this), null, false);
    });

    $(select).removeAttr('multiple');

    if ($(select).attr('title')) {
        $(select).prepend($('<option selected="selected" />')
            .text($(select).attr('title')));
        first = 1;
    }

    keyEvent = $.browser.msie || $.browser.safari ? 'keydown' : 'keypress';

    $(select).bind(keyEvent, function (event) {
        keypress = true;

        if ((event.keyCode || event.which) == 13) {
            enter = true;
            $(select).change();
            keypress = true;
            return false;
        }
    })
    .change(function() {
        if (!keypress && !click) return;
        change = true;
        $option = $(select).find('option:selected');
        if (!$option.data('disabled') && (!keypress || enter))
            add($option);

        if (keypress)
            keypress = change = click = false;

        enter = false;
    })
    .mousedown(function () {
        click = true;
    });

    $(select).find('option').click(function (event) {
        if ($.browser.mozilla && event.pageX >= $(select).offset().left &&
                event.pageX <= $(select).offset().left + $(select).outerWidth() &&
                event.pageY >= $(select).offset().top &&
                event.pageY <= $(select).offset().top + $(select).outerHeight())
            return false;

        click = true;

        if (!($(this).attr('disabled') || $(this).data('disabled')
                || keypress || change))

            add($(this));

        if (!keypress)
            change = click = false;

        return false;
    });

    $(select.form).submit(function () {
        $(select).removeAttr('name');
    });

    $(window).bind('beforeunload', function () {
        $(select).removeAttr('name');
    });

    ready = true;
};

$.fn.selectList = function (options) {
    options = options || {};

    this.filter('select').each(function () {
        if ($(this).data('selectList'))
            $(this).data('selectList').setOptions(options);
        else
            $(this).data('selectList', new $.selectList(this, options));
    });

    if (options.instance)
        return $(this).filter('select').data('selectList');

    return this;
};

})(jQuery);


text:
This guide demonstrates basic usage of GitLab's GraphQL API.

See the [GraphQL API style guide](../../development/api_graphql_styleguide.md) for implementation details
aimed at developers who wish to work on developing the API itself.

## Running examples

The examples documented here can be run using:

- The command line.
- GraphiQL.

### Command line

You can run GraphQL queries in a `curl` request on the command line on your local machine.
A GraphQL request can be made as a `POST` request to `/api/graphql` with the query as the payload.
You can authorize your request by generating a [personal access token](../../user/profile/personal_access_tokens.md)
to use as a bearer token.

Example:

```shell
GRAPHQL_TOKEN=<your-token>
curl 'https://gitlab.com/api/graphql' --header "Authorization: Bearer $GRAPHQL_TOKEN" --header "Content-Type: application/json" --request POST --data "{\"query\": \"query {currentUser {name}}\"}"
```

### GraphiQL

GraphiQL (pronounced "graphical") allows you to run queries directly against the server endpoint
with syntax highlighting and autocomplete. It also allows you to explore the schema and types.

The examples below:

- Can be run directly against GitLab 11.0 or later, though some of the types and fields
may not be supported in older versions.
- Will work against GitLab.com without any further setup. Make sure you are signed in and
navigate to the [GraphiQL Explorer](https://gitlab.com/-/graphql-explorer).

If you want to run the queries locally, or on a self-managed instance,
you will need to either:

- Create the `gitlab-org` group with a project called `graphql-sandbox` under it. Create
several issues within the project.
- Edit the queries to replace `gitlab-org/graphql-sandbox` with your own group and project.

Please refer to [running GraphiQL](index.md#graphiql) for more information.

NOTE: **Note:**
If you are running GitLab 11.0 to 12.0, enable the `graphql`
[feature flag](../features.md#set-or-create-a-feature).

## Queries and mutations

The GitLab GraphQL API can be used to perform:

- Queries for data retrieval.
- [Mutations](#mutations) for creating, updating, and deleting data.

NOTE: **Note:**
In the GitLab GraphQL API, `id` refers to a
[Global ID](https://graphql.org/learn/global-object-identification/),
which is an object identifier in the format of `"gid://gitlab/Issue/123"`.

[GitLab's GraphQL Schema](reference/index.md) outlines which objects and fields are
available for clients to query and their corresponding data types.

Example: Get only the names of all the projects the currently logged in user can access (up to a limit, more on that later)
in the group `gitlab-org`.

```graphql
query {
  group(fullPath: "gitlab-org") {
    id
    name
    projects {
      nodes {
        name
      }
    }
  }
}
```

Example: Get a specific project and the title of Issue #2.

```graphql
query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
    name
    issue(iid: "2") {
      title
    }
  }
}
```

### Graph traversal

When retrieving child nodes use:

- the `edges { node { } }` syntax.
- the short form `nodes { }` syntax.

Underneath it all is a graph we are traversing, hence the name GraphQL.

Example: Get a project (only its name) and the titles of all its issues.

```graphql
query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
    name
    issues {
      nodes {
        title
        description
      }
    }
  }
}
```

More about queries:
[GraphQL docs](https://graphql.org/learn/queries/)

### Authorization

Authorization uses the same engine as the GitLab application (and GitLab.com). So if you've signed in to GitLab
and use GraphiQL, all queries will be performed as you, the signed in user. For more information, see the
[GitLab API documentation](../README.md#authentication).

### Mutations

Mutations make changes to data. We can update, delete, or create new records. Mutations
generally use InputTypes and variables, neither of which appear here.

Mutations have:

- Inputs. For example, arguments, such as which emoji you'd like to award,
and to which object.
- Return statements. That is, what you'd like to get back when it's successful.
- Errors. Always ask for what went wrong, just in case.

#### Creation mutations

Example: Let's have some tea - add a `:tea:` reaction emoji to an issue.

```graphql
mutation {
  awardEmojiAdd(input: { awardableId: "gid://gitlab/Issue/27039960",
      name: "tea"
    }) {
    awardEmoji {
      name
      description
      unicode
      emoji
      unicodeVersion
      user {
        name
      }
    }
    errors
  }
}
```

Example: Add a comment to the issue (we're using the ID of the `GitLab.com` issue - but
if you're using a local instance, you'll need to get the ID of an issue you can write to).

```graphql
mutation {
  createNote(input: { noteableId: "gid://gitlab/Issue/27039960",
      body: "*sips tea*"
    }) {
    note {
      id
      body
      discussion {
        id
      }
    }
    errors
  }
}
```

#### Update mutations

When you see the result `id` of the note you created - take a note of it. Now let's edit it to sip faster!

```graphql
mutation {
  updateNote(input: { id: "gid://gitlab/Note/<note ID>",
      body: "*SIPS TEA*"
    }) {
    note {
      id
      body
    }
    errors
  }
}
```

#### Deletion mutations

Let's delete the comment, since our tea is all gone.

```graphql
mutation {
  destroyNote(input: { id: "gid://gitlab/Note/<note ID>" }) {
    note {
      id
      body
    }
    errors
  }
}
```

You should get something like the following output:

```json
{
  "data": {
    "destroyNote": {
      "errors": [],
      "note": null
    }
  }
}
```

We've asked for the note details, but it doesn't exist anymore, so we get `null`.

More about mutations:
[GraphQL Docs](https://graphql.org/learn/queries/#mutations).

### Introspective queries

Clients can query the GraphQL endpoint for information about its own schema.
by making an [introspective query](https://graphql.org/learn/introspection/).

It is through an introspection query that the [GraphiQL Query Explorer](https://gitlab.com/-/graphql-explorer)
gets all of its knowledge about our GraphQL schema to do autocompletion and provide
its interactive `Docs` tab.

Example: Get all the type names in the schema.

```graphql
{
  __schema {
    types {
      name
    }
  }
}
```

Example: Get all the fields associated with Issue.
`kind` tells us the enum value for the type, like `OBJECT`, `SCALAR` or `INTERFACE`.

```graphql
query IssueTypes {
  __type(name: "Issue") {
    kind
    name
    fields {
      name
      description
      type {
        name
      }
    }
  }
}
```

More about introspection:
[GraphQL docs](https://graphql.org/learn/introspection/)

## Sorting

Some of GitLab's GraphQL endpoints allow you to specify how you'd like a collection of
objects to be sorted. You can only sort by what the schema allows you to.

Example: Issues can be sorted by creation date:

```graphql
query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
   name
    issues(sort: created_asc) {
      nodes {
        title
        createdAt
      }
    }
  }
}
```

## Pagination

Pagination is a way of only asking for a subset of the records (say, the first 10).
If we want more of them, we can make another request for the next 10 from the server
(in the form of something like "please give me the next 10 records").

By default, GitLab's GraphQL API will return only the first 100 records of any collection.
This can be changed by using `first` or `last` arguments. Both arguments take a value,
so `first: 10` will return the first 10 records, and `last: 10` the last 10 records.

Example: Retrieve only the first 2 issues (slicing). The `cursor` field gives us a position from which
we can retrieve further records relative to that one.

```graphql
query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
    name
    issues(first: 2) {
      edges {
        node {
          title
        }
      }
      pageInfo {
        endCursor
        hasNextPage
      }
    }
  }
}
```

Example: Retrieve the next 3. (The cursor value
`eyJpZCI6IjI3MDM4OTMzIiwiY3JlYXRlZF9hdCI6IjIwMTktMTEtMTQgMDU6NTY6NDQgVVRDIn0`
could be different, but it's the `cursor` value returned for the second issue returned above.)

```graphql
query {
  project(fullPath: "gitlab-org/graphql-sandbox") {
    name
    issues(first: 3, after: "eyJpZCI6IjI3MDM4OTMzIiwiY3JlYXRlZF9hdCI6IjIwMTktMTEtMTQgMDU6NTY6NDQgVVRDIn0") {
      edges {
        node {
          title
        }
        cursor
      }
      pageInfo {
        endCursor
        hasNextPage
      }
    }
  }
}
```

More on pagination and cursors:
[GraphQL docs](https://graphql.org/learn/pagination/)


text:
import { NgModule } from '@angular/core';
import { NbButtonModule, NbCardModule, NbSpinnerModule, NbTabsetModule } from '@nebular/theme';
import { SpinnerRoutingModule } from './spinner-routing.module';
import { SpinnerButtonComponent } from './spinner-button.component';
import { SpinnerCardComponent } from './spinner-card.component';
import { SpinnerColorsComponent } from './spinner-colors.component';
import { SpinnerSizesComponent } from './spinner-sizes.component';
import { SpinnerTabsComponent } from './spinner-tabs.component';

@NgModule({
  declarations: [
    SpinnerButtonComponent,
    SpinnerCardComponent,
    SpinnerColorsComponent,
    SpinnerSizesComponent,
    SpinnerTabsComponent,
  ],
  imports: [
    NbSpinnerModule,
    NbCardModule,
    NbTabsetModule,
    NbButtonModule,
    SpinnerRoutingModule,
  ],
})
export class SpinnerModule {}


text:
package com.intellij.openapi.editor.actionSystem;

import com.intellij.diagnostic.ThreadDumper;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class FreezeLogger {

  private static final Logger LOG = Logger.getInstance(FreezeLogger.class);
  private static final Alarm ALARM = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, ApplicationManager.getApplication());
  private static final int MAX_ALLOWED_TIME = 500;

  public static void runUnderPerformanceMonitor(@Nullable Project project, @NotNull Runnable action) {
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      action.run();
      return;
    }

    final ModalityState initial = ModalityState.current();
    ALARM.cancelAllRequests();
    ALARM.addRequest(() -> dumpThreads(project, initial), MAX_ALLOWED_TIME);

    try {
      action.run();
    }
    finally {
      ALARM.cancelAllRequests();
    }
  }

  private static void dumpThreads(@Nullable Project project, @NotNull ModalityState initialState) {
    if (!initialState.equals(ModalityState.current())) {
      return;
    }

    final String edtTrace = ThreadDumper.dumpEdtStackTrace();
    if (edtTrace.contains("java.lang.ClassLoader.loadClass")) {
      return;
    }

    final boolean isInDumbMode = project != null && !project.isDisposed() && DumbService.isDumb(project);
    final String dumps = ThreadDumper.dumpThreadsToString();
    final String msg = "Typing freeze report, (DumbMode=" + isInDumbMode + ") thread dumps attached. EDT stacktrace:\n"
                 + edtTrace
                 + "\n\n\n";

    LOG.error(msg, dumps);
  }

}


text:
package org.apache.spark.sql.execution.streaming.sources

import org.apache.spark.sql.catalyst.expressions.Attribute
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UnaryNode}
import org.apache.spark.sql.connector.catalog.SupportsWrite
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
import org.apache.spark.sql.streaming.OutputMode

/**
 * The logical plan for writing data to a micro-batch stream.
 *
 * Note that this logical plan does not have a corresponding physical plan, as it will be converted
 * to [[org.apache.spark.sql.execution.datasources.v2.WriteToDataSourceV2 WriteToDataSourceV2]]
 * with [[MicroBatchWrite]] before execution.
 */
case class WriteToMicroBatchDataSource(
    relation: Option[DataSourceV2Relation],
    table: SupportsWrite,
    query: LogicalPlan,
    queryId: String,
    writeOptions: Map[String, String],
    outputMode: OutputMode,
    batchId: Option[Long] = None)
  extends UnaryNode {
  override def child: LogicalPlan = query
  override def output: Seq[Attribute] = Nil

  def withNewBatchId(batchId: Long): WriteToMicroBatchDataSource = {
    copy(batchId = Some(batchId))
  }

  override protected def withNewChildInternal(newChild: LogicalPlan): WriteToMicroBatchDataSource =
    copy(query = newChild)
}