text:
package com.vaadin.ui;

import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;

import com.vaadin.server.ErrorMessage;
import com.vaadin.server.Resource;
import com.vaadin.server.SerializableFunction;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.shared.ui.composite.CompositeState;

/**
 * Composite allows creating new UI components by composition of existing
 * server-side components.
 *

 * A composite is created by extending the Composite class and setting the
 * composition root component using {@link #setCompositionRoot(Component)}.
 *

 *

 * The composition root itself can contain more components. The advantage of
 * wrapping it in a composite is that the details of the composition root, such
 * as its public API, are hidden from the users of the composite.
 *

 *

 * A composite itself does not contribute to the DOM in any way (contrary to
 * {@link CustomComponent} which adds a {@code
} to the DOM.
 *

 *
 * @author Vaadin Ltd.
 * @since 8.1
 */
public class Composite extends AbstractComponent implements HasComponents {

    /**
     * The contained component.
     */
    private Component root = null;

    /**
     * Constructs a new empty composite.
     *

     * Use {@link #setCompositionRoot(Component)} to define the contents of the
     * composite.
     */
    public Composite() {
    }

    /**
     * Constructs a new composite containing the given component.
     *
     * @param compositionRoot
     *            the root of the composition component tree. It must not be
     *            null.
     */
    public Composite(AbstractComponent compositionRoot) {
        this();
        Objects.requireNonNull(compositionRoot);
        setCompositionRoot(compositionRoot);
    }

    /**
     * Returns the composition root.
     *
     * @return the Component Composition root.
     */
    protected Component getCompositionRoot() {
        return root;
    }

    /**
     * Sets the component contained in the composite.
     *

     * You must set the composition root to a non-null value before the
     * component can be used. It cannot be changed.
     *

     *
     * @param compositionRoot
     *            the root of the composition component tree.
     */
    protected void setCompositionRoot(Component compositionRoot) {
        if (root != null) {
            throw new IllegalStateException(
                    "Composition root cannot be changed");
        }
        if (compositionRoot == null) {
            throw new IllegalArgumentException(
                    "Composition root cannot be null");
        }

        // set new component
        if (compositionRoot.getParent() != null) {
            // If the component already has a parent, try to remove it
            AbstractSingleComponentContainer.removeFromParent(compositionRoot);
        }

        compositionRoot.setParent(this);
        root = compositionRoot;
        markAsDirty();
    }

    /* Basic component features ------------------------------------------ */

    @Override
    public Iterator<Component> iterator() {
        if (getCompositionRoot() != null) {
            return Collections.singletonList(getCompositionRoot()).iterator();
        } else {
            return Collections.<Component> emptyList().iterator();
        }
    }

    @Override
    protected CompositeState getState() {
        return (CompositeState) super.getState();
    }

    @Override
    protected CompositeState getState(boolean markAsDirty) {
        return (CompositeState) super.getState(markAsDirty);
    }

    @Override
    public void beforeClientResponse(boolean initial) {
        super.beforeClientResponse(initial);
        if (getCompositionRoot() == null) {
            throw new IllegalStateException(
                    "A composite must always have a composition root");
        }
    }

    @Override
    public String getStyleName() {
        Component root = getCompositionRoot();
        return root == null ? "" : root.getStyleName();
    }

    @Override
    public void setStyleName(String style) {
        getRootOrThrow().setStyleName(style);
    }

    @Override
    public void setStyleName(String style, boolean add) {
        getRootAbstractComponentOrThrow().setStyleName(style, add);
    }

    @Override
    public void addStyleName(String style) {
        getRootOrThrow().addStyleName(style);
    }

    @Override
    public void removeStyleName(String style) {
        getRootOrThrow().removeStyleName(style);
    }

    @Override
    public String getPrimaryStyleName() {
        return getRootAbstractComponentPropertyOrNull(
                AbstractComponent::getPrimaryStyleName);
    }

    @Override
    public void setPrimaryStyleName(String style) {
        getRootOrThrow().setPrimaryStyleName(style);
    }

    private Component getRootOrThrow() {
        Component root = getCompositionRoot();
        if (root == null) {
            throw new IllegalStateException(
                    "Composition root has not been set");
        }
        return root;
    }

    private AbstractComponent getRootAbstractComponentOrThrow() {
        Component root = getRootOrThrow();
        if (!(root instanceof AbstractComponent)) {
            throw new IllegalStateException(
                    "Composition root is not AbstractComponent");
        }
        return (AbstractComponent) root;
    }

    private <T> T getRootPropertyOrNull(
            SerializableFunction<Component, T> getter) {
        Component root = getCompositionRoot();
        return root == null ? null : getter.apply(root);
    }

    private <T> T getRootAbstractComponentPropertyOrNull(
            SerializableFunction<AbstractComponent, T> getter) {
        Component root = getCompositionRoot();
        if (root instanceof AbstractComponent) {
            return getter.apply((AbstractComponent) root);
        }
        return null;
    }

    @Override
    public float getWidth() {
        return getRootOrThrow().getWidth();
    }

    @Override
    public float getHeight() {
        return getRootOrThrow().getHeight();
    }

    @Override
    public Unit getWidthUnits() {
        return getRootOrThrow().getWidthUnits();
    }

    @Override
    public Unit getHeightUnits() {
        return getRootOrThrow().getHeightUnits();
    }

    @Override
    public void setHeight(String height) {
        getRootOrThrow().setHeight(height);
    }

    @Override
    public void setWidth(float width, Unit unit) {
        getRootOrThrow().setWidth(width, unit);
    }

    @Override
    public void setHeight(float height, Unit unit) {
        getRootOrThrow().setHeight(height, unit);
    }

    @Override
    public void setWidth(String width) {
        getRootOrThrow().setWidth(width);
    }

    @Override
    public void setSizeFull() {
        getRootOrThrow().setSizeFull();
    }

    @Override
    public void setSizeUndefined() {
        getRootOrThrow().setSizeUndefined();
    }

    @Override
    public void setWidthUndefined() {
        getRootOrThrow().setWidthUndefined();
    }

    @Override
    public void setHeightUndefined() {
        getRootOrThrow().setHeightUndefined();
    }

    @Override
    public void setId(String id) {
        getRootOrThrow().setId(id);
    }

    @Override
    public String getId() {
        return getRootPropertyOrNull(Component::getId);
    }

    @Override
    public void setDebugId(String id) {
        getRootAbstractComponentOrThrow().setDebugId(id);
    }

    @Override
    public String getDebugId() {
        return getRootAbstractComponentPropertyOrNull(
                AbstractComponent::getDebugId);
    }

    @Override
    public String getCaption() {
        return getRootPropertyOrNull(Component::getCaption);
    }

    @Override
    public void setCaption(String caption) {
        getRootOrThrow().setCaption(caption);
    }

    @Override
    public void setCaptionAsHtml(boolean captionAsHtml) {
        getRootAbstractComponentOrThrow().setCaptionAsHtml(captionAsHtml);
    }

    @Override
    public boolean isCaptionAsHtml() {
        return getRootAbstractComponentPropertyOrNull(
                AbstractComponent::isCaptionAsHtml);
    }

    @Override
    public Resource getIcon() {
        return getRootPropertyOrNull(Component::getIcon);
    }

    @Override
    public void setIcon(Resource icon) {
        getRootOrThrow().setIcon(icon);
    }

    @Override
    public String getDescription() {
        return getRootOrThrow().getDescription();
    }

    @Override
    public void setDescription(String description) {
        getRootAbstractComponentOrThrow().setDescription(description);
    }

    @Override
    public void setDescription(String description, ContentMode mode) {
        getRootAbstractComponentOrThrow().setDescription(description, mode);
    }

    @Override
    public ErrorMessage getErrorMessage() {
        return getRootAbstractComponentPropertyOrNull(
                AbstractComponent::getErrorMessage);
    }

    @Override
    public ErrorMessage getComponentError() {
        return getRootAbstractComponentPropertyOrNull(
                AbstractComponent::getComponentError);
    }

    @Override
    public void setComponentError(ErrorMessage componentError) {
        getRootAbstractComponentOrThrow().setComponentError(componentError);
    }

}


text:
var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    connect = require('gulp-connect'),
    karma = require('gulp-karma'),
    jshint = require('gulp-jshint'),
    protractor = require("gulp-protractor").protractor,
    concat = require('gulp-concat'),
    rename = require('gulp-rename'),
    program = require('commander'),
    stylish = require('jshint-stylish'),
    debug = false,
    WATCH_MODE = 'watch',
    RUN_MODE = 'run';

var mode = RUN_MODE;

function list(val) {
  return val.split(',');
}

program
  .version('0.0.1')
  .option('-t, --tests [glob]', 'Specify which tests to run')
  .option('-b, --browsers <items>', 'Specify which browsers to run on', list)
  .option('-r, --reporters <items>', 'Specify which reporters to use', list)
  .parse(process.argv);

gulp.task('js', function() {
  var jsTask = gulp.src('src/**/*.js')
    .pipe(concat('ng-breadcrumbs.js'))
    .pipe(gulp.dest('dist'));
  if (!debug) {
    jsTask.pipe(uglify());
  }
  jsTask
    .pipe(rename('ng-breadcrumbs.min.js'))
    .pipe(gulp.dest('dist'));
});

gulp.task('lint', function() {
  gulp.src(['src/**/*.js', 'test/**/*.js'])
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter(stylish));
});

gulp.task('connect', function() {
  if (mode === WATCH_MODE) {
    gulp.watch(['public/**/*', 'index.html'], function() {
      gulp.src(['public/**/*', 'index.html'])
        .pipe(connect.reload());
    });
  }

  connect.server({
    livereload: mode === WATCH_MODE
  });
});

gulp.task('karma', ['js'], function() {
  // undefined.js: unfortunately necessary for now
  gulp.src(['undefined.js'])
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: mode,
      tests: program.tests,
      reporters: program.reporters || ['progress'],
      browsers: program.browsers || ['PhantomJS']
    }))
    .on('error', function() {});
});

gulp.task('protractor', function(done) {
  gulp.src(["./src/tests/*.js"])
    .pipe(protractor({
      configFile: 'protractor.conf.js',
      args: [
        '--baseUrl', 'http://127.0.0.1:8080',
        '--browser', program.browsers ? program.browsers[0] : 'phantomjs'
      ]
    }))
    .on('end', function() {
      if (mode === RUN_MODE) {
        connect.serverClose();
      }
      done();
    })
    .on('error', function() {
      if (mode === RUN_MODE) {
        connect.serverClose();
      }
      done();
    });
});

gulp.task('debug', function() {
  debug = true;
});

gulp.task('watch-mode', function() {
  mode = WATCH_MODE;

  var jsWatcher = gulp.watch(['src/**/*.js'], ['js']),
      jshintWatcher = gulp.watch(['src/**/*.js', 'test/**/*.js'], ['lint']),
      karmaWatcher = gulp.watch('test/unit/**/*.js', ['karma']),
      protractorWatcher = gulp.watch('test/ui/**/*.js', ['protractor']);

  function changeNotification(event) {
    console.log('File', event.path, 'was', event.type, ', running tasks...');
  }

  jsWatcher.on('change', changeNotification);
  jshintWatcher.on('change', changeNotification);
  karmaWatcher.on('change', changeNotification);
  protractorWatcher.on('change', changeNotification);
});

gulp.task('all', ['js', 'lint', 'karma', 'protractor']);
gulp.task('default', ['watch-mode', 'all']);
gulp.task('server', ['connect', 'default']);
gulp.task('test', ['connect', 'all']);

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="5dp"
    card_view:cardBackgroundColor="@color/white"
    card_view:cardElevation="5dp">
    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="120dp"
        android:gravity="center"
        android:orientation="vertical">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_toast" />
        <TextView
            android:id="@+id/toast_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:text="内容测试"
            android:textColor="@color/text_333333"
            android:textSize="15sp" />
    </LinearLayout>
</android.support.v7.widget.CardView>


text:
package hso.autonomy.agent.communication.perception.impl;

import hso.autonomy.agent.communication.perception.ITimerPerceptor;

/**
 * @author Simon Raffeiner
 */
public class TimePerceptor extends Perceptor implements ITimerPerceptor
{
	private float time;

	public TimePerceptor()
	{
		this(0.00f);
	}

	public TimePerceptor(float time)
	{
		super("time");
		this.time = time;
	}

	@Override
	public float getTime()
	{
		return time;
	}
}


text:
for flextext in `ls *.flextext`;
    do
         exb=$(echo $flextext | sed 's/flextext/exb/g');
         curl -F file=@$flextext "http://localhost:8080/flex2exb/transform/file/upload" > $exb;
done


text:
![Swift 3.0.x](https://img.shields.io/badge/Swift-3.0.x-orange.svg)
[![License: MIT](https://img.shields.io/badge/License-MIT-grey.svg)](https://opensource.org/licenses/MIT)

Description

## Features

- [x] Feature 1

## Requirements

- iOS 9.0+
- Xcode 8.0+
- Swift 3.0+

### Persistent Storage
This project is aimed at testing and showing how to use `Realm` as an alternative to `CoreData`. It is used for data persistence over time, a special highlight is dedicated to its multithreading capabilities while syncing contacts with remote server, leaving room for the Main Thread to focus on UI rendering.

### Dependency Management
Contact Syncing relies on **two dependency managers**. It is usually best practice to centralize dependency management into only one of them — the **reason to use both CocoaPods and Carthage** in Contact Syncing was its necessity to import some of the libraries only supporting the latter (e.g. `DataSource` and `Ethanol`).

#### CocoaPods
[CocoaPods](https://cocoapods.org "CocoaPods Homepage") is the most famous and widely used dependency manager in iOS. When imported, the libraries are added to your repository in a _centralized_ fashion. There is no need to update the **pods** after cloning the repository as they are already included in the workspace.
Most of the libraries are imported using CocoaPods:

1. [**RealmSwift**](https://github.com/realm/realm-cocoa/tree/master/RealmSwift) (cocoapods) - Realm is a mobile database: a replacement for Core Data & SQLite.

##### Update
Run the following command in order to update the Pods:
`pod udpate`

##### Add Dependency
All dependencies are added in the entry point file named `Podfile`. In order to add any new dependency, just add a new entry and perform an Update (see above).

#### Carthage
[Carthage](https://github.com/Carthage/Carthage "Carthage Homepage") is intended to be the simplest way to add frameworks to your Cocoa application. It is a _decentralized_ dependency manager that will create separate `xcodebuild` libraries, it is the responsability of the developer to import them. Once imported, the libraries are not actually part of your repository; consequently, it is always needed to fetch them after the project is cloned.

1. [**ReactiveCocoa**](https://github.com/ReactiveCocoa/ReactiveCocoa) - ReactiveCocoa (RAC) is a Cocoa framework inspired by Functional Reactive Programming. It provides APIs for composing and transforming streams of values over time.
2. [**Result**](https://github.com/antitypical/Result) - This is a Swift µframework providing Result<Value, Error>, which is used with reactive Cocoa for handling event results in a better way.
3. [**DataSource**](https://github.com/Vadim-Yelagin/DataSource) - DataSource is a Swift framework that helps you specify, display and manipulate sectioned collections of items in UITableview and UICollectionView in an MVVM (Model-View-ViewModel) fashion without having to deal with index mapping or writing repetitive and error-prone code to handle and display changes of those collections.
5. [**Ethanol**](https://github.com/Fueled) - (Contacts/Utilities) Developed and managed by **Fueled**. Ethanol is used in many places throughout the project for utility functions and reusable code, here Address Book contacts fetch most notably.

##### Update
Note that you need to update **carthage** in order to be able to compile the project. This can be achieved by running the following command in the project:
`carthage update --use-submodules --no-build`

When encountering update/setup issues, it can be useful to reset all dependencies by running the following command (no risk involved):
`git submodule foreach --recursive "git reset --hard && git clean -xqfd" && git submodule update --init —recursive`

##### Add Dependency
The process might seem trivial but is actually more complicated than it seemed because of our usage of non-builtin schemes name (Snapshot, Staging and Production). This section describes how to do it, using the example of adding `ethanol-social` into the workspace.

_The screenshots in the following sections all reference the project `EthanolExamples` (Or a different project name), but it's the same as if it was `Contact Syncing`._

###### Add it via Carthage

1. Add `ethanol-social` into the Cartfile. For example, the result will be:

```
# <Current dependencies...>
github "Fueled/ethanol-social" ~> 0.1
```

2. Run `carthage update --use-submodules --no-build`
This will create a new folder in the relative directory `Carthage/Checkouts` called `ethanol-social`

###### Add it into the workspace

1. Locate the .xcodeproj package from `ethanol-social`:
![ethanol-social.xcodeproj package](README_Images/XcodeProjLocation.png)
Drag and drop it into the workspace:
![result](README_Images/XcodeProjDragNDropWorkspace.png)

2. _This step and the next one is sometimes not necessarily, but is most of the times. In any case, the end result is the same_
Open the workspace `ContactSyncing.xcworkspace`, and go to the `Link Binary with Libraries` build phase for the Contact Syncing target. To do so, first click on `Contact Syncing` project, then click on the target `Contact Syncing`, go to `General`, and finally expand `Link Binary with Libraries`.
![Build Phases](README_Images/LinkBinaryWithLibraries.png)
From there, click the "+" button at the bottom and select the framework from the dependency you're adding (In our case, `EthanolSocial.framework`):
![Add framework](README_Images/AddAFrameworkLink.png)
_Note that if xcode was properly setting up everything, we would only need to do the previous step and step #4._

3. You now have to remove it from there, in `Link Binary with Libraries`. The purpose of adding it in the first place was so xcode adds a reference to it in the `Frameworks` folder.
![Select&Delete](README_Images/SelectNDeleteFramework.png)
Before you continue, please make sure that the the framework is there, with a missing icon.
In our case, here what it looks like:
![Framework with missing icon](README_Images/FrameworkWithMissingIcon.png)

4. Now, similarly to the `Link Binary with Libraries`, expand the `Embedded Binaries` build phase right above it. From there, click the "+" button, and select the framework from the `Frameworks` folder:
![Add embedded binaries](README_Images/AddEmbeddedLibraries.png)
The framework should then show up both in `Embedded Binaries` and in `Link Binary with Libraries`:
![End results](README_Images/EndResultAfterAddingEmbeddedBinaries.png)

5. Now, we need to edit the project file so that everything works for other people when they fetch it later on. Do to so, first right-click on `EthanolExample` in the workspace and click on `Show in Finder`
![Show in finder](README_Images/ShowInFinder.png)
From the finder window that shows up, right-click on the `ContactSyncing.xcodeproj` and click on `Show Package Contents`.
![Show Package Contents](README_Images/ShowPackageContents.png)
From then, locate the file `project.pbxproj` and open it with your favorite text editor.
![project.pbxproj](README_Images/ProjectPbxprojLocation.png)

6. Search for the framework you added on step #2 (In our case, `EthanolSocial.framework`). After a few hits, you should find a line that looks like this one:

```
F43F75DA1B9F05C200954745 /* EthanolSocial.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = EthanolSocial.framework; path = "../ethanol-social/build/Debug-iphoneos/EthanolSocial.framework"; sourceTree = "<group>"; };
```

See that ugly `path` reference? That's what we're going to fix. What's happening here is that xcode has found our framework but wants to us the result as if it was created via `carthage build`, which is not what we want, since we want to build it with xcode directly.
In order to fix it, we need to tell xcode to find the framework into the build directory for the current workspace (As everything built as part of the workspace goes into the same folder). This folder changes for every project/workspace, and is indicated by the xcodebuild environment variable `BUILT_PRODUCTS_DIR`.
However, there is something else that needs to be taken into account: the frameworks will be built in only 2 different built folder path, depending on which scheme they're being built is either `Debug` (Which corresponds to our `Debug` scheme) or `Release` (Which corresponds to all the other schemes, `Snapshot`, `Staging`, `Release` and `Production`). Our project will be built into a specific built folder path for each scheme. The `WORKSPACE_FRAMEWORK_BUILT_PRODUCTS_DIR` environment solves that issue by pointing to `Debug` built folder path in the `Debug` scheme, and to the `Release` built folder path in all other schemes, allowing to correctly reference the built frameworks for each scheme.
What we need to do then is this: change `sourceTree` so that it's relative to `WORKSPACE_FRAMEWORK_BUILT_PRODUCTS_DIR`, and change the path so it's just the name of the framework. In our example, the line becomes:

```
F43F75DA1B9F05C200954745 /* EthanolSocial.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = EthanolSocial.framework; path = EthanolSocial.framework; sourceTree = WORKSPACE_FRAMEWORK_BUILT_PRODUCTS_DIR; };
```

You can then save the file and the project should run and compile fine.

7. Last step, is to remove a parameter that xcode automatically adds when adding frameworks this way, and that creates a warning on compilation if left as-is. The parameter  can be found in the `Build Settings` tab, and is called `Framework Search Paths`. To remove the parameter, make sure you select the target, then highlight it, and hit the remove key on your keyboard. This should change the parameter from being bold to normal.

## License

[Name] is available under the MIT license. See the LICENSE file for more info.


text:
Ext.ns('MMD');

MMD.Store = function(root, id, columns, config) {
	var config = config || {};
	Ext.applyIf(config, {
    reader: new Ext.data.JsonReader(
      {
        root: root,
        idProperty: id,
        totalProperty: 'total_entries'
      },
      columns)
	});
	// call the superclass's constructor
	MMD.Store.superclass.constructor.call(this, config);
};
Ext.extend(MMD.Store, Ext.data.Store);


text:
package com.ansorgit.plugins.bash.editor.codecompletion;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.TreeSet;

import jakarta.inject.Singleton;

import com.intellij.openapi.application.ApplicationManager;

/**
 * Implements cached lookup of the global commands which are available in the configured paths of $PATH.
 *
 * @author jansorg
 */
@Singleton
public class BashPathCommandCompletion
{
	public static BashPathCommandCompletion getInstance()
	{
		return ApplicationManager.getApplication().getComponent(BashPathCommandCompletion.class);
	}

	//may only be modified in the initComponent method, because it's not serialzed
	private final TreeSet<String> cachedCommands = new TreeSet<String>();

	public BashPathCommandCompletion()
	{
		String envPath = System.getenv("PATH");
		if(envPath != null)
		{
			String[] split = envPath.split(":");
			if(split != null)
			{
				//fixme better do this in a background task?
				for(String path : Arrays.asList(split))
				{
					File dir = new File(path);
					if(dir.exists() && dir.isDirectory())
					{
						File[] commands = dir.listFiles(new ExecutableFileFilter());

						for(File command : commands)
						{
							cachedCommands.add(command.getName());
						}
					}
				}
			}
		}
	}

	public Iterable<String> findCommands(String commandPrefix)
	{
		return cachedCommands.subSet(commandPrefix, findUpperLimit(commandPrefix));
	}

	/**
	 * Find the upper limit of the TreeSet map lookup. E.g. "git" has a upper lookup limit of "giu" (exclusive).
	 *
	 * @param prefix The prefix which should be used to retrieve all keys which start with this value
	 * @return The key to use for the upper limit l
	 */
	protected String findUpperLimit(String prefix)
	{
		if(prefix.isEmpty())
		{
			return "z";
		}

		if(prefix.length() == 1)
		{
			char c = prefix.charAt(0);
			return c < 'z' ? Character.toString((char) (c + 1)) : "z";
		}

		//change the last character to 'z' to create the lookup range
		//if it already is 'z' then cut it of and call again with the substring
		char lastChar = prefix.charAt(prefix.length() - 1);
		if(lastChar < 'z')
		{
			return prefix.substring(0, prefix.length() - 1) + Character.toString((char) (lastChar + 1));
		}

		return findUpperLimit(prefix.substring(0, prefix.length() - 1));
	}

	private static final class ExecutableFileFilter implements FileFilter
	{
		ExecutableFileFilter()
		{
		}

		@Override
		public boolean accept(File file)
		{
			return file.isFile() && file.canExecute() && file.canRead();
		}
	}
}


text:
package org.apache.spark.network.util;

/**
 * A central location that tracks all the settings we expose to users.
 */
public class TransportConf {
  private final ConfigProvider conf;

  public TransportConf(ConfigProvider conf) {
    this.conf = conf;
  }

  /** IO mode: nio or epoll */
  public String ioMode() { return conf.get("spark.shuffle.io.mode", "NIO").toUpperCase(); }

  /** If true, we will prefer allocating off-heap byte buffers within Netty. */
  public boolean preferDirectBufs() {
    return conf.getBoolean("spark.shuffle.io.preferDirectBufs", true);
  }

  /** Connect timeout in milliseconds. Default 120 secs. */
  public int connectionTimeoutMs() {
    int defaultTimeout = conf.getInt("spark.network.timeout", 120);
    return conf.getInt("spark.shuffle.io.connectionTimeout", defaultTimeout) * 1000;
  }

  /** Number of concurrent connections between two nodes for fetching data. */
  public int numConnectionsPerPeer() {
    return conf.getInt("spark.shuffle.io.numConnectionsPerPeer", 1);
  }

  /** Requested maximum length of the queue of incoming connections. Default -1 for no backlog. */
  public int backLog() { return conf.getInt("spark.shuffle.io.backLog", -1); }

  /** Number of threads used in the server thread pool. Default to 0, which is 2x#cores. */
  public int serverThreads() { return conf.getInt("spark.shuffle.io.serverThreads", 0); }

  /** Number of threads used in the client thread pool. Default to 0, which is 2x#cores. */
  public int clientThreads() { return conf.getInt("spark.shuffle.io.clientThreads", 0); }

  /**
   * Receive buffer size (SO_RCVBUF).
   * Note: the optimal size for receive buffer and send buffer should be
   *  latency * network_bandwidth.
   * Assuming latency = 1ms, network_bandwidth = 10Gbps
   *  buffer size should be ~ 1.25MB
   */
  public int receiveBuf() { return conf.getInt("spark.shuffle.io.receiveBuffer", -1); }

  /** Send buffer size (SO_SNDBUF). */
  public int sendBuf() { return conf.getInt("spark.shuffle.io.sendBuffer", -1); }

  /** Timeout for a single round trip of SASL token exchange, in milliseconds. */
  public int saslRTTimeoutMs() { return conf.getInt("spark.shuffle.sasl.timeout", 30) * 1000; }

  /**
   * Max number of times we will try IO exceptions (such as connection timeouts) per request.
   * If set to 0, we will not do any retries.
   */
  public int maxIORetries() { return conf.getInt("spark.shuffle.io.maxRetries", 3); }

  /**
   * Time (in milliseconds) that we will wait in order to perform a retry after an IOException.
   * Only relevant if maxIORetries > 0.
   */
  public int ioRetryWaitTimeMs() { return conf.getInt("spark.shuffle.io.retryWait", 5) * 1000; }

  /**
   * Minimum size of a block that we should start using memory map rather than reading in through
   * normal IO operations. This prevents Spark from memory mapping very small blocks. In general,
   * memory mapping has high overhead for blocks close to or below the page size of the OS.
   */
  public int memoryMapBytes() {
    return conf.getInt("spark.storage.memoryMapThreshold", 2 * 1024 * 1024);
  }

  /**
   * Whether to initialize shuffle FileDescriptor lazily or not. If true, file descriptors are
   * created only when data is going to be transferred. This can reduce the number of open files.
   */
  public boolean lazyFileDescriptor() {
    return conf.getBoolean("spark.shuffle.io.lazyFD", true);
  }

  /**
   * Maximum number of retries when binding to a port before giving up.
   */
  public int portMaxRetries() {
    return conf.getInt("spark.port.maxRetries", 16);
  }
}


text:
package com.tutorialspoint.hibernate.pojo;

public class Account implements java.io.Serializable {

	private int id;
	private String description;

	public Account() {
	}

	public Account(String description) {
		this.description = description;
	}

	public int getId() {
		return id;
	}

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

	public String getDescription() {
		return description;
	}

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

}


text:
cask 'double-commander' do
  version '0.7.2-6850'
  sha256 'ab2604af151e50e133d7af423a4008dd27de699e759231608f3f00f696269118'

  url "http://downloads.sourceforge.net/sourceforge/doublecmd/doublecmd-#{version}.qt.x86_64.dmg"
  name 'Double Commander'
  homepage 'http://doublecmd.sourceforge.net/'
  license :gpl

  app 'Double Commander.app'
end


text:
class ApplicationController < ActionController::Base

  protect_from_forgery with: :exception

  helper_method :user
  helper_method :authenticated?

private

  def user
    cookie = cookies.signed[:user]
    @_user ||= User.find(cookie) rescue deauthenticate if cookie
  end

  def authenticate(user)
    cookies.permanent.signed[:user] = user.id
  end

  def deauthenticate
    cookies.delete :user
  end

  def authenticated?
    user.present?
  end

  def authenticate!
    unless authenticated?
      store
      flash[:warning] = 'You must be logged in.'
      respond_to do |format|
        format.html { redirect_to new_user_path }
      end
      return false
    end
  end

  def deauthenticate!
    if authenticated?
      store
      flash[:warning] = 'You must be logged out.'
      respond_to do |format|
        format.html { redirect_to edit_user_path }
      end
      return false
    end
  end

  def store
    session[:location] = request.fullpath
  end

  def restore(options)
    location = session[:location] || options[:default]
    session[:location] = nil
    return location
  end

end


text:
from setuptools import setup, find_packages

setup(name='py_particle_processor',
      version='0.1.3',
      description='a GUI application to generate or load and export particle data for beam physics',
      url='https://github.com/DanielWinklehner/py_particle_processor',
      author='Daniel Winklehner, Philip Weigel, Maria Yampolskaya',
      author_email='winklehn@mit.edu',
      license='MIT',
      packages=find_packages(),
      package_data={'': ['mainwindow.py', 'propertieswindow.py']},
      include_package_data=True,
      zip_safe=False)


text:
package deviceplugin

import (
	"flag"
	"fmt"
	"reflect"
	"testing"

	"github.com/stretchr/testify/assert"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/apimachinery/pkg/util/uuid"
	pluginapi "k8s.io/kubernetes/pkg/kubelet/apis/deviceplugin/v1alpha"
	"k8s.io/kubernetes/pkg/kubelet/lifecycle"
	"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
)

func TestUpdateCapacity(t *testing.T) {
	var expected = v1.ResourceList{}
	as := assert.New(t)
	verifyCapacityFunc := func(updates v1.ResourceList) {
		as.Equal(expected, updates)
	}
	testHandler, err := NewHandlerImpl(verifyCapacityFunc)
	as.NotNil(testHandler)
	as.Nil(err)

	devs := []pluginapi.Device{
		{ID: "Device1", Health: pluginapi.Healthy},
		{ID: "Device2", Health: pluginapi.Healthy},
		{ID: "Device3", Health: pluginapi.Unhealthy},
	}

	resourceName := "resource1"
	// Adds three devices for resource1, two healthy and one unhealthy.
	// Expects capacity for resource1 to be 2.
	expected[v1.ResourceName(resourceName)] = *resource.NewQuantity(int64(2), resource.DecimalSI)
	testHandler.devicePluginManagerMonitorCallback(resourceName, devs, []pluginapi.Device{}, []pluginapi.Device{})
	// Deletes an unhealthy device should NOT change capacity.
	testHandler.devicePluginManagerMonitorCallback(resourceName, []pluginapi.Device{}, []pluginapi.Device{}, []pluginapi.Device{devs[2]})
	// Updates a healthy device to unhealthy should reduce capacity by 1.
	expected[v1.ResourceName(resourceName)] = *resource.NewQuantity(int64(1), resource.DecimalSI)
	// Deletes a healthy device should reduce capacity by 1.
	expected[v1.ResourceName(resourceName)] = *resource.NewQuantity(int64(0), resource.DecimalSI)
	// Tests adding another resource.
	delete(expected, v1.ResourceName(resourceName))
	resourceName2 := "resource2"
	expected[v1.ResourceName(resourceName2)] = *resource.NewQuantity(int64(2), resource.DecimalSI)
	testHandler.devicePluginManagerMonitorCallback(resourceName2, devs, []pluginapi.Device{}, []pluginapi.Device{})
}

type stringPairType struct {
	value1 string
	value2 string
}

// DevicePluginManager stub to test device Allocation behavior.
type DevicePluginManagerTestStub struct {
	// All data structs are keyed by resourceName+DevId
	devRuntimeDevices map[string][]stringPairType
	devRuntimeMounts  map[string][]stringPairType
	devRuntimeEnvs    map[string][]stringPairType
}

func NewDevicePluginManagerTestStub() (*DevicePluginManagerTestStub, error) {
	return &DevicePluginManagerTestStub{
		devRuntimeDevices: make(map[string][]stringPairType),
		devRuntimeMounts:  make(map[string][]stringPairType),
		devRuntimeEnvs:    make(map[string][]stringPairType),
	}, nil
}

func (m *DevicePluginManagerTestStub) Start() error {
	return nil
}

func (m *DevicePluginManagerTestStub) Devices() map[string][]pluginapi.Device {
	return make(map[string][]pluginapi.Device)
}

func (m *DevicePluginManagerTestStub) Allocate(resourceName string, devIds []string) (*pluginapi.AllocateResponse, error) {
	resp := new(pluginapi.AllocateResponse)
	resp.Envs = make(map[string]string)
	for _, id := range devIds {
		key := resourceName + id
		fmt.Printf("Alloc device %v for resource %v\n", id, resourceName)
		for _, dev := range m.devRuntimeDevices[key] {
			fmt.Printf("Add dev %v %v\n", dev.value1, dev.value2)
			resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
				ContainerPath: dev.value1,
				HostPath:      dev.value2,
				Permissions:   "mrw",
			})
		}
		for _, mount := range m.devRuntimeMounts[key] {
			fmt.Printf("Add mount %v %v\n", mount.value1, mount.value2)
			resp.Mounts = append(resp.Mounts, &pluginapi.Mount{
				ContainerPath: mount.value1,
				HostPath:      mount.value2,
				ReadOnly:      true,
			})
		}
		for _, env := range m.devRuntimeEnvs[key] {
			fmt.Printf("Add env %v %v\n", env.value1, env.value2)
			resp.Envs[env.value1] = env.value2
		}
	}
	return resp, nil
}

func (m *DevicePluginManagerTestStub) Stop() error {
	return nil
}

func (m *DevicePluginManagerTestStub) CheckpointFile() string {
	return "/tmp/device-plugin-checkpoint"
}

func constructDevices(devices []string) sets.String {
	ret := sets.NewString()
	for _, dev := range devices {
		ret.Insert(dev)
	}
	return ret
}

func constructAllocResp(devices, mounts, envs map[string]string) *pluginapi.AllocateResponse {
	resp := &pluginapi.AllocateResponse{}
	for k, v := range devices {
		resp.Devices = append(resp.Devices, &pluginapi.DeviceSpec{
			HostPath:      k,
			ContainerPath: v,
			Permissions:   "mrw",
		})
	}
	for k, v := range mounts {
		resp.Mounts = append(resp.Mounts, &pluginapi.Mount{
			ContainerPath: k,
			HostPath:      v,
			ReadOnly:      true,
		})
	}
	resp.Envs = make(map[string]string)
	for k, v := range envs {
		resp.Envs[k] = v
	}
	return resp
}

func TestCheckpoint(t *testing.T) {
	resourceName1 := "domain1.com/resource1"
	resourceName2 := "domain2.com/resource2"

	m, err := NewDevicePluginManagerTestStub()
	as := assert.New(t)
	as.Nil(err)

	testHandler := &HandlerImpl{
		devicePluginManager: m,
		allDevices:          make(map[string]sets.String),
		allocatedDevices:    make(map[string]sets.String),
		podDevices:          make(podDevices),
	}

	testHandler.podDevices.insert("pod1", "con1", resourceName1,
		constructDevices([]string{"dev1", "dev2"}),
		constructAllocResp(map[string]string{"/dev/r1dev1": "/dev/r1dev1", "/dev/r1dev2": "/dev/r1dev2"},
			map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))
	testHandler.podDevices.insert("pod1", "con1", resourceName2,
		constructDevices([]string{"dev1", "dev2"}),
		constructAllocResp(map[string]string{"/dev/r2dev1": "/dev/r2dev1", "/dev/r2dev2": "/dev/r2dev2"},
			map[string]string{"/home/r2lib1": "/usr/r2lib1"},
			map[string]string{"r2devices": "dev1 dev2"}))
	testHandler.podDevices.insert("pod1", "con2", resourceName1,
		constructDevices([]string{"dev3"}),
		constructAllocResp(map[string]string{"/dev/r1dev3": "/dev/r1dev3"},
			map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))
	testHandler.podDevices.insert("pod2", "con1", resourceName1,
		constructDevices([]string{"dev4"}),
		constructAllocResp(map[string]string{"/dev/r1dev4": "/dev/r1dev4"},
			map[string]string{"/home/r1lib1": "/usr/r1lib1"}, map[string]string{}))

	expectedPodDevices := testHandler.podDevices
	expectedAllocatedDevices := testHandler.podDevices.devices()

	err = testHandler.writeCheckpoint()
	as.Nil(err)
	testHandler.podDevices = make(podDevices)
	err = testHandler.readCheckpoint()
	as.Nil(err)

	as.Equal(len(expectedPodDevices), len(testHandler.podDevices))
	for podUID, containerDevices := range expectedPodDevices {
		for conName, resources := range containerDevices {
			for resource := range resources {
				as.True(reflect.DeepEqual(
					expectedPodDevices.containerDevices(podUID, conName, resource),
					testHandler.podDevices.containerDevices(podUID, conName, resource)))
				opts1 := expectedPodDevices.deviceRunContainerOptions(podUID, conName)
				opts2 := testHandler.podDevices.deviceRunContainerOptions(podUID, conName)
				as.Equal(len(opts1.Envs), len(opts2.Envs))
				as.Equal(len(opts1.Mounts), len(opts2.Mounts))
				as.Equal(len(opts1.Devices), len(opts2.Devices))
			}
		}
	}
	as.True(reflect.DeepEqual(expectedAllocatedDevices, testHandler.allocatedDevices))
}

type activePodsStub struct {
	activePods []*v1.Pod
}

func (a *activePodsStub) getActivePods() []*v1.Pod {
	return a.activePods
}

func (a *activePodsStub) updateActivePods(newPods []*v1.Pod) {
	a.activePods = newPods
}

func TestPodContainerDeviceAllocation(t *testing.T) {
	flag.Set("alsologtostderr", fmt.Sprintf("%t", true))
	var logLevel string
	flag.StringVar(&logLevel, "logLevel", "4", "test")
	flag.Lookup("v").Value.Set(logLevel)

	resourceName1 := "domain1.com/resource1"
	resourceQuantity1 := *resource.NewQuantity(int64(2), resource.DecimalSI)
	devID1 := "dev1"
	devID2 := "dev2"
	resourceName2 := "domain2.com/resource2"
	resourceQuantity2 := *resource.NewQuantity(int64(1), resource.DecimalSI)
	devID3 := "dev3"
	devID4 := "dev4"

	m, err := NewDevicePluginManagerTestStub()
	as := assert.New(t)
	as.Nil(err)
	monitorCallback := func(resourceName string, added, updated, deleted []pluginapi.Device) {}
	podsStub := activePodsStub{
		activePods: []*v1.Pod{},
	}
	cachedNode := &v1.Node{
		Status: v1.NodeStatus{
			Allocatable: v1.ResourceList{},
		},
	}
	nodeInfo := &schedulercache.NodeInfo{}
	nodeInfo.SetNode(cachedNode)

	testHandler := &HandlerImpl{
		devicePluginManager:                m,
		devicePluginManagerMonitorCallback: monitorCallback,
		allDevices:                         make(map[string]sets.String),
		allocatedDevices:                   make(map[string]sets.String),
		podDevices:                         make(podDevices),
		activePods:                         podsStub.getActivePods,
	}
	testHandler.allDevices[resourceName1] = sets.NewString()
	testHandler.allDevices[resourceName1].Insert(devID1)
	testHandler.allDevices[resourceName1].Insert(devID2)
	testHandler.allDevices[resourceName2] = sets.NewString()
	testHandler.allDevices[resourceName2].Insert(devID3)
	testHandler.allDevices[resourceName2].Insert(devID4)

	m.devRuntimeDevices[resourceName1+devID1] = append(m.devRuntimeDevices[resourceName1+devID1], stringPairType{"/dev/aaa", "/dev/aaa"})
	m.devRuntimeDevices[resourceName1+devID1] = append(m.devRuntimeDevices[resourceName1+devID1], stringPairType{"/dev/bbb", "/dev/bbb"})
	m.devRuntimeDevices[resourceName1+devID2] = append(m.devRuntimeDevices[resourceName1+devID2], stringPairType{"/dev/ccc", "/dev/ccc"})
	m.devRuntimeMounts[resourceName1+devID1] = append(m.devRuntimeMounts[resourceName1+devID1], stringPairType{"/container_dir1/file1", "host_dir1/file1"})
	m.devRuntimeMounts[resourceName1+devID2] = append(m.devRuntimeMounts[resourceName1+devID2], stringPairType{"/container_dir1/file2", "host_dir1/file2"})
	m.devRuntimeEnvs[resourceName1+devID2] = append(m.devRuntimeEnvs[resourceName1+devID2], stringPairType{"key1", "val1"})
	m.devRuntimeEnvs[resourceName2+devID3] = append(m.devRuntimeEnvs[resourceName2+devID3], stringPairType{"key2", "val2"})
	m.devRuntimeEnvs[resourceName2+devID4] = append(m.devRuntimeEnvs[resourceName2+devID4], stringPairType{"key2", "val3"})

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			UID: uuid.NewUUID(),
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name: string(uuid.NewUUID()),
					Resources: v1.ResourceRequirements{
						Limits: v1.ResourceList{
							v1.ResourceName(resourceName1): resourceQuantity1,
							v1.ResourceName("cpu"):         resourceQuantity1,
							v1.ResourceName(resourceName2): resourceQuantity2,
						},
					},
				},
			},
		},
	}

	podsStub.updateActivePods([]*v1.Pod{pod})
	err = testHandler.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: pod})
	as.Nil(err)
	runContainerOpts := testHandler.GetDeviceRunContainerOptions(pod, &pod.Spec.Containers[0])
	as.Equal(len(runContainerOpts.Devices), 3)
	as.Equal(len(runContainerOpts.Mounts), 2)
	as.Equal(len(runContainerOpts.Envs), 2)

	// Requesting to create a pod without enough resources should fail.
	as.Equal(2, testHandler.allocatedDevices[resourceName1].Len())
	failPod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			UID: uuid.NewUUID(),
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name: string(uuid.NewUUID()),
					Resources: v1.ResourceRequirements{
						Limits: v1.ResourceList{
							v1.ResourceName(resourceName1): resourceQuantity2,
						},
					},
				},
			},
		},
	}
	err = testHandler.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: failPod})
	as.NotNil(err)
	runContainerOpts2 := testHandler.GetDeviceRunContainerOptions(failPod, &failPod.Spec.Containers[0])
	as.Nil(runContainerOpts2)

	// Requesting to create a new pod with a single resourceName2 should succeed.
	newPod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			UID: uuid.NewUUID(),
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name: string(uuid.NewUUID()),
					Resources: v1.ResourceRequirements{
						Limits: v1.ResourceList{
							v1.ResourceName(resourceName2): resourceQuantity2,
						},
					},
				},
			},
		},
	}
	err = testHandler.Allocate(nodeInfo, &lifecycle.PodAdmitAttributes{Pod: newPod})
	as.Nil(err)
	runContainerOpts3 := testHandler.GetDeviceRunContainerOptions(newPod, &newPod.Spec.Containers[0])
	as.Equal(1, len(runContainerOpts3.Envs))
}

func TestSanitizeNodeAllocatable(t *testing.T) {
	resourceName1 := "domain1.com/resource1"
	devID1 := "dev1"

	resourceName2 := "domain2.com/resource2"
	devID2 := "dev2"

	m, err := NewDevicePluginManagerTestStub()
	as := assert.New(t)
	as.Nil(err)
	monitorCallback := func(resourceName string, added, updated, deleted []pluginapi.Device) {}

	testHandler := &HandlerImpl{
		devicePluginManager:                m,
		devicePluginManagerMonitorCallback: monitorCallback,
		allDevices:                         make(map[string]sets.String),
		allocatedDevices:                   make(map[string]sets.String),
		podDevices:                         make(podDevices),
	}
	// require one of resource1 and one of resource2
	testHandler.allocatedDevices[resourceName1] = sets.NewString()
	testHandler.allocatedDevices[resourceName1].Insert(devID1)
	testHandler.allocatedDevices[resourceName2] = sets.NewString()
	testHandler.allocatedDevices[resourceName2].Insert(devID2)

	cachedNode := &v1.Node{
		Status: v1.NodeStatus{
			Allocatable: v1.ResourceList{
				// has no resource1 and two of resource2
				v1.ResourceName(resourceName2): *resource.NewQuantity(int64(2), resource.DecimalSI),
			},
		},
	}
	nodeInfo := &schedulercache.NodeInfo{}
	nodeInfo.SetNode(cachedNode)

	testHandler.sanitizeNodeAllocatable(nodeInfo)

	allocatableScalarResources := nodeInfo.AllocatableResource().ScalarResources
	// allocatable in nodeInfo is less than needed, should update
	as.Equal(1, int(allocatableScalarResources[v1.ResourceName(resourceName1)]))
	// allocatable in nodeInfo is more than needed, should skip updating
	as.Equal(2, int(allocatableScalarResources[v1.ResourceName(resourceName2)]))
}


text:
var CryptoJS = require("crypto-js");
var AES = require("crypto-js/aes");
var SHA256 = require("crypto-js/sha256");
var key = process.env["ENCRYPT_KEY"];
var _ = require('ramda');

function aesDecrypt(string,key){
  var decrypted = AES.decrypt(string, key);
  var decryptedString = CryptoJS.enc.Utf8.stringify(decrypted);
  return decryptedString;
}

function aesEncrypt(string,key){
  var encrypted = AES.encrypt(string,key);
  var encryptedString = encrypted.toString();
  return encryptedString;
}

module.exports.decrypt = _.curry(aesDecrypt)(_.__, key);
module.exports.encrypt = _.curry(aesEncrypt)(_.__, key);


text:
package m10f.lipgen.grammar.symbol;

public class Tagged<T extends Symbol> implements Symbol {
    private final T sub;
    private final String tag;

    public Tagged(T sub, String tag) {
        this.sub = sub;
        this.tag = tag;
    }

    @Override
    public String getName() {
        return sub.getName();
    }

    @Override
    public String getTag() {
        return tag;
    }

    public T getTarget() {
        return sub;
    }

    @Override
    public boolean equals(Object o) {
        if(!(o instanceof Symbol))
            return false;
        return ((Symbol) o).getName() == getName();
    }

    @Override
    public int hashCode() {
        return getName().hashCode();
    }
}


text:
<?php

namespace Tekkl\Bundle\BatchProcessingBundle\Exception;

class BatchjobRescheduledException extends \RuntimeException {

}


text:
layout: page
title: Stone Dragon Trade Dinner
date: 2016-05-24
author: Douglas Wright
tags: weekly links, java
status: published
summary: Praesent volutpat libero nunc, eu interdum nisl vestibulum.
banner: images/banner/wedding.jpg
booking:
  startDate: 07/14/2016
  endDate: 07/17/2016
  ctyhocn: HOUSXHX
  groupCode: SDTD
published: true
---
Vestibulum vehicula vel risus efficitur vehicula. Mauris eget mattis erat, non mollis leo. Maecenas id metus nisi. Morbi ac ipsum enim. Aenean sit amet eleifend mi. Donec non ligula quam. Etiam quis urna iaculis, venenatis velit vitae, interdum sem. In in massa rutrum, commodo nibh ut, consectetur dolor. Morbi mattis dignissim vestibulum. Phasellus scelerisque arcu augue, non elementum arcu blandit a.

* Quisque ultricies ligula eget ante elementum pellentesque
* Nullam porta tortor et massa volutpat molestie
* Vestibulum venenatis turpis nec quam interdum, nec mollis sem accumsan
* Donec nec magna ut tellus hendrerit ultricies
* Donec vel turpis id mauris vehicula dignissim vel id nunc
* Cras ultricies nisl eget auctor porttitor.

Suspendisse vel urna enim. Etiam et dolor augue. Praesent posuere quam non volutpat feugiat. Etiam vel ligula molestie neque luctus interdum. Aenean volutpat magna vitae ipsum dictum mollis. Cras nec risus mattis ipsum mollis auctor vel tempus arcu. Suspendisse porta mauris ut nulla auctor iaculis. Maecenas quis dui libero. In malesuada justo eleifend, congue ante id, ornare tortor. Aliquam at tincidunt augue. Aliquam erat volutpat. Praesent a neque fermentum, dignissim nisl eget, mattis nibh. Nullam eros orci, tincidunt sed neque a, dignissim consequat sapien. Phasellus gravida arcu orci, nec malesuada libero semper et. Vivamus feugiat, augue nec feugiat sagittis, massa lorem bibendum mauris, id finibus mauris augue et mauris. Sed risus dui, bibendum ut condimentum et, suscipit eget dolor.


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.creationgroundmedia.twitternator.activities.TimelineActivity">

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:id="@+id/rvTweets"
            tools:listitem="@layout/activity_timeline_item" />
    </android.support.v4.widget.SwipeRefreshLayout>

</FrameLayout>


text:
@interface UISSFloatValueConverterTests : SenTestCase

@property(nonatomic, strong) UISSFloatValueConverter *converter;

@end

@implementation UISSFloatValueConverterTests

- (void)setUp; {
    self.converter = [[UISSFloatValueConverter alloc] init];
    self.converter.precision = 4;
}

- (void)tearDown; {
    self.converter = nil;
}

- (void)testConversionFromNumber; {
    id value = [self.converter convertValue:@0.5f];
    STAssertTrue([value isKindOfClass:[NSValue class]], nil);

    CGFloat floatValue = 0;
    [value getValue:&floatValue];

    STAssertEquals(floatValue, 0.5f, nil);
}

- (void)testGeneratedCodeFromString; {
    STAssertEqualObjects([self.converter generateCodeForValue:@"1.123"], @"1.1230", nil);
}

- (void)testGeneratedCodeFromNumber; {
    STAssertEqualObjects([self.converter generateCodeForValue:[NSNumber numberWithFloat:1.123]], @"1.1230", nil);
}

@end


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Service\HubServiceInterface;

/**
 * Description of Roundup2018Controller
 *
 * @author Alexander
 */
class Roundup2018Controller extends AbstractActionController
{
    /**
     *
     * @var HubServiceInterface
     */
    protected $services;

    public function __construct(HubServiceInterface $hubService)
    {
        $this->services = $hubService;
    }

    public function usersAction()
    {
        $reader = new \Zend\Config\Reader\Json();
        $data = $reader->fromFile(getcwd().'/public/data/roundup/2018/users.json');
        return new ViewModel($data);
    }

    public function pagesAction()
    {
        $reader = new \Zend\Config\Reader\Json();
        $data = $reader->fromFile(getcwd().'/public/data/roundup/2018/pages.json');

        return new ViewModel($data);
    }
}


text:
"use strict";
//# sourceMappingURL=ValidationErrorInterface.js.map


text:
<button ng-click="ctrl.tableDisplayToggle.toggle()" id="table-toggle" class="btn btn-warning btn-xs">{{ctrl.tableDisplayToggle.buttonText}}</button>
table hidden
<input ng-hide="ctrl.tableDisplayToggle.isTableHidden" type="text" class="form-control" ng-model="ctrl.filterExpr" placeholder="Search">


text:
using BEPUutilities2.Memory;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace BEPUutilitiesTests
{
    public static class SpanCodeGenTests
    {

        [MethodImpl(MethodImplOptions.NoInlining)]
        static double Test<TSpan>(ref TSpan span, int iterations, out int accumulator) where TSpan : ISpan<int>
        {
            var start = Stopwatch.GetTimestamp();
            accumulator = 0;
            for (int i = 0; i < iterations; ++i)
            {
                for (int j =0; j < span.Length; ++j)
                {
                    if (span[j] * 73 == 1)
                        break;
                    else
                        span[j] = 0;
                }
                //for (int j = 10; j < span.Length; ++j)
                //{
                //    accumulator += span[j - 1] + span[j];
                //    accumulator += span[j - 2] + span[j];
                //    accumulator += span[j - 3] + span[j];
                //    accumulator += span[j - 4] + span[j];
                //    accumulator += span[j - 5] + span[j];
                //    accumulator += span[j - 6] + span[j];
                //    accumulator += span[j - 7] + span[j];
                //    accumulator += span[j - 8] + span[j];
                //    accumulator += span[j - 9] + span[j];
                //    accumulator += span[j - 10] + span[j];

                //}
            }

            return (Stopwatch.GetTimestamp() - start) / (double)Stopwatch.Frequency;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        unsafe static double RawPointerTest(int* span, int spanLength, int iterations, out int accumulator)
        {
            var start = Stopwatch.GetTimestamp();
            accumulator = 0;
            for (int i = 0; i < iterations; ++i)
            {
                for (int j = 0; j < spanLength; ++j)
                {
                    if (span[j] * 73 == 1)
                        break;
                    else
                        span[j] = 0;
                }
                //for (int j = 10; j < spanLength; ++j)
                //{
                //    accumulator += span[j - 1] + span[j];
                //    accumulator += span[j - 2] + span[j];
                //    accumulator += span[j - 3] + span[j];
                //    accumulator += span[j - 4] + span[j];
                //    accumulator += span[j - 5] + span[j];
                //    accumulator += span[j - 6] + span[j];
                //    accumulator += span[j - 7] + span[j];
                //    accumulator += span[j - 8] + span[j];
                //    accumulator += span[j - 9] + span[j];
                //    accumulator += span[j - 10] + span[j];

                //}
            }

            return (Stopwatch.GetTimestamp() - start) / (double)Stopwatch.Frequency;

        }
        public static unsafe void Test()
        {
            var array = new int[32];

            fixed (int* pointer = array)
            {
                Buffer<int> pSpan = new Buffer<int>(pointer, array.Length);
                Array<int> mSpan = new Array<int>(array);

                Console.WriteLine(
                    $"Warmup: {Test(ref pSpan, 1, out int accumulator)}," +
                    $" {Test(ref mSpan, 1, out accumulator)}" +
                    $" {RawPointerTest(pointer, array.Length, 1, out accumulator)}");
                const int iterations = 20000000;
                Console.WriteLine($"Pointer: {Test(ref pSpan, iterations, out accumulator)}");
                Console.WriteLine($"Managed: {Test(ref mSpan, iterations, out accumulator)}");

                Console.WriteLine($"Raw: {RawPointerTest(pointer, array.Length, iterations, out accumulator)}");
            }
        }
    }
}


text:
package com.rollbar.notifier.sender.queue;

import static java.util.Collections.emptyList;

import com.rollbar.api.payload.Payload;
import com.rollbar.notifier.util.ObjectsUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link Queue queue} of {@link Payload payloads} persisted on disk.
 */
public class DiskQueue extends AbstractQueue<Payload> {

  private static Logger LOGGER = LoggerFactory.getLogger(DiskQueue.class);

  private static final int UNBOUNDED_QUEUE = 0;

  private static final String QUEUE_FOLDER = ".rollbar-queue";

  private static final String FILENAME_SUFFIX = "payload";

  private static final String FILENAME_NAME_FORMAT = "%s.%s";

  private final File queueFolder;

  private final int maxSize;

  private DiskQueue(Builder builder) {
    this.maxSize = builder.maxSize;
    this.queueFolder = builder.queueFolder;

    if (!this.queueFolder.exists()) {
      if (!this.queueFolder.mkdirs()) {
        throw new RuntimeException("Could not create folder: " + queueFolder);
      }
    }

    if (!this.queueFolder.canRead() || !this.queueFolder.canWrite()) {
      throw new RuntimeException("Not enough permissions folder: " + queueFolder);
    }
  }

  @Override
  public Iterator<Payload> iterator() {
    return new PayloadIterator(getFiles().iterator());
  }

  @Override
  public int size() {
    return getFiles().size();
  }

  @Override
  public boolean offer(Payload payload) {
    if (isFull()) {
      return false;
    }

    writeToFile(payload);
    return true;
  }

  @Override
  public Payload poll() {
    return readFromFile(true);
  }

  @Override
  public Payload peek() {
    return readFromFile(false);
  }

  private void writeToFile(Payload payload) {
    ObjectOutputStream objectOut = null;
    File file = new File(queueFolder.getAbsolutePath(), createFilename(payload));
    try {
      objectOut = new ObjectOutputStream(new FileOutputStream(file));
      objectOut.writeObject(payload);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      ObjectsUtils.close(objectOut);
    }
  }

  private boolean isFull() {
    if (maxSize <= UNBOUNDED_QUEUE) {
      return false;
    }

    return size() >= maxSize;
  }

  private Payload readFromFile(boolean removeFile) {
    List<File> files = getFiles();

    if (files.size() > 0) {
      File eventFile = getFiles().get(0);

      return read(eventFile, removeFile);
    } else {
      return null;
    }
  }

  private List<File> getFiles() {
    File[] files = this.queueFolder.listFiles();

    if (files == null) {
      return emptyList();
    }

    List<File> payloads = new ArrayList<>();
    for (File file : files) {
      if (file.getName().endsWith(FILENAME_SUFFIX)) {
        payloads.add(file);
      }
    }

    return payloads;
  }

  private static String createFilename(Payload payload) {
    String uuid;
    if (payload.getData() != null && payload.getData().getUuid() != null) {
      uuid = payload.getData().getUuid();
    } else {
      uuid = UUID.randomUUID().toString();
    }
    return String.format(FILENAME_NAME_FORMAT, uuid, FILENAME_SUFFIX);
  }

  private static Payload read(File file, boolean remove) {
    ObjectInputStream objectInput = null;
    boolean error = false;

    try {
      objectInput = new ObjectInputStream(new FileInputStream(file));
      Object o = objectInput.readObject();

      return (Payload) o;
    } catch (Exception e) {
      error = true;
      throw new RuntimeException(e);
    } finally {
      // If some error happened discard the payload independently of remove flag.
      if (remove || error) {
        if (!file.delete()) {
          LOGGER.error("Can not delete the file: {}", file.getPath());
        }
      }
      ObjectsUtils.close(objectInput);
    }
  }

  /**
   * Builder class for {@link DiskQueue}.
   */
  public static final class Builder {

    private File queueFolder;

    private int maxSize;

    /**
     * Constructor.
     */
    public Builder() {
      this.maxSize = UNBOUNDED_QUEUE;
    }

    /**
     * The max size of the queue.
     * @param maxSize the max size.
     * @return the builder instance.
     */
    public Builder maxSize(int maxSize) {
      this.maxSize = maxSize;
      return this;
    }

    /**
     * The queue folder where persist the payloads.
     * @param queueFolder the queue folder.
     * @return the builder instance.
     */
    public Builder queueFolder(File queueFolder) {
      this.queueFolder = queueFolder;
      return this;
    }

    /**
     * Builds the {@link DiskQueue disk queue}.
     *
     * @return the disk queue.
     */
    public DiskQueue build() {
      if (this.queueFolder == null) {
        this.queueFolder = new File(QUEUE_FOLDER);
      }
      return new DiskQueue(this);
    }
  }

  static final class PayloadIterator implements Iterator<Payload> {

    private final Iterator<File> it;

    public PayloadIterator(Iterator<File> it) {
      this.it = it;
    }

    @Override
    public boolean hasNext() {
      return it.hasNext();
    }

    @Override
    public Payload next() {
      return read(it.next(), false);
    }

    @Override
    public void remove() {
      it.remove();
    }
  }
}


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */

package dev.test.namespace_from_package_without_module_name;

import com.facebook.thrift.type.TypeList;
import java.util.ArrayList;
import java.util.List;

public class __fbthrift_TypeList_e2067a44 implements TypeList {

  private static List<TypeMapping> list = new ArrayList<>();

  static {
    list.add(new TypeList.TypeMapping("test.dev/namespace_from_package_without_module_name/Foo", "dev.test.namespace_from_package_without_module_name.Foo"));
  }

  @java.lang.Override
  public List<TypeList.TypeMapping> getTypes() {
    return list;
  }
}


text:
using System.Threading.Tasks;

namespace LinqToDB.Interceptors
{
	public abstract class EntityServiceInterceptor : IEntityServiceInterceptor
	{
		public virtual object EntityCreated(EntityCreatedEventData eventData, object entity) => entity;
	}
}


text:
import {Animate} from "../../core/util/animate";
import {ElementRef, ViewEncapsulation, Component, Input, Output, EventEmitter} from "angular2/core";
import {DOM} from "angular2/src/platform/dom/dom_adapter";
import {ViewportHelper} from "../../core/util/viewport";

/**
 * An overlay for content on the page.
 * Can optionally dismiss when clicked on.
 * Has outputs for show/showing and hide/hiding.
 */
@Component({
  selector: 'md-backdrop',
  template: '',
  encapsulation: ViewEncapsulation.None,
  host: {
    'class': 'md-backdrop',
    '(click)': 'onClick()',
  },
})
export class MdBackdrop {

  /**
   * When true, clicking on the backdrop will close it
   */
  @Input()
  clickClose: boolean = false;

  /**
   * When true, disable the parent container scroll while the backdrop is active.
   */
  @Input()
  hideScroll: boolean = true;

  /**
   * Emits when the backdrop begins to hide.
   */
  @Output()
  onHiding: EventEmitter<MdBackdrop> = new EventEmitter<MdBackdrop>(false);

  /**
   * Emits when the backdrop has finished being hidden.
   */
  @Output()
  onHidden: EventEmitter<MdBackdrop> = new EventEmitter<MdBackdrop>(false);

  /**
   * Emits when the backdrop begins to be shown.
   */
  @Output()
  onShowing: EventEmitter<MdBackdrop> = new EventEmitter<MdBackdrop>();

  /**
   * Emits when the backdrop has finished being shown.
   */
  @Output()
  onShown: EventEmitter<MdBackdrop> = new EventEmitter<MdBackdrop>();

  constructor(public element: ElementRef, public viewport: ViewportHelper) {
    this._body = DOM.querySelector(viewport.getDocumentNativeElement(), 'body');
  }

  /**
   * The CSS class name to transition on/off when the backdrop is hidden/shown.
   */
  @Input()
  public transitionClass: string = 'md-active';

  /**
   * Whether to add the {@see transitionClass} or remove it when the backdrop is shown. The
   * opposite will happen when the backdrop is hidden.
   */
  @Input()
  public transitionAddClass = true;

  /**
   * Whether the backdrop is visible.
   */
  get visible(): boolean {
    return this._visible;
  }

  @Input()
  set visible(value: boolean) {
    this.toggle(value);
  }

  protected _visible: boolean = false;
  private _transitioning: boolean = false;
  private _previousOverflow: string = null;
  private _body: HTMLElement = null;

  onClick() {
    if (this.clickClose && !this._transitioning && this.visible) {
      this.hide();
    }
  }

  /**
   * Hide the backdrop and return a promise that is resolved when the hide animations are
   * complete.
   */
  hide(): Promise<any> {
    return this.toggle(false);
  }

  /**
   * Show the backdrop and return a promise that is resolved when the show animations are
   * complete.
   */
  show(): Promise<any> {
    return this.toggle(true);
  }

  /**
   * Toggle the visibility of the backdrop.
   * @param visible whether or not the backdrop should be visible
   * @returns {any}
   */
  toggle(visible: boolean = !this.visible): any {
    if (visible === this._visible) {
      return Promise.resolve();
    }

    let beginEvent = visible ? this.onShowing : this.onHiding;
    let endEvent = visible ? this.onShown : this.onHidden;

    this._visible = visible;
    this._transitioning = true;
    beginEvent.emit(this);
    let action = visible ?
      (this.transitionAddClass ? Animate.enter : Animate.leave) :
      (this.transitionAddClass ? Animate.leave : Animate.enter);

    // Page scroll
    if (visible && this.hideScroll && this.element && !this._previousOverflow) {
      let style = DOM.getStyle(this._body, 'overflow');
      if (style !== 'hidden') {
        this._previousOverflow = style;
        DOM.setStyle(this._body, 'overflow', 'hidden');
      }
    }
    else if (!visible && this.hideScroll && this.element && this._previousOverflow !== null) {
      DOM.setStyle(this._body, 'overflow', this._previousOverflow);
      this._previousOverflow = null;
    }

    // Animate transition class in/out and then finally emit the completed event.
    return action(this.element.nativeElement, this.transitionClass).then(() => {
      this._transitioning = false;
      endEvent.emit(this);
    });
  }
}


text:
function myFunction() {
	return this
}
console.log(myFunction())


text:
class WelcomeController < ApplicationController

require 'json'
require 'oembed'

	def youtube

		@video = OEmbed::Providers::Youtube.get("https://youtu.be/HkZDSqyE1do")

	end

	def create

	end

	def edit
	end

	def delete
	end

	def user
		@users = User.all

	end

end


text:
<?php

namespace TreeHouse\Anchor\Tests;

use Mockery\MockInterface;
use TreeHouse\Anchor\Anchor;
use TreeHouse\Anchor\Observer\ObserverInterface;
use TreeHouse\Anchor\Test\Event\TestEvent;
use TreeHouse\Anchor\Test\Observer\NullObserver;

class AnchorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function it_can_be_constructed_with_observers()
    {
        $observers = [
            new NullObserver(),
        ];

        $anchor = new Anchor($observers);

        $this->assertInstanceOf(Anchor::class, $anchor);
        $this->assertSame($observers, $anchor->getObservers());
    }

    /**
     * @test
     */
    public function it_can_add_observers()
    {
        $anchor = new Anchor();

        $this->assertEmpty($anchor->getObservers());

        $anchor->addObserver(new NullObserver());

        $this->assertNotEmpty($anchor->getObservers());
    }

    /**
     * @test
     * @expectedException \LogicException
     */
    public function it_throws_an_exception_for_invalid_observers()
    {
        new Anchor([$this]);
    }

    /**
     * @test
     */
    public function it_reports_to_specific_observers()
    {
        $event = new TestEvent('name', ['foo' => 'bar'], new \DateTime());

        /** @var ObserverInterface|MockInterface $observer1 */
        $observer1 = \Mockery::mock(ObserverInterface::class);
        $observer1->shouldReceive('observes')->once()->andReturn(false);
        $observer1->shouldNotReceive('observe');

        /** @var ObserverInterface|MockInterface $observer2 */
        $observer2 = \Mockery::mock(ObserverInterface::class);
        $observer2->shouldReceive('observes')->once()->andReturn(true);
        $observer2->shouldReceive('observe')->once()->with($event);

        $anchor = new Anchor([$observer1, $observer2]);
        $anchor->report($event);
    }
}


text:
package TeamF.jsonconnector.enums;

public enum Gender {
    MALE("m"),
    FEMALE("w");

    private String _value;

    private Gender(String value) {
        _value = value;
    }

    @Override
    public String toString() {
        return _value;
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Serialized Form</title>
<meta name="date" content="2017-05-10">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Serialized Form

Package Ventanas

Class Ventanas.AdministrativoHome extends javax.swing.JFrame implements Serializable

Serialized Fields

cf

CentroFormulario cf

cd

CentroDetalle cd

cl

CentroListado cl

tf

TrabajadorFormulario tf

td

TrabajadorDetalle td

tl

TrabajadorListado tl

dm

javax.swing.table.DefaultTableModel dm

avisos

java.util.ArrayList<E> avisos

t

Trabajador t

tp

TodosLosPartes tp

id

int id

jCheckBoxMenuItem2

javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem2

jCheckBoxMenuItem4

javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem4

jCheckBoxMenuItem5

javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem5

jMenu1

javax.swing.JMenu jMenu1

jMenu2

javax.swing.JMenu jMenu2

jMenu3

javax.swing.JMenu jMenu3

jMenuBar1

javax.swing.JMenuBar jMenuBar1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jSeparator1

javax.swing.JPopupMenu.Separator jSeparator1

jSeparator2

javax.swing.JPopupMenu.Separator jSeparator2

jTable1

javax.swing.JTable jTable1

jbBorrar

javax.swing.JButton jbBorrar

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jmDetalleUsu

javax.swing.JMenuItem jmDetalleUsu

jmListarTrab

javax.swing.JMenuItem jmListarTrab

jmNuevoCen

javax.swing.JMenuItem jmNuevoCen

jmNuevoTrab

javax.swing.JMenuItem jmNuevoTrab

jmNuevoUsu

javax.swing.JMenuItem jmNuevoUsu

jmTodos

javax.swing.JCheckBoxMenuItem jmTodos

jmTrabaCentro

javax.swing.JMenuItem jmTrabaCentro

Class Ventanas.BuscarCentro extends javax.swing.JFrame implements Serializable

Serialized Fields

model

javax.swing.table.DefaultTableModel model

tf

TrabajadorFormulario tf

tfe

TrabajadorFormularioEdit tfe

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

Class Ventanas.BuscarTrabajador extends javax.swing.JFrame implements Serializable

Serialized Fields

model

javax.swing.table.DefaultTableModel model

tp

TodosLosPartes tp

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

Class Ventanas.BuscarUsuario extends javax.swing.JFrame implements Serializable

Serialized Fields

model

javax.swing.table.DefaultTableModel model

tf

TrabajadorFormulario tf

tfe

TrabajadorFormularioEdit tfe

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

Class Ventanas.BuscarVehiculo extends javax.swing.JFrame implements Serializable

Serialized Fields

model

javax.swing.table.DefaultTableModel model

vp

VentanaParte vp

vpa

VentanaParteAdminis vpa

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

Class Ventanas.CentroDetalle extends javax.swing.JFrame implements Serializable

Serialized Fields

cl

CentroListado cl

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jlCP

javax.swing.JLabel jlCP

jlDireccion

javax.swing.JLabel jlDireccion

jlLocalidad

javax.swing.JLabel jlLocalidad

jlNombre

javax.swing.JLabel jlNombre

jlProvincia

javax.swing.JLabel jlProvincia

jlTelefono

javax.swing.JLabel jlTelefono

jltitulo

javax.swing.JLabel jltitulo

Class Ventanas.CentroFormulario extends javax.swing.JFrame implements Serializable

Serialized Fields

cl

CentroListado cl

cf

CentroFormulario cf

id

int id

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jPanel1

javax.swing.JPanel jPanel1

jbGuardar

javax.swing.JButton jbGuardar

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtCP

javax.swing.JTextField jtCP

jtDireccion

javax.swing.JTextField jtDireccion

jtLimpiar

javax.swing.JButton jtLimpiar

jtLocalidad

javax.swing.JTextField jtLocalidad

jtNombre

javax.swing.JTextField jtNombre

jtProvincia

javax.swing.JTextField jtProvincia

jtTelefono

javax.swing.JTextField jtTelefono

Class Ventanas.CentroFormularioEdit extends javax.swing.JFrame implements Serializable

Serialized Fields

cl

CentroListado cl

cf

CentroFormularioEdit cf

centro

Centro centro

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jPanel1

javax.swing.JPanel jPanel1

jbGuardar

javax.swing.JButton jbGuardar

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtCP

javax.swing.JTextField jtCP

jtDireccion

javax.swing.JTextField jtDireccion

jtLimpiar

javax.swing.JButton jtLimpiar

jtLocalidad

javax.swing.JTextField jtLocalidad

jtNombre

javax.swing.JTextField jtNombre

jtProvincia

javax.swing.JTextField jtProvincia

jtTelefono

javax.swing.JTextField jtTelefono

Class Ventanas.CentroListado extends javax.swing.JFrame implements Serializable

Serialized Fields

cfe

CentroFormularioEdit cfe

cd

CentroDetalle cd

model

javax.swing.table.DefaultTableModel model

modelTra

javax.swing.table.DefaultTableModel modelTra

centros

java.util.List<E> centros

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jScrollPane2

javax.swing.JScrollPane jScrollPane2

jTable1

javax.swing.JTable jTable1

jTable2

javax.swing.JTable jTable2

jbBorrar

javax.swing.JButton jbBorrar

jbDetalle

javax.swing.JButton jbDetalle

jbEditar

javax.swing.JButton jbEditar

jbTrabajadores

javax.swing.JButton jbTrabajadores

jltitulo

javax.swing.JLabel jltitulo

Class Ventanas.Login extends javax.swing.JFrame implements Serializable

Serialized Fields

ah

AdministrativoHome ah

vp

VentanaParte vp

us

Usuario us

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jPanel1

javax.swing.JPanel jPanel1

jPassword

javax.swing.JPasswordField jPassword

jbLogin

javax.swing.JButton jbLogin

jtUsuario

javax.swing.JTextField jtUsuario

Class Ventanas.TodosLosPartes extends javax.swing.JFrame implements Serializable

Serialized Fields

dm

javax.swing.table.DefaultTableModel dm

Creates new form TodosLosPartes

partes

java.util.ArrayList<E> partes

ah

AdministrativoHome ah

tLogin

Trabajador tLogin

tParte

Trabajador tParte

fecha

java.util.Date fecha

bt

BuscarTrabajador bt

p

Parte p

vp

VentanaParte vp

fila

int fila

id_trabajador

int id_trabajador

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel8

javax.swing.JLabel jLabel8

jPanel1

javax.swing.JPanel jPanel1

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

jbBorrar

javax.swing.JButton jbBorrar

jbBuscarTra

javax.swing.JButton jbBuscarTra

jbCrearAviso

javax.swing.JButton jbCrearAviso

jbFiltrarFecha

javax.swing.JButton jbFiltrarFecha

jbFiltrarFechaTra

javax.swing.JButton jbFiltrarFechaTra

jbModificar

javax.swing.JButton jbModificar

jbValidar

javax.swing.JButton jbValidar

jdFechaFinSolo

com.toedter.calendar.JDateChooser jdFechaFinSolo

jdFechaFinSolo2

com.toedter.calendar.JDateChooser jdFechaFinSolo2

jdFechaIniSolo

com.toedter.calendar.JDateChooser jdFechaIniSolo

jdFechaIniSolo2

com.toedter.calendar.JDateChooser jdFechaIniSolo2

jlAviso

javax.swing.JLabel jlAviso

jtTrabajador

javax.swing.JTextField jtTrabajador

Class Ventanas.TrabajadorDetalle extends javax.swing.JFrame implements Serializable

Serialized Fields

jLabel1

javax.swing.JLabel jLabel1

jLabel10

javax.swing.JLabel jLabel10

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel8

javax.swing.JLabel jLabel8

jLabel9

javax.swing.JLabel jLabel9

jlAp1

javax.swing.JLabel jlAp1

jlAp2

javax.swing.JLabel jlAp2

jlCategoria

javax.swing.JLabel jlCategoria

jlDireccion

javax.swing.JLabel jlDireccion

jlDni

javax.swing.JLabel jlDni

jlFecha

javax.swing.JLabel jlFecha

jlNombre

javax.swing.JLabel jlNombre

jlSalario

javax.swing.JLabel jlSalario

jlTelEmp

javax.swing.JLabel jlTelEmp

jlTelPer

javax.swing.JLabel jlTelPer

jltitulo

javax.swing.JLabel jltitulo

Class Ventanas.TrabajadorFormulario extends javax.swing.JFrame implements Serializable

Serialized Fields

centros

java.util.List<E> centros

bc

BuscarCentro bc

bu

BuscarUsuario bu

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel11

javax.swing.JLabel jLabel11

jLabel12

javax.swing.JLabel jLabel12

jLabel13

javax.swing.JLabel jLabel13

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel8

javax.swing.JLabel jLabel8

jLabel9

javax.swing.JLabel jLabel9

jbuscarboton

javax.swing.JButton jbuscarboton

jbuscarboton1

javax.swing.JButton jbuscarboton1

jcCategoria

javax.swing.JComboBox<E> jcCategoria

jidcentro

javax.swing.JTextField jidcentro

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtAp1

javax.swing.JTextField jtAp1

jtAp2

javax.swing.JTextField jtAp2

jtDireccion

javax.swing.JTextField jtDireccion

jtDni

javax.swing.JTextField jtDni

jtNombre

javax.swing.JTextField jtNombre

jtSalario

javax.swing.JTextField jtSalario

jtTelEmp

javax.swing.JTextField jtTelEmp

jtTelPer

javax.swing.JTextField jtTelPer

jtfechanacimiento

javax.swing.JTextField jtfechanacimiento

jusuario

javax.swing.JTextField jusuario

Class Ventanas.TrabajadorFormularioEdit extends javax.swing.JFrame implements Serializable

Serialized Fields

centros

java.util.List<E> centros

tra

Trabajador tra

bc

BuscarCentro bc

bu

BuscarUsuario bu

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel11

javax.swing.JLabel jLabel11

jLabel12

javax.swing.JLabel jLabel12

jLabel13

javax.swing.JLabel jLabel13

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel8

javax.swing.JLabel jLabel8

jLabel9

javax.swing.JLabel jLabel9

jbuscarboton

javax.swing.JButton jbuscarboton

jbuscarboton1

javax.swing.JButton jbuscarboton1

jcCategoria

javax.swing.JComboBox<E> jcCategoria

jidcentro

javax.swing.JTextField jidcentro

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtAp1

javax.swing.JTextField jtAp1

jtAp2

javax.swing.JTextField jtAp2

jtDireccion

javax.swing.JTextField jtDireccion

jtDni

javax.swing.JTextField jtDni

jtNombre

javax.swing.JTextField jtNombre

jtSalario

javax.swing.JTextField jtSalario

jtTelEmp

javax.swing.JTextField jtTelEmp

jtTelPer

javax.swing.JTextField jtTelPer

jtfechanacimiento

javax.swing.JTextField jtfechanacimiento

jusuario

javax.swing.JTextField jusuario

Class Ventanas.TrabajadorListado extends javax.swing.JFrame implements Serializable

Serialized Fields

td

TrabajadorDetalle td

tfe

TrabajadorFormularioEdit tfe

model

javax.swing.table.DefaultTableModel model

trabajadores

java.util.List<E> trabajadores

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

jbBorrar

javax.swing.JButton jbBorrar

jbDetalle

javax.swing.JButton jbDetalle

jbEditar

javax.swing.JButton jbEditar

jltitulo

javax.swing.JLabel jltitulo

Class Ventanas.UsuarioFormulario extends javax.swing.JFrame implements Serializable

Serialized Fields

ah

AdministrativoHome ah

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jcorrecto

javax.swing.JLabel jcorrecto

jguardarboton

javax.swing.JButton jguardarboton

jtcontra

javax.swing.JPasswordField jtcontra

jtusuario

javax.swing.JTextField jtusuario

Class Ventanas.VehiculoDetalle extends javax.swing.JFrame implements Serializable

Serialized Fields

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jMarca

javax.swing.JLabel jMarca

jModelo

javax.swing.JLabel jModelo

jltitulo

javax.swing.JLabel jltitulo

jmatricula

javax.swing.JLabel jmatricula

Class Ventanas.VehiculoFormulario extends javax.swing.JFrame implements Serializable

Serialized Fields

centros

java.util.List<E> centros

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtMarca

javax.swing.JTextField jtMarca

jtMatricula

javax.swing.JTextField jtMatricula

jtModelo

javax.swing.JTextField jtModelo

Class Ventanas.VehiculoFormularioEdit extends javax.swing.JFrame implements Serializable

Serialized Fields

v

Vehiculo v

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jlAviso

javax.swing.JLabel jlAviso

jltitulo

javax.swing.JLabel jltitulo

jtMarca

javax.swing.JTextField jtMarca

jtMatricula

javax.swing.JTextField jtMatricula

jtModelo

javax.swing.JTextField jtModelo

Class Ventanas.VehiculoListado extends javax.swing.JFrame implements Serializable

Serialized Fields

vd

VehiculoDetalle vd

vfe

VehiculoFormularioEdit vfe

model

javax.swing.table.DefaultTableModel model

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

jbBorrar

javax.swing.JButton jbBorrar

jbDetalle

javax.swing.JButton jbDetalle

jbEditar

javax.swing.JButton jbEditar

jltitulo

javax.swing.JLabel jltitulo

Class Ventanas.VentanaAviso extends javax.swing.JFrame implements Serializable

Serialized Fields

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jTable1

javax.swing.JTable jTable1

Class Ventanas.VentanaParte extends javax.swing.JFrame implements Serializable

Serialized Fields

vr

VentanaReparto vr

t

Trabajador t

p

Parte p

v

Vehiculo v

bv

BuscarVehiculo bv

id

int id

model

javax.swing.table.DefaultTableModel model

fila

int fila

repartos

java.util.List<E> repartos

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel10

javax.swing.JLabel jLabel10

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel9

javax.swing.JLabel jLabel9

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jScrollPane2

javax.swing.JScrollPane jScrollPane2

jTable1

javax.swing.JTable jTable1

jbBorrarRep

javax.swing.JButton jbBorrarRep

jbBuscar

javax.swing.JButton jbBuscar

jbCerrar

javax.swing.JButton jbCerrar

jbGuardar

javax.swing.JButton jbGuardar

jbUpdate

javax.swing.JButton jbUpdate

jbañadirRep

javax.swing.JButton jbañadirRep

jlAviso

javax.swing.JLabel jlAviso

jtAutopista

javax.swing.JTextField jtAutopista

jtDietas

javax.swing.JTextField jtDietas

jtGasoil

javax.swing.JTextField jtGasoil

jtIncidencias

javax.swing.JTextArea jtIncidencias

jtKmFin

javax.swing.JTextField jtKmFin

jtKmIni

javax.swing.JTextField jtKmIni

jtOtros

javax.swing.JTextField jtOtros

jtVehiculo

javax.swing.JTextField jtVehiculo

Class Ventanas.VentanaParteAdminis extends javax.swing.JFrame implements Serializable

Serialized Fields

vr

VentanaReparto vr

t

Trabajador t

p

Parte p

v

Vehiculo v

bv

BuscarVehiculo bv

id

int id

model

javax.swing.table.DefaultTableModel model

fila

int fila

repartos

java.util.List<E> repartos

jButton1

javax.swing.JButton jButton1

jLabel1

javax.swing.JLabel jLabel1

jLabel10

javax.swing.JLabel jLabel10

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jLabel5

javax.swing.JLabel jLabel5

jLabel6

javax.swing.JLabel jLabel6

jLabel7

javax.swing.JLabel jLabel7

jLabel9

javax.swing.JLabel jLabel9

jScrollPane1

javax.swing.JScrollPane jScrollPane1

jScrollPane2

javax.swing.JScrollPane jScrollPane2

jTable1

javax.swing.JTable jTable1

jbBorrarRep

javax.swing.JButton jbBorrarRep

jbBuscar

javax.swing.JButton jbBuscar

jbCerrar

javax.swing.JButton jbCerrar

jbGuardar

javax.swing.JButton jbGuardar

jbUpdate

javax.swing.JButton jbUpdate

jbañadirRep

javax.swing.JButton jbañadirRep

jlAviso

javax.swing.JLabel jlAviso

jtAutopista

javax.swing.JTextField jtAutopista

jtDietas

javax.swing.JTextField jtDietas

jtGasoil

javax.swing.JTextField jtGasoil

jtIncidencias

javax.swing.JTextArea jtIncidencias

jtKmFin

javax.swing.JTextField jtKmFin

jtKmIni

javax.swing.JTextField jtKmIni

jtOtros

javax.swing.JTextField jtOtros

jtVehiculo

javax.swing.JTextField jtVehiculo

Class Ventanas.VentanaReparto extends javax.swing.JFrame implements Serializable

Serialized Fields

JSpinner3

java.lang.Object JSpinner3

sm

javax.swing.SpinnerDateModel sm

sm3

javax.swing.SpinnerDateModel sm3

vp

VentanaParte vp

vpa

VentanaParteAdminis vpa

jLabel1

javax.swing.JLabel jLabel1

jLabel2

javax.swing.JLabel jLabel2

jLabel3

javax.swing.JLabel jLabel3

jLabel4

javax.swing.JLabel jLabel4

jguardaboton

javax.swing.JButton jguardaboton

jsfin

javax.swing.JSpinner jsfin

jsinicio

javax.swing.JSpinner jsinicio

jtalbaran

javax.swing.JTextField jtalbaran

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package md5b60ffeb829f638581ab2bb9b1a7f4f3f;

public class NavigationMenuRenderer_MenuAdapter
	extends android.widget.BaseAdapter
	implements
		mono.android.IGCUserPeer
{
/** @hide */
	public static final String __md_methods;
	static {
		__md_methods =
			"n_getItem:(I)Ljava/lang/Object;:GetGetItem_IHandler\n" +
			"n_getView:(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;:GetGetView_ILandroid_view_View_Landroid_view_ViewGroup_Handler\n" +
			"n_getItemId:(I)J:GetGetItemId_IHandler\n" +
			"n_getCount:()I:GetGetCountHandler\n" +
			"";
		mono.android.Runtime.register ("Xamarin.Forms.Platform.Android.NavigationMenuRenderer+MenuAdapter, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", NavigationMenuRenderer_MenuAdapter.class, __md_methods);
	}

	public NavigationMenuRenderer_MenuAdapter ()
	{
		super ();
		if (getClass () == NavigationMenuRenderer_MenuAdapter.class)
			mono.android.TypeManager.Activate ("Xamarin.Forms.Platform.Android.NavigationMenuRenderer+MenuAdapter, Xamarin.Forms.Platform.Android, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] {  });
	}

	public java.lang.Object getItem (int p0)
	{
		return n_getItem (p0);
	}

	private native java.lang.Object n_getItem (int p0);

	public android.view.View getView (int p0, android.view.View p1, android.view.ViewGroup p2)
	{
		return n_getView (p0, p1, p2);
	}

	private native android.view.View n_getView (int p0, android.view.View p1, android.view.ViewGroup p2);

	public long getItemId (int p0)
	{
		return n_getItemId (p0);
	}

	private native long n_getItemId (int p0);

	public int getCount ()
	{
		return n_getCount ();
	}

	private native int n_getCount ();

	private java.util.ArrayList refList;
	public void monodroidAddReference (java.lang.Object obj)
	{
		if (refList == null)
			refList = new java.util.ArrayList ();
		refList.add (obj);
	}

	public void monodroidClearReferences ()
	{
		if (refList != null)
			refList.clear ();
	}
}


text:
/**
 * Package réunissant les classes permettant de contrôler des données provenant de formulaires
 *
 * @see fr.fablabmars.controler
 * @see fr.fablabmars.vue.formulaires
 */
package fr.fablabmars.controler.formulaire;


text:
package org.cleartk.corpus.timeml;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngine;
import org.apache.uima.collection.CollectionReader;
import org.apache.uima.resource.ResourceInitializationException;
import org.apache.uima.util.FileUtils;
import org.cleartk.test.util.CleartkTestBase;
import org.cleartk.timeml.type.Event;
import org.cleartk.timeml.type.TemporalLink;
import org.cleartk.timeml.type.Time;
import org.cleartk.util.cr.FilesCollectionReader;
import org.jdom2.Attribute;
import org.jdom2.Content;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.apache.uima.fit.factory.AnalysisEngineFactory;

/**
 *

 * Copyright (c) 2007-2008, Regents of the University of Colorado

 * All rights reserved.
 *
 *
 * @author Steven Bethard
 *
 */
public class TempEval2007WriterTest extends CleartkTestBase {

  private File inputFile;

  private File outputFile;

  @Before
  public void setUp() throws Exception {
    super.setUp();
    inputFile = new File("src/test/resources/data/timeml/test.foo");
    outputFile = new File(outputDirectory, "test.foo.tml");
  }

  @Test
  public void test() throws Exception, JDOMException {
    CollectionReader reader = FilesCollectionReader.getCollectionReaderWithView(
        this.inputFile.getPath(),
        TimeMlGoldAnnotator.TIMEML_VIEW_NAME);
    AnalysisEngine annotator = AnalysisEngineFactory.createEngine(TimeMlGoldAnnotator.getDescription());
    AnalysisEngine writer = AnalysisEngineFactory.createEngine(TempEval2007Writer.getDescription(this.outputDirectory.getPath()));

    reader.getNext(this.jCas.getCas());
    annotator.process(this.jCas);
    writer.process(this.jCas);
    reader.close();
    annotator.collectionProcessComplete();
    writer.collectionProcessComplete();

    String expected = FileUtils.file2String(this.inputFile);
    String actual = FileUtils.file2String(this.outputFile);
    this.assertEquals(this.getRoot(expected), this.getRoot(actual));
  }

  @Test
  public void testToTimeML() throws Throwable {
    this.jCas.setDocumentText("\nHe bought milk yesterday.\n\n\n");
    Event event = new Event(this.jCas, 4, 10);
    event.setId("e1");
    event.setEventInstanceID("ei1");
    event.addToIndexes();
    Assert.assertEquals("bought", event.getCoveredText());

    Time time = new Time(this.jCas, 16, 25);
    time.setId("t1");
    time.addToIndexes();
    Assert.assertEquals("yesterday", time.getCoveredText());

    TemporalLink tlink1 = new TemporalLink(this.jCas, 27, 27);
    tlink1.setSource(event);
    tlink1.setTarget(time);
    tlink1.setRelationType("OVERLAP");
    tlink1.addToIndexes();

    TemporalLink tlink2 = new TemporalLink(this.jCas, 28, 28);
    tlink2.setSource(time);
    tlink2.setTarget(event);
    tlink2.setRelationType("OVERLAP");
    tlink2.addToIndexes();

    String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><TimeML>\n"
        + "He <EVENT eid=\"e1\">bought</EVENT> milk <TIMEX3 tid=\"t1\">yesterday</TIMEX3>.\n"
        + "<TLINK relType=\"OVERLAP\" eventID=\"e1\" relatedToTime=\"t1\"/>\n"
        + "<TLINK relType=\"OVERLAP\" timeID=\"t1\" relatedToEvent=\"e1\"/>\n"
        + "</TimeML>";
    Assert.assertEquals(expected, TempEval2007Writer.toTimeML(this.jCas).replaceAll("\r", ""));
  }

  @Test
  public void testDescriptor() throws UIMAException {
    try {
      AnalysisEngineFactory.createEngine(TempEval2007Writer.class);
      Assert.fail("expected failure with no OutputDirectory specified");
    } catch (ResourceInitializationException e) {
    }

    AnalysisEngine engine = AnalysisEngineFactory.createEngine(
        TempEval2007Writer.class,
        TempEval2007Writer.PARAM_OUTPUT_DIRECTORY_NAME,
        this.outputDirectory.getPath());
    Assert.assertEquals(
        this.outputDirectory.getPath(),
        engine.getConfigParameterValue(TempEval2007Writer.PARAM_OUTPUT_DIRECTORY_NAME));
    engine.collectionProcessComplete();
  }

  private Element getRoot(String xml) throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    builder.setDTDHandler(null);
    return builder.build(new StringReader(xml)).getRootElement();
  }

  private void assertEquals(Element element1, Element element2) {
    Assert.assertEquals(element1.getName(), element2.getName());
    Assert.assertEquals(this.getAttributes(element1), this.getAttributes(element2));
    List<Content> children1 = element1.getContent();
    List<Content> children2 = element2.getContent();
    Assert.assertEquals(children1.size(), children2.size());
    for (int i = 0; i < children1.size(); i++) {
      Content child1 = children1.get(0);
      Content child2 = children2.get(0);
      if (child1 instanceof Element) {
        this.assertEquals((Element) child1, (Element) child2);
      } else {
        Assert.assertEquals(child1.getValue(), child2.getValue());
      }
    }
  }

  private Map<String, String> getAttributes(Element element) {
    Map<String, String> attributes = new HashMap<String, String>();
    for (Object attrObj : element.getAttributes()) {
      Attribute attribute = (Attribute) attrObj;
      attributes.put(attribute.getName(), attribute.getValue());
    }
    return attributes;
  }
}