text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>wang.conge.springdemo</groupId>
	<artifactId>springdemo-parent</artifactId>
	<version>${project.version}</version>
	<packaging>pom</packaging>

	<properties>
		<project.version>1.0.0-SNAPSHOT</project.version>
		<project.encoding>UTF-8</project.encoding>

		<compiler.plugin.version>3.3</compiler.plugin.version>
		<resources.plugin.version>2.7</resources.plugin.version>
		<surefire.plugin.version>2.9</surefire.plugin.version>

		<java.version>1.8</java.version>
		<servlet.version>3.1.0</servlet.version>
		<aopalliance.version>1.0</aopalliance.version>
		<commons-logging.version>1.2</commons-logging.version>
		<gson.version>2.6.2</gson.version>
		<aspectj.version>1.8.8</aspectj.version>
		<spring.version>4.2.5.RELEASE</spring.version>
		<junit.version>4.12</junit.version>
		<h2.version>1.4.191</h2.version>
	</properties>

	<modules>
		<module>springdemo-web</module>
		<module>springdemo-core</module>
		<module>springbase</module>
	</modules>

	<dependencyManagement>
		<dependencies>
			<!-- self -->
			<dependency>
				<groupId>wang.conge.springdemo</groupId>
				<artifactId>springdemo-core</artifactId>
				<version>${project.version}</version>
			</dependency>
			<dependency>
				<groupId>wang.conge.springdemo</groupId>
				<artifactId>springdemo-web</artifactId>
				<version>${project.version}</version>
			</dependency>
			<dependency>
				<groupId>wang.conge.springdemo</groupId>
				<artifactId>springbase</artifactId>
				<version>${project.version}</version>
			</dependency>

			<!--servlet -->
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>javax.servlet-api</artifactId>
				<version>${servlet.version}</version>
				<scope>provided</scope>
			</dependency>

			<!-- common lib -->
			<dependency>
				<groupId>aopalliance</groupId>
				<artifactId>aopalliance</artifactId>
				<version>${aopalliance.version}</version>
			</dependency>
			<dependency>
				<groupId>org.aspectj</groupId>
				<artifactId>aspectjweaver</artifactId>
				<version>${aspectj.version}</version>
			</dependency>
			<dependency>
				<groupId>com.google.code.gson</groupId>
				<artifactId>gson</artifactId>
				<version>${gson.version}</version>
			</dependency>
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>${junit.version}</version>
				<scope>test</scope>
			</dependency>
			<dependency>
				<groupId>com.h2database</groupId>
				<artifactId>h2</artifactId>
				<version>${h2.version}</version>
			</dependency>

			<!-- logging -->
			<dependency>
				<groupId>commons-logging</groupId>
				<artifactId>commons-logging</artifactId>
				<version>${commons-logging.version}</version>
			</dependency>

			<!-- spring -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-core</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-beans</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aop</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context-support</artifactId>
				<version>${spring.version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-expression</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-web</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-webmvc</artifactId>
				<version>${spring.version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-tx</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>${spring.version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-test</artifactId>
				<version>${spring.version}</version>
				<scope>test</scope>
			</dependency>

		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${compiler.plugin.version}</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.encoding}</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
/* TODO:
- Rename .name -> id?
- Rename getEditName -> getEditId() ?
- Don't pass name in render? but use getEditId like everywhere else?
*/

EditItem = Base.extend(new function() {
	var types = new Hash();

	return {
		_scale: false,
		itemClassName: 'edit-item',
		// Facilitate adding buttons through this.buttons object by making
		// sure it one always there...
		buttons: {},

		initialize: function() {
			if (this.prototypes) {
				// Convert prototypes string to array of prototype names
				if (typeof this.prototypes == 'string') {
					this.prototypes = this.prototypes.split(/\s*,\s*/);
				} else if (this.prototypes instanceof Function) {
					// If it's one constructor, create an array containing its
					// name.
					this.prototypes = [this.prototypes.name];
				} else if (this.prototypes instanceof Array) {
					// Make sure the array only contains strings. If constructor
					// functions are listed, access their name field which seems
					// to be defined for HopObject constructors:
					for (var i = 0, j = this.prototypes.length; i < j; i++) {
						var proto = this.prototypes[i];
						// If it's a constructor, assume it's a HopObject and
						// use its name
						if (proto instanceof Function)
							this.prototypes[i] = proto.name;
					}
				}
			}
			// Automatically prepend edit-element to the classname
			this.className = this.className ? 'edit-element ' + this.className
					: 'edit-element';
		},

		render: function(baseForm, name, value, param, out) {
		},

		convert: function(value) {
			return EditForm.DONT_APPLY;
		},

		convertBreaks: function(str) {
			// Helper function: convert any possible kind of line breaks to \n.
			// This can be used when retrieveing values from forms
			return str ? str.replace(/\r\n|\n\r|\r/mg, '\n') : str;
		},

		apply: function(value) {
			// Only set if it changed
			if (this.getValue() != value) {
				return this.setValue(value);
			} else {
				return false;
			}
		},

		getValue: function() {
			if (this.value != null) {
				return this.value;
			} else if (this.evaluate) {
				// Evaluates the content of item.evaluate in the object and
				// returns it. Use a function instead of eval, as only in this
				// way, in "this.evaluate", "this" will point to the right
				// object.
				try {
					return new Function('return ' + this.evaluate).call(
							this.form.object);
				} catch (e) {
					User.logError('EditItem#getValue(): ' + this.evaluate, e);
				}
			} else if (this.name) {
				 // Read the property with given name
				return this.form.object[this.name];
			}
			return null;
		},

		setValue: function(value) {
			if (this.evaluate) {
				if (app.properties.debugEdit)
					User.log('EditItem#setValue(): ' + this.evaluate + ' = '
							+ Json.encode(value));
				// Evaluate string variable to the content of value:
				try {
					if (app.properties.debugEdit)
						User.log('EditItem#setValue(): ' + this.evaluate + ' = '
								+ Json.encode(value));
					new Function('value', this.evaluate + ' = value;')
							.call(this.form.object, value);
					return true;
				} catch (e) {
					User.logError('EditItem#setValue(): ' + this.evaluate, e);
				}
			} else if (this.name) {
				if (app.properties.debugEdit)
					User.log('EditItem#setValue(): ' + this.name + ' = '
							+ Json.encode(value));
				this.form.object[this.name] = value;
				return true;
			}
			return false;
		},

		store: function(object) {
			return this.setValue(object);
		},

		getOptions: function() {
			return { scaleToFit: this._scale };
		},

		getEditName: function() {
			return this.name ? this.form.getVariablePrefix() + this.name : null;
		},

		getEditParam: function(params) {
			var obj = {
				edit_item: this.name,
				edit_group: this.form.name
			};
			// Add the list entry id needed to identify forms for editable list
			// entries, or pass it on if the editing request already came from
			// such an entry.
			if (this.form.listEntryId)
				obj.edit_entry_id = this.form.listEntryId;
			else if (req.data.edit_entry_id)
				obj.edit_entry_id = req.data.edit_entry_id;
			return Hash.append(obj, params);
		},

		getPrototypes: function() {
			// Convert string prototype names to constructors
		 	return this.prototypes && this.prototypes.collect(function(name) {
				var proto = global[name];
				if (proto) return proto;
				User.log("WARNING: Prototype '" + name + "' does not exist!");
			});
		},

		getPrototypeChooserList: function(baseForm, renderHandler) {
			var editParam = this.getEditParam();
		 	return this.prototypes && this.prototypes.collect(function(name) {
				var proto = global[name];
				if (proto) {
					return {
						name: proto.name.uncamelize(),
						handler: renderHandler
							? renderHandler.call(this, proto)
							: baseForm.renderHandle('execute', 'new',
								Hash.append({ edit_prototype: proto.name },
									editParam))
					};
				}
				User.log("WARNING: Prototype '" + name + "' does not exist!");
			}, this) || [];
		},

		getPrototypeChooserButton: function(baseForm, param, chooser) {
			// If a chooser object is passed, it contains the prerendered
			// chooser values, to be reused for multiple list entries.
			// In this case pass its name as a string, otherwise, render the
			// chooser list now and pass it to the select_new function.
			var value = chooser
				? chooser.name
				: this.getPrototypeChooserList(baseForm);
			param = new Hash(param);
			param.name = (param.name || this.getEditName()) + '_new';
			param.onClick = param.onClick || baseForm.renderHandle(
					'select_new', param.name, value, this.getEditParam())
			return param;
		},

		/**
		 * Used by image related items to receive a hopoject collection that
		 * contains pictures resources. The list can contain other resources
		 * too, as it then gets filtered as well. This can be overridden in
		 * apps. Returning arrays is not supported.
		 */
		getPictureResources: function(object) {
			return object.resources;
		},

		hasPictureResources: function() {
			var resources = this.getPictureResources(this.form.object);
			return resources && resources.list().find(function(resource) {
				return resource.instanceOf(Picture);
			});
		},

		getCropOptions: function(object, picture, options) {
			// options is only optionally provided by overriding prototypes.
			// By default it is null.
			if (!options)
				options = {};
			if (!options.crop) {
				// If no crop is provided for a new picture yet, calculate a
				// default one now.
				var crop = options.crop = { width: 50, height: 50 };
				// Scan through presets and select one if none is selected
				var presets = options.presets;
				if (presets) {
					// Find selected preset first
					var selected = presets.find(function(preset) {
						if (preset.selected)
							return preset;
					});
					// If there is none, find the first and select it.
					if (!selected) {
						selected = presets.find(function(preset) {
							if (preset)
								return preset;
						});
						if (selected)
							selected.selected = true;
					}
					if (selected) {
						if (crop.width < selected.width)
							crop.width = selected.width;
						if (crop.height < selected.height)
							crop.height = selected.height;
					}
				}
				crop.left = Math.round((picture.width - crop.width) / 2);
				crop.top = Math.round((picture.height - crop.height) / 2);
			}
			return options;
		},

		getButtons: function(baseForm, name) {
			return null;
		},

		renderButtons: function(baseForm, name, wrapped, out) {
			var buttons = this.getButtons(baseForm, name);
			if (buttons && buttons.length)
				return baseForm.renderButtons(buttons, wrapped, out);
		},

		toString: function() {
			var out = [];
			['type', 'name', 'index', 'row', 'groupForm'].each(function(val) {
				if (this[val] !== undefined) {
					out.push(val + ': ' + (val == 'row'
							? this.row.index : this[val]));
				}
			}, this);
			return '{ ' + out.join(', ') + ' }';
		},

		statics: {
			extend: function(src) {
				return (src._types || '').split(',').each(function(type) {
					types[type] = this;
				}, this.base(src));
			},

			initialize: function(item) {
				// Convert the item which is a plain object to that prototype
				// by setting its __proto__ field.
				// This hack works on Rhino but not on every browser:
				var type = item.type && types[item.type] || EditItem;
				item.__proto__ = type.prototype;
				return item.initialize && item.initialize() || item;
			}
		}
	}
});

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

ModuleAudio::ModuleAudio(bool start_enabled) : Module(start_enabled)
{}

// Destructor
ModuleAudio::~ModuleAudio()
{}

// Called before render is available
bool ModuleAudio::Init()
{
	LOG("Loading Audio Mixer");
	bool ret = true;
	SDL_Init(0);

	if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
	{
		LOG("SDL_INIT_AUDIO could not initialize! SDL_Error: %s\n", SDL_GetError());
		ret = false;
	}

	// load support for the OGG format
	int flags = MIX_INIT_OGG;
	int init = Mix_Init(flags);

	if ((init & flags) != flags)
	{
		LOG("Could not initialize Mixer lib. Mix_Init: %s", Mix_GetError());
		ret = false;
	}

	//Initialize SDL_mixer
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
	{
		LOG("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
		ret = false;
	}

	return ret;
}

// Called before quitting
bool ModuleAudio::CleanUp()
{
	LOG("Freeing sound FX, closing Mixer and Audio subsystem");

	if (music != nullptr)
	{
		Mix_FreeMusic(music);
	}

	for (vector<Mix_Chunk*>::iterator it = fx.begin(); it != fx.end(); ++it)
		Mix_FreeChunk(*it);

	fx.clear();
	Mix_CloseAudio();
	Mix_Quit();
	SDL_QuitSubSystem(SDL_INIT_AUDIO);
	return true;
}

// Play a music file
bool ModuleAudio::PlayMusic(const char* path, float fade_time, int loop)
{
	bool ret = true;

	if (music != nullptr)
	{
		if (fade_time > 0.0f)
		{
			Mix_FadeOutMusic((int)(fade_time * 1000.0f));
		}
		else
		{
			Mix_HaltMusic();
		}

		// this call blocks until fade out is done
		Mix_FreeMusic(music);
	}

	music = Mix_LoadMUS(path);

	if (music == nullptr)
	{
		LOG("Cannot load music %s. Mix_GetError(): %s\n", path, Mix_GetError());
		ret = false;
	}
	else
	{
		if (fade_time > 0.0f)
		{
			if (Mix_FadeInMusic(music, -1, (int)(fade_time * 1000.0f)) < 0)
			{
				LOG("Cannot fade in music %s. Mix_GetError(): %s", path, Mix_GetError());
				ret = false;
			}
		}
		else
		{
			if (Mix_PlayMusic(music, loop) < 0)
			{
				LOG("Cannot play in music %s. Mix_GetError(): %s", path, Mix_GetError());
				ret = false;
			}
		}
	}

	LOG("Successfully playing %s", path);
	return ret;
}

// Load WAV
unsigned int ModuleAudio::LoadFx(const char* path)
{
	unsigned int ret = 0;
	Mix_Chunk* chunk = Mix_LoadWAV(path);

	if (chunk == nullptr)
	{
		LOG("Cannot load wav %s. Mix_GetError(): %s", path, Mix_GetError());
	}
	else
	{
		fx.push_back(chunk);
		ret = fx.size() - 1;
	}

	return ret;
}

// Play WAV
bool ModuleAudio::PlayFx(unsigned int id, int repeat)
{
	bool ret = false;

	if (id < fx.size())
	{
		Mix_PlayChannel(-1, fx[id], repeat);
		ret = true;
	}

	return ret;
}

void ModuleAudio::FreeFx() {
	for (vector<Mix_Chunk*>::iterator it = fx.begin(); it != fx.end(); ++it)
		Mix_FreeChunk(*it);

	fx.clear();
}


text:
import collections
from collections import defaultdict

import six

from mongo_dynamic_fixture import fields

class BaseSchema(fields.ObjectField):

    schema = {}

    def __init__(self):
        super(BaseSchema, self).__init__(self.schema)

    def generate(self, **kwargs):
        generated = super(BaseSchema, self).generate()
        extra = kwargs.pop('extra', {})
        extra.update(kwargs)
        overrider = self._build_overrider(extra)

        return self._override(generated, overrider)

    def _build_overrider(self, overrider_kwargs):
        infinite_defaultdict = lambda: defaultdict(infinite_defaultdict)
        overrider = infinite_defaultdict()
        keys_values = [(k.split('__'), v)
                       for k, v in six.iteritems(overrider_kwargs)]

        for keys, value in keys_values:
            cd = overrider
            for k in keys[:-1]:
                cd = cd[k]

            cd[keys[-1]] = value

        return dict(overrider)

    def _override(self, generated, overrider):
        for k, v in six.iteritems(overrider):
            if isinstance(v, collections.Mapping):
                r = self._override(generated.get(k, {}), v)
                generated[k] = r
            else:
                generated[k] = overrider[k]

        return generated


text:
package galileo.bmp;

import galileo.dataset.Coordinates;

import galileo.dataset.Point;
import galileo.dataset.SpatialRange;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Similar to the GeoavailabilityGrid, the GeoavailabilityMap allows arbitrary
 * spatial locations to be mapped to lists of data points.
 *
 * @author malensek
 */
public class GeoavailabilityMap<T> {

    private GeoavailabilityGrid grid;
    private Map<Integer, List<T>> points;

    public GeoavailabilityMap(String baseGeohash, int precision) {
        grid = new GeoavailabilityGrid(baseGeohash, precision);
        points = new HashMap<>();
    }

    /**
     * Adds a new point to this GeoavailabilityMap, and associates it with a
     * data point.
     *
     * @param coords The location (coordinates in lat, lon) to add.
     * @param data Data point to associate with the location.
     *
     * @return true if the point could be added to map, false otherwise (for
     * example, if the point falls outside the purview of the grid)
     */
    public boolean addPoint(Coordinates coords, T data) {
        if (grid.addPoint(coords) == false) {
            return false;
        }

        Point<Integer> gridPoint = grid.coordinatesToXY(coords);
        int index = grid.XYtoIndex(gridPoint.X(), gridPoint.Y());

        List<T> dataList = points.get(index);
        if (dataList == null) {
            dataList = new ArrayList<>();
            points.put(index, dataList);
        }

        dataList.add(data);
        return true;
    }

    /**
     * Retrieves the {@link SpatialRange} represented by a grid index point.
     */
    public SpatialRange indexToSpatialRange(int index) {
        return grid.indexToSpatialRange(index);
    }

    /**
     * Queries the GeoavailabilityGrid, returning the grid indices that contain
     * matching points, with lists of their associated data points.
     *
     * @param query GeoavailabilityQuery to evaluate
     *
     * @return results, as a Map of indices to arrays of data points.
     */
    public Map<Integer, List<T>> query(GeoavailabilityQuery query)
    throws BitmapException {
        Map<Integer, List<T>> results = new HashMap<>();
        int[] indices = grid.query(query);
        for (int i : indices) {
            results.put(i, points.get(i));
        }

        return results;
    }
}


text:
@interface HomeViewController ()

@end

@implementation HomeViewController
{
    NSMutableArray<NSManagedObject*>* canvases;
    int itemsPerRow;
    UIEdgeInsets cellInsets;
    DatabaseHelper* helper;
}

@synthesize collectionView;

- (void)dismiss
{
    CCDirector* direction = [CCDirector sharedDirector];
    [direction dismissViewControllerAnimated:self completion:NULL];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    canvases = [NSMutableArray array];
    itemsPerRow = 3;
    cellInsets = UIEdgeInsetsMake(50.f, 20.f, 50.f, 20.f);
    helper = [DatabaseHelper sharedDatabaseHelper];

    UINib *cellNib = [UINib nibWithNibName:@"CollectionViewCell" bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"Cell"];
}

- (void)viewDidAppear:(BOOL)animated
{
    NSArray<NSManagedObject*>* images = [helper getImages];
    [canvases removeAllObjects];
    [canvases addObjectsFromArray:images];
    if ([images count] == 0)
    {
        // If there is no image, we create a default one
        [self addCanvas:nil];
    }
    else
    {
        [self reload];
    }
}

- (void)reload
{
    [self.collectionView reloadData];
}

- (void)addImage:(NSData*)data imageId:(int32_t)imageId
{
    [helper insertImage:data imageId:imageId];
    [canvases removeAllObjects];
    [canvases addObjectsFromArray:[helper getImages]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)addCanvas:(id)sender
{
    int32_t newId = (int32_t)[helper getImages].count;
    [self addImage:nil imageId:newId];
    [self reload];
}

- (UIImage*)imageForIndexPath:(NSIndexPath*)indexPath
{
    if ([canvases count] > indexPath.row)
    {
        NSManagedObject* managedObject = [canvases objectAtIndex:indexPath.row];
        NSData* imageData = [managedObject valueForKey:kImageDataKey];
        if (imageData != NULL)
        {
            UIImage* image = [UIImage imageWithData:imageData];
            return image;
        }
    }
    return nil;
}

#pragma CollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    id delegate = [[UIApplication sharedApplication] delegate];
    NSManagedObject* object = [canvases objectAtIndex:indexPath.row];
    [delegate runSceneWithManagedObject:object];
    [self dismiss];
}

#pragma CollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat paddingSpace = cellInsets.left * (itemsPerRow + 1);
    CGFloat availableWidth = self.view.frame.size.width - paddingSpace;
    CGFloat widthPerItem = availableWidth / itemsPerRow;

    return CGSizeMake(widthPerItem, widthPerItem);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return cellInsets;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return cellInsets.left;
}

#pragma CollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    // One section for now
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    // There is only one section
    return [canvases count];
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)_collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";

    CollectionViewCell *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.imageView.image = [self imageForIndexPath:indexPath];
    cell.layer.borderWidth = 2.5f;
    cell.layer.borderColor = [UIColor blackColor].CGColor;
    cell.layer.cornerRadius = 2.5f;

    return cell;
}

@end


text:
package gg.galaxygaming.necessities.Commands.WorldManager;

import gg.galaxygaming.necessities.Necessities;
import gg.galaxygaming.necessities.Variables;
import gg.galaxygaming.necessities.WorldManager.WarpManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class CmdRemoveWarp implements WorldCmd {

    public boolean commandUse(CommandSender sender, String[] args) {
        Variables var = Necessities.getVar();
        if (args.length == 0) {
            sender.sendMessage(
                  var.getEr() + "Error: " + var.getErMsg() + "You must enter a name for the warp you wish to remove.");
            return true;
        }
        WarpManager warps = Necessities.getWarps();
        if (!warps.isWarp(args[0])) {
            sender.sendMessage(var.getEr() + "Error: " + var.getErMsg() + "There is no warp by that name.");
            return true;
        }
        warps.remove(args[0]);
        sender.sendMessage(
              var.getMessages() + "Removed the warp named " + var.getObj() + args[0] + var.getMessages() + '.');
        return true;
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String[] args) {
        if (args.length != 1 || !(sender instanceof Player)) {
            return Collections.emptyList();
        }
        List<String> complete = new ArrayList<>();
        String search = args[0];
        WarpManager warps = Necessities.getWarps();
        for (String warp : warps.getAllWarps()) {
            if (warp.startsWith(search)) {
                complete.add(warp);
            }
        }
        return complete;
    }
}


text:
package com.intellij.codeInspection;

import com.intellij.codeInsight.intention.LowPriorityAction;
import com.intellij.codeInspection.ex.InspectionProfileModifiableModelKt;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.command.undo.BasicUndoableAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ReflectionUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public class SetInspectionOptionFix implements LocalQuickFix, LowPriorityAction, Iconable {
  private String myShortName;
  private final String myProperty;
  private final String myMessage;
  private boolean myValue;

  public SetInspectionOptionFix(InspectionProfileEntry inspection, String property, String message, boolean value) {
    myShortName = inspection.getShortName();
    myProperty = property;
    myMessage = message;
    myValue = value;
  }

  @Nls
  @NotNull
  @Override
  public String getName() {
    return myMessage;
  }

  @Nls
  @NotNull
  @Override
  public String getFamilyName() {
    return "Set inspection option";
  }

  @Override
  public boolean startInWriteAction() {
    return false;
  }

  @Override
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    setOption(project, myValue);
    final VirtualFile vFile = descriptor.getPsiElement().getContainingFile().getVirtualFile();
    UndoManager.getInstance(project).undoableActionPerformed(new BasicUndoableAction(vFile) {
      @Override
      public void undo() {
        setOption(project, !myValue);
      }

      @Override
      public void redo() {
        setOption(project, myValue);
      }
    });
  }

  private void setOption(@NotNull Project project, boolean value) {
    InspectionProfileModifiableModelKt.modifyAndCommitProjectProfile(project, model -> {
      InspectionToolWrapper tool = model.getInspectionTool(myShortName, project);
      if(tool == null) return;
      InspectionProfileEntry inspection = tool.getTool();
      ReflectionUtil.setField(inspection.getClass(), inspection, boolean.class, myProperty, value);
    });
  }

  @Override
  public Icon getIcon(int flags) {
    return AllIcons.Actions.Cancel;
  }
}


text:
using CoreVideo;
#if WINUI
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
#else
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#endif

#if WINDOWS || WINUI
namespace SkiaSharp.Views.Windows
#else
namespace SkiaSharp.Views.UWP
#endif
{
	public partial class SKSwapChainPanel : FrameworkElement
	{
		private SKGLView glView;
		private CVDisplayLink displayLink;

		public SKSwapChainPanel()
		{
			Initialize();
		}

		private SKSize GetCanvasSize() =>
			glView?.CanvasSize ?? SKSize.Empty;

		private GRContext GetGRContext() =>
			glView?.GRContext;

		partial void DoLoaded()
		{
			glView = new SKGLView(Bounds);
			glView.PaintSurface += OnPaintSurface;
			AddSubview(glView);
		}

		partial void DoUnloaded()
		{
			DoEnableRenderLoop(false);

			if (glView != null)
			{
				glView.RemoveFromSuperview();
				glView.PaintSurface -= OnPaintSurface;
				glView.Dispose();
				glView = null;
			}
		}

		private void DoInvalidate() =>
			DoEnableRenderLoop(true);

		private void OnPaintSurface(object sender, SKPaintGLSurfaceEventArgs e) =>
			OnPaintSurface(e);

		partial void DoEnableRenderLoop(bool enable)
		{
			// stop the render loop
			if (!enable)
			{
				if (displayLink != null)
				{
					displayLink.Stop();
					displayLink.Dispose();
					displayLink = null;
				}
				return;
			}

			// only start if we haven't already
			if (displayLink != null)
				return;

			// create the loop
			displayLink = new CVDisplayLink();
			displayLink.SetOutputCallback(delegate
			{
				// redraw the view
				glView?.BeginInvokeOnMainThread(() =>
				{
					if (glView != null)
						glView.NeedsDisplay = true;
				});

				// stop the render loop if it has been disabled or the views are disposed
				if (glView == null || !EnableRenderLoop)
					DoEnableRenderLoop(false);

				return CVReturn.Success;
			});
			displayLink.Start();
		}
	}
}


text:
<#
.Synopsis
   Given a task sequence package id the referenced packages are looked up and the Source path displayed
.EXAMPLE
   Get-TSPkgSource -PackageId DEV005A4 -SiteCode DEV
   Displays the Packages and Source Path information for Task Sequence DEV005A4 on Site DEV
.EXAMPLE
   DEV005A4|Get-TSPkgSource -SiteCode DEV
   Displays the Packages and Source Path information for Task Sequence DEV005A4 on Site DEV
   by passing the task sequence package id via the pipeline
.Note
    Author
        Jon Warnken
        jon.warnken@gmail.com
        @MrBoDean
#>
function Get-TSPkgSource
{
    [CmdletBinding()]
    #Requires -Version 3.0
    #Requires -Modules ConfigurationManager
    Param(
        # Param1 help description
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [String]$PackageId,
        [Parameter(Mandatory=$true)]
        [String]$SiteCode
    )#Param

    Begin
    {
        If((Get-Location).Drive.Name -ne $SiteCode){
            Try{Set-Location -path "($SiteCode):" -ErrorAction Stop}
            Catch{Throw "Unable to connect to Site $SiteCode. Ensure that the Site Code is correct and that you have access."}
        }#If
    }#Begin
    Process
    {
        ForEach($tspkgid in $PackageId){
            $tasksequence = Get-CMTaskSequence -TaskSequencePackageId $tspkgid
            If($tasksequence){
                $tasksequence|select-object -ExpandProperty References|Select-Object -ExpandProperty Package -Unique|
                ForEach-Object{ $t = Get-CMPackage -Id $_ |select-object Name,PackageID,PkgSourcePath,SourceDate
                     if(!($t)){Get-CMDriverPackage -Id $_ |select-object Name,PackageID,PkgSourcePath,SourceDate}
                     if(!($t)){Get-CMBootImage -Id $_ |select-object Name,PackageID,PkgSourcePath,SourceDate}
                     if(!($t)){Get-CMOperatingSystemImage -Id $_ |select-object Name,PackageID,PkgSourcePath,SourceDate}
                     if(!($t)){Get-CMSoftwareUpdateDeploymentPackage -Id $_ |select-object Name,PackageID,PkgSourcePath,SourceDate}
                     $t
                     Remove-Variable -Name t
                  }#Pipeline ForEach
            }Else{
                Write-Error "$tspkgid is invalid or not a Task Sequence"
            }#Else If
        }#ForEach
    }#Process
    End{}
}


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

from pdb.lib.create_logger import create_logger

create_logger()


text:
package v3

import (
	"github.com/rancher/lasso/pkg/client"
	"github.com/rancher/lasso/pkg/controller"
	"github.com/rancher/norman/generator"
	"github.com/rancher/norman/objectclient"
	"github.com/rancher/rancher/pkg/apis/cluster.cattle.io/v3"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/rest"
)

type Interface interface {
	ClusterAuthTokensGetter
	ClusterUserAttributesGetter
}

type Client struct {
	controllerFactory controller.SharedControllerFactory
	clientFactory     client.SharedClientFactory
}

func NewForConfig(cfg rest.Config) (Interface, error) {
	scheme := runtime.NewScheme()
	if err := v3.AddToScheme(scheme); err != nil {
		return nil, err
	}
	sharedOpts := &controller.SharedControllerFactoryOptions{
		SyncOnlyChangedObjects: generator.SyncOnlyChangedObjects(),
	}
	controllerFactory, err := controller.NewSharedControllerFactoryFromConfigWithOptions(&cfg, scheme, sharedOpts)
	if err != nil {
		return nil, err
	}
	return NewFromControllerFactory(controllerFactory)
}

func NewFromControllerFactory(factory controller.SharedControllerFactory) (Interface, error) {
	return &Client{
		controllerFactory: factory,
		clientFactory:     factory.SharedCacheFactory().SharedClientFactory(),
	}, nil
}

type ClusterAuthTokensGetter interface {
	ClusterAuthTokens(namespace string) ClusterAuthTokenInterface
}

func (c *Client) ClusterAuthTokens(namespace string) ClusterAuthTokenInterface {
	sharedClient := c.clientFactory.ForResourceKind(ClusterAuthTokenGroupVersionResource, ClusterAuthTokenGroupVersionKind.Kind, true)
	objectClient := objectclient.NewObjectClient(namespace, sharedClient, &ClusterAuthTokenResource, ClusterAuthTokenGroupVersionKind, clusterAuthTokenFactory{})
	return &clusterAuthTokenClient{
		ns:           namespace,
		client:       c,
		objectClient: objectClient,
	}
}

type ClusterUserAttributesGetter interface {
	ClusterUserAttributes(namespace string) ClusterUserAttributeInterface
}

func (c *Client) ClusterUserAttributes(namespace string) ClusterUserAttributeInterface {
	sharedClient := c.clientFactory.ForResourceKind(ClusterUserAttributeGroupVersionResource, ClusterUserAttributeGroupVersionKind.Kind, true)
	objectClient := objectclient.NewObjectClient(namespace, sharedClient, &ClusterUserAttributeResource, ClusterUserAttributeGroupVersionKind, clusterUserAttributeFactory{})
	return &clusterUserAttributeClient{
		ns:           namespace,
		client:       c,
		objectClient: objectClient,
	}
}


text:
package org.cryptoworkshop.ximix.common.asn1.message;

import java.io.IOException;

import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
import org.cryptoworkshop.ximix.common.asn1.board.PointSequence;
import org.cryptoworkshop.ximix.common.crypto.ECDecryptionProof;

/**
 * Class used to define the fields in a decryption challenge log message.
 */
public class ChallengeLogMessage
    extends ASN1Object
{
    private final int index;
    private final int sequenceNo;
    private final boolean hasPassed;
    private final SubjectPublicKeyInfo keyInfo;
    private final ECPoint[] sourceMessage;
    private final ECDecryptionProof[] decryptionProofs;

    /**
     * Base constructor.
     *
     * @param index the index number of the message challenged.
     * @param sequenceNo the sequenceNo in the sharing process for the node this message is based on.
     * @param hasPassed
     * @param keyInfo the node's partial public key.
     * @param sourceMessage the input message for the challenge computation.
     * @param decryptionProofs decryption proofs..
     */
    public ChallengeLogMessage(int index, int sequenceNo, boolean hasPassed, SubjectPublicKeyInfo keyInfo, ECPoint[] sourceMessage, ECDecryptionProof[] decryptionProofs)
    {
        this.index = index;
        this.sequenceNo = sequenceNo;
        this.hasPassed = hasPassed;
        this.keyInfo = keyInfo;
        this.sourceMessage = sourceMessage;
        this.decryptionProofs = decryptionProofs;
    }

    private ChallengeLogMessage(ASN1Sequence seq)
    {
        this.index = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue().intValue();
        this.sequenceNo = ASN1Integer.getInstance(seq.getObjectAt(1)).getValue().intValue();
        this.hasPassed = ASN1Boolean.getInstance(seq.getObjectAt(2)).isTrue();
        this.keyInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(3));

        ECPublicKeyParameters ecKey;
        try
        {
            ecKey = (ECPublicKeyParameters)PublicKeyFactory.createKey(keyInfo);
        }
        catch (IOException e)
        {
            throw new IllegalArgumentException("Unable to create EC key from keyInfo in sequence.");
        }

        ECCurve curve = ecKey.getParameters().getCurve();

        this.sourceMessage = PointSequence.getInstance(curve, ASN1Sequence.getInstance(seq.getObjectAt(4))).getECPoints();

        ASN1Sequence proofS = ASN1Sequence.getInstance(seq.getObjectAt(5));
        decryptionProofs = new ECDecryptionProof[proofS.size()];

        for (int i = 0; i != decryptionProofs.length; i++)
        {
            ASN1Sequence proof = ASN1Sequence.getInstance(proofS.getObjectAt(i));
            decryptionProofs[i] = new ECDecryptionProof(curve.decodePoint(ASN1OctetString.getInstance(proof.getObjectAt(0)).getOctets()),
                curve.decodePoint(ASN1OctetString.getInstance(proof.getObjectAt(1)).getOctets()), ASN1Integer.getInstance(proof.getObjectAt(2)).getValue());
        }
    }

    /**
     * Create an instance of ChallengeLogMessage from the passed in object.
     *
     * @param o the source object to use.
     * @return a ChallengeLogMessage.
     */
    public static ChallengeLogMessage getInstance(Object o)
    {
        if (o instanceof ChallengeLogMessage)
        {
            return (ChallengeLogMessage)o;
        }
        else if (o != null)
        {
            return new ChallengeLogMessage(ASN1Sequence.getInstance(o));
        }

        return null;
    }

    @Override
    public ASN1Primitive toASN1Primitive()
    {
        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(new ASN1Integer(index));
        v.add(new ASN1Integer(sequenceNo));
        v.add(ASN1Boolean.getInstance(hasPassed));
        v.add(keyInfo);
        v.add(new PointSequence(sourceMessage));

        ASN1EncodableVector dv = new ASN1EncodableVector();
        for (ECDecryptionProof proof : decryptionProofs)
        {
            ASN1EncodableVector proofV = new ASN1EncodableVector();

            proofV.add(new DEROctetString(proof.getA().getEncoded(true)));
            proofV.add(new DEROctetString(proof.getB().getEncoded(true)));
            proofV.add(new ASN1Integer(proof.getR()));

            dv.add(new DERSequence(proofV));
        }

        v.add(new DERSequence(dv));

        return new DERSequence(v);
    }

    public boolean hasPassed()
    {
        return hasPassed;
    }

    public ECPoint[] getSourceMessage()
    {
        return sourceMessage;
    }

    public ECDecryptionProof[] getProofs()
    {
        return decryptionProofs;
    }

    public SubjectPublicKeyInfo getKeyInfo()
    {
        return keyInfo;
    }

    public int getIndex()
    {
        return index;
    }

    public int getSequenceNo()
    {
        return sequenceNo;
    }
}


text:
package com.vlabs.wearcontract;

public class WearConstants {
    public static final int FAVORITES_LIMIT = 5;
    public static final int MY_STATIONS_LIMIT = 15;
}


text:
package docker

import (
	"reflect"
	"strconv"
	"strings"
	"testing"

	"github.com/containous/traefik/types"
	docker "github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/container"
	"github.com/docker/go-connections/nat"
)

func TestDockerGetFrontendName(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(name("foo")),
			expected:  "Host-foo-docker-localhost",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "Headers:User-Agent,bat/0.1.0",
			})),
			expected: "Headers-User-Agent-bat-0-1-0",
		},
		{
			container: containerJSON(labels(map[string]string{
				"com.docker.compose.project": "foo",
				"com.docker.compose.service": "bar",
			})),
			expected: "Host-bar-foo-docker-localhost",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "Host:foo.bar",
			})),
			expected: "Host-foo-bar",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "Path:/test",
			})),
			expected: "Path-test",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "PathPrefix:/test2",
			})),
			expected: "PathPrefix-test2",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{
				Domain: "docker.localhost",
			}
			actual := provider.getFrontendName(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetFrontendRule(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(name("foo")),
			expected:  "Host:foo.docker.localhost",
		},
		{
			container: containerJSON(name("bar")),
			expected:  "Host:bar.docker.localhost",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "Host:foo.bar",
			})),
			expected: "Host:foo.bar",
		}, {
			container: containerJSON(labels(map[string]string{
				"com.docker.compose.project": "foo",
				"com.docker.compose.service": "bar",
			})),
			expected: "Host:bar.foo.docker.localhost",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.rule": "Path:/test",
			})),
			expected: "Path:/test",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{
				Domain: "docker.localhost",
			}
			actual := provider.getFrontendRule(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetBackend(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(name("foo")),
			expected:  "foo",
		},
		{
			container: containerJSON(name("bar")),
			expected:  "bar",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.backend": "foobar",
			})),
			expected: "foobar",
		},
		{
			container: containerJSON(labels(map[string]string{
				"com.docker.compose.project": "foo",
				"com.docker.compose.service": "bar",
			})),
			expected: "bar-foo",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getBackend(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetIPAddress(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(withNetwork("testnet", ipv4("10.11.12.13"))),
			expected:  "10.11.12.13",
		},
		{
			container: containerJSON(
				labels(map[string]string{
					"traefik.docker.network": "testnet",
				}),
				withNetwork("testnet", ipv4("10.11.12.13")),
			),
			expected: "10.11.12.13",
		},
		{
			container: containerJSON(
				labels(map[string]string{
					"traefik.docker.network": "testnet2",
				}),
				withNetwork("testnet", ipv4("10.11.12.13")),
				withNetwork("testnet2", ipv4("10.11.12.14")),
			),
			expected: "10.11.12.14",
		},
		{
			container: containerJSON(
				networkMode("host"),
				withNetwork("testnet", ipv4("10.11.12.13")),
				withNetwork("testnet2", ipv4("10.11.12.14")),
			),
			expected: "127.0.0.1",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getIPAddress(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetPort(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(name("foo")),
			expected:  "",
		},
		{
			container: containerJSON(ports(nat.PortMap{
				"80/tcp": {},
			})),
			expected: "80",
		},
		{
			container: containerJSON(ports(nat.PortMap{
				"80/tcp":  {},
				"443/tcp": {},
			})),
			expected: "80",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.port": "8080",
			})),
			expected: "8080",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.port": "8080",
			}), ports(nat.PortMap{
				"80/tcp": {},
			})),
			expected: "8080",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.port": "8080",
			}), ports(nat.PortMap{
				"8080/tcp": {},
				"80/tcp":   {},
			})),
			expected: "8080",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getPort(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetWeight(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(),
			expected:  "0",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.weight": "10",
			})),
			expected: "10",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getWeight(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetDomain(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(),
			expected:  "docker.localhost",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.domain": "foo.bar",
			})),
			expected: "foo.bar",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{
				Domain: "docker.localhost",
			}
			actual := provider.getDomain(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetProtocol(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(),
			expected:  "http",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.protocol": "https",
			})),
			expected: "https",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getProtocol(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetPassHostHeader(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(),
			expected:  "true",
		},
		{
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.passHostHeader": "false",
			})),
			expected: "false",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getPassHostHeader(dockerData)
			if actual != e.expected {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetWhitelistSourceRange(t *testing.T) {
	containers := []struct {
		desc      string
		container docker.ContainerJSON
		expected  []string
	}{
		{
			desc:      "no whitelist-label",
			container: containerJSON(),
			expected:  nil,
		},
		{
			desc: "whitelist-label with empty string",
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.whitelistSourceRange": "",
			})),
			expected: nil,
		},
		{
			desc: "whitelist-label with IPv4 mask",
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.whitelistSourceRange": "1.2.3.4/16",
			})),
			expected: []string{
				"1.2.3.4/16",
			},
		},
		{
			desc: "whitelist-label with IPv6 mask",
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.whitelistSourceRange": "fe80::/16",
			})),
			expected: []string{
				"fe80::/16",
			},
		},
		{
			desc: "whitelist-label with multiple masks",
			container: containerJSON(labels(map[string]string{
				"traefik.frontend.whitelistSourceRange": "1.1.1.1/24, 1234:abcd::42/32",
			})),
			expected: []string{
				"1.1.1.1/24",
				"1234:abcd::42/32",
			},
		},
	}

	for _, e := range containers {
		e := e
		t.Run(e.desc, func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			provider := &Provider{}
			actual := provider.getWhitelistSourceRange(dockerData)
			if !reflect.DeepEqual(actual, e.expected) {
				t.Errorf("expected %q, got %q", e.expected, actual)
			}
		})
	}
}

func TestDockerGetLabel(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  string
	}{
		{
			container: containerJSON(),
			expected:  "Label not found:",
		},
		{
			container: containerJSON(labels(map[string]string{
				"foo": "bar",
			})),
			expected: "",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			label, err := getLabel(dockerData, "foo")
			if e.expected != "" {
				if err == nil || !strings.Contains(err.Error(), e.expected) {
					t.Errorf("expected an error with %q, got %v", e.expected, err)
				}
			} else {
				if label != "bar" {
					t.Errorf("expected label 'bar', got %s", label)
				}
			}
		})
	}
}

func TestDockerGetLabels(t *testing.T) {
	containers := []struct {
		container      docker.ContainerJSON
		expectedLabels map[string]string
		expectedError  string
	}{
		{
			container:      containerJSON(),
			expectedLabels: map[string]string{},
			expectedError:  "Label not found:",
		},
		{
			container: containerJSON(labels(map[string]string{
				"foo": "fooz",
			})),
			expectedLabels: map[string]string{
				"foo": "fooz",
			},
			expectedError: "Label not found: bar",
		},
		{
			container: containerJSON(labels(map[string]string{
				"foo": "fooz",
				"bar": "barz",
			})),
			expectedLabels: map[string]string{
				"foo": "fooz",
				"bar": "barz",
			},
			expectedError: "",
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			labels, err := getLabels(dockerData, []string{"foo", "bar"})
			if !reflect.DeepEqual(labels, e.expectedLabels) {
				t.Errorf("expect %v, got %v", e.expectedLabels, labels)
			}
			if e.expectedError != "" {
				if err == nil || !strings.Contains(err.Error(), e.expectedError) {
					t.Errorf("expected an error with %q, got %v", e.expectedError, err)
				}
			}
		})
	}
}

func TestDockerTraefikFilter(t *testing.T) {
	containers := []struct {
		container docker.ContainerJSON
		expected  bool
		provider  *Provider
	}{
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config:          &container.Config{},
				NetworkSettings: &docker.NetworkSettings{},
			},
			expected: false,
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable": "false",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: false,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.frontend.rule": "Host:foo.bar",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container-multi-ports",
				},
				Config: &container.Config{},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp":  {},
							"443/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.port": "80",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp":  {},
							"443/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable": "true",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable": "anything",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.frontend.rule": "Host:foo.bar",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: true,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: false,
			},
			expected: false,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable": "true",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				Domain:           "test",
				ExposedByDefault: false,
			},
			expected: true,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable": "true",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				ExposedByDefault: false,
			},
			expected: false,
		},
		{
			container: docker.ContainerJSON{
				ContainerJSONBase: &docker.ContainerJSONBase{
					Name: "container",
				},
				Config: &container.Config{
					Labels: map[string]string{
						"traefik.enable":        "true",
						"traefik.frontend.rule": "Host:i.love.this.host",
					},
				},
				NetworkSettings: &docker.NetworkSettings{
					NetworkSettingsBase: docker.NetworkSettingsBase{
						Ports: nat.PortMap{
							"80/tcp": {},
						},
					},
				},
			},
			provider: &Provider{
				ExposedByDefault: false,
			},
			expected: true,
		},
	}

	for containerID, e := range containers {
		e := e
		t.Run(strconv.Itoa(containerID), func(t *testing.T) {
			t.Parallel()
			dockerData := parseContainer(e.container)
			actual := e.provider.containerFilter(dockerData)
			if actual != e.expected {
				t.Errorf("expected %v for %+v, got %+v", e.expected, e, actual)
			}
		})
	}
}

func TestDockerLoadDockerConfig(t *testing.T) {
	cases := []struct {
		containers        []docker.ContainerJSON
		expectedFrontends map[string]*types.Frontend
		expectedBackends  map[string]*types.Backend
	}{
		{
			containers:        []docker.ContainerJSON{},
			expectedFrontends: map[string]*types.Frontend{},
			expectedBackends:  map[string]*types.Backend{},
		},
		{
			containers: []docker.ContainerJSON{
				containerJSON(
					name("test"),
					ports(nat.PortMap{
						"80/tcp": {},
					}),
					withNetwork("bridge", ipv4("127.0.0.1")),
				),
			},
			expectedFrontends: map[string]*types.Frontend{
				"frontend-Host-test-docker-localhost": {
					Backend:        "backend-test",
					PassHostHeader: true,
					EntryPoints:    []string{},
					BasicAuth:      []string{},
					Routes: map[string]types.Route{
						"route-frontend-Host-test-docker-localhost": {
							Rule: "Host:test.docker.localhost",
						},
					},
				},
			},
			expectedBackends: map[string]*types.Backend{
				"backend-test": {
					Servers: map[string]types.Server{
						"server-test": {
							URL:    "http://127.0.0.1:80",
							Weight: 0,
						},
					},
					CircuitBreaker: nil,
				},
			},
		},
		{
			containers: []docker.ContainerJSON{
				containerJSON(
					name("test1"),
					labels(map[string]string{
						"traefik.backend":              "foobar",
						"traefik.frontend.entryPoints": "http,https",
						"traefik.frontend.auth.basic":  "test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/,test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0",
					}),
					ports(nat.PortMap{
						"80/tcp": {},
					}),
					withNetwork("bridge", ipv4("127.0.0.1")),
				),
				containerJSON(
					name("test2"),
					labels(map[string]string{
						"traefik.backend": "foobar",
					}),
					ports(nat.PortMap{
						"80/tcp": {},
					}),
					withNetwork("bridge", ipv4("127.0.0.1")),
				),
			},
			expectedFrontends: map[string]*types.Frontend{
				"frontend-Host-test1-docker-localhost": {
					Backend:        "backend-foobar",
					PassHostHeader: true,
					EntryPoints:    []string{"http", "https"},
					BasicAuth:      []string{"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/", "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0"},
					Routes: map[string]types.Route{
						"route-frontend-Host-test1-docker-localhost": {
							Rule: "Host:test1.docker.localhost",
						},
					},
				},
				"frontend-Host-test2-docker-localhost": {
					Backend:        "backend-foobar",
					PassHostHeader: true,
					EntryPoints:    []string{},
					BasicAuth:      []string{},
					Routes: map[string]types.Route{
						"route-frontend-Host-test2-docker-localhost": {
							Rule: "Host:test2.docker.localhost",
						},
					},
				},
			},
			expectedBackends: map[string]*types.Backend{
				"backend-foobar": {
					Servers: map[string]types.Server{
						"server-test1": {
							URL:    "http://127.0.0.1:80",
							Weight: 0,
						},
						"server-test2": {
							URL:    "http://127.0.0.1:80",
							Weight: 0,
						},
					},
					CircuitBreaker: nil,
				},
			},
		},
		{
			containers: []docker.ContainerJSON{
				containerJSON(
					name("test1"),
					labels(map[string]string{
						"traefik.backend":                           "foobar",
						"traefik.frontend.entryPoints":              "http,https",
						"traefik.backend.maxconn.amount":            "1000",
						"traefik.backend.maxconn.extractorfunc":     "somethingelse",
						"traefik.backend.loadbalancer.method":       "drr",
						"traefik.backend.circuitbreaker.expression": "NetworkErrorRatio() > 0.5",
					}),
					ports(nat.PortMap{
						"80/tcp": {},
					}),
					withNetwork("bridge", ipv4("127.0.0.1")),
				),
			},
			expectedFrontends: map[string]*types.Frontend{
				"frontend-Host-test1-docker-localhost": {
					Backend:        "backend-foobar",
					PassHostHeader: true,
					EntryPoints:    []string{"http", "https"},
					BasicAuth:      []string{},
					Routes: map[string]types.Route{
						"route-frontend-Host-test1-docker-localhost": {
							Rule: "Host:test1.docker.localhost",
						},
					},
				},
			},
			expectedBackends: map[string]*types.Backend{
				"backend-foobar": {
					Servers: map[string]types.Server{
						"server-test1": {
							URL:    "http://127.0.0.1:80",
							Weight: 0,
						},
					},
					CircuitBreaker: &types.CircuitBreaker{
						Expression: "NetworkErrorRatio() > 0.5",
					},
					LoadBalancer: &types.LoadBalancer{
						Method: "drr",
					},
					MaxConn: &types.MaxConn{
						Amount:        1000,
						ExtractorFunc: "somethingelse",
					},
				},
			},
		},
	}

	for caseID, c := range cases {
		c := c
		t.Run(strconv.Itoa(caseID), func(t *testing.T) {
			t.Parallel()
			var dockerDataList []dockerData
			for _, container := range c.containers {
				dockerData := parseContainer(container)
				dockerDataList = append(dockerDataList, dockerData)
			}

			provider := &Provider{
				Domain:           "docker.localhost",
				ExposedByDefault: true,
			}
			actualConfig := provider.loadDockerConfig(dockerDataList)
			// Compare backends
			if !reflect.DeepEqual(actualConfig.Backends, c.expectedBackends) {
				t.Errorf("expected %#v, got %#v", c.expectedBackends, actualConfig.Backends)
			}
			if !reflect.DeepEqual(actualConfig.Frontends, c.expectedFrontends) {
				t.Errorf("expected %#v, got %#v", c.expectedFrontends, actualConfig.Frontends)
			}
		})
	}
}


text:
package org.apache.druid.query.aggregation.datasketches.theta;

import com.yahoo.memory.WritableMemory;
import com.yahoo.sketches.Family;
import com.yahoo.sketches.theta.SetOperation;
import com.yahoo.sketches.theta.Union;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.apache.druid.query.aggregation.BufferAggregator;
import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import org.apache.druid.segment.BaseObjectColumnValueSelector;

import java.nio.ByteBuffer;
import java.util.IdentityHashMap;

public class SketchBufferAggregator implements BufferAggregator
{
  private final BaseObjectColumnValueSelector selector;
  private final int size;
  private final int maxIntermediateSize;
  private final IdentityHashMap<ByteBuffer, Int2ObjectMap<Union>> unions = new IdentityHashMap<>();
  private final IdentityHashMap<ByteBuffer, WritableMemory> memCache = new IdentityHashMap<>();

  public SketchBufferAggregator(BaseObjectColumnValueSelector selector, int size, int maxIntermediateSize)
  {
    this.selector = selector;
    this.size = size;
    this.maxIntermediateSize = maxIntermediateSize;
  }

  @Override
  public void init(ByteBuffer buf, int position)
  {
    createNewUnion(buf, position, false);
  }

  @Override
  public void aggregate(ByteBuffer buf, int position)
  {
    Object update = selector.getObject();
    if (update == null) {
      return;
    }

    Union union = getOrCreateUnion(buf, position);
    SketchAggregator.updateUnion(union, update);
  }

  @Override
  public Object get(ByteBuffer buf, int position)
  {
    Int2ObjectMap<Union> unionMap = unions.get(buf);
    Union union = unionMap != null ? unionMap.get(position) : null;
    if (union == null) {
      return SketchHolder.EMPTY;
    }
    //in the code below, I am returning SetOp.getResult(true, null)
    //"true" returns an ordered sketch but slower to compute than unordered sketch.
    //however, advantage of ordered sketch is that they are faster to "union" later
    //given that results from the aggregator will be combined further, it is better
    //to return the ordered sketch here
    return SketchHolder.of(union.getResult(true, null));
  }

  private Union getOrCreateUnion(ByteBuffer buf, int position)
  {
    Int2ObjectMap<Union> unionMap = unions.get(buf);
    Union union = unionMap != null ? unionMap.get(position) : null;
    if (union != null) {
      return union;
    }
    return createNewUnion(buf, position, true);
  }

  private Union createNewUnion(ByteBuffer buf, int position, boolean isWrapped)
  {
    WritableMemory mem = getMemory(buf).writableRegion(position, maxIntermediateSize);
    Union union = isWrapped
                  ? (Union) SetOperation.wrap(mem)
                  : (Union) SetOperation.builder().setNominalEntries(size).build(Family.UNION, mem);
    Int2ObjectMap<Union> unionMap = unions.get(buf);
    if (unionMap == null) {
      unionMap = new Int2ObjectOpenHashMap<>();
      unions.put(buf, unionMap);
    }
    unionMap.put(position, union);
    return union;
  }

  @Override
  public float getFloat(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public long getLong(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public double getDouble(ByteBuffer buf, int position)
  {
    throw new UnsupportedOperationException("Not implemented");
  }

  @Override
  public void close()
  {
    unions.clear();
    memCache.clear();
  }

  @Override
  public void inspectRuntimeShape(RuntimeShapeInspector inspector)
  {
    inspector.visit("selector", selector);
  }

  @Override
  public void relocate(int oldPosition, int newPosition, ByteBuffer oldBuffer, ByteBuffer newBuffer)
  {
    createNewUnion(newBuffer, newPosition, true);
    Int2ObjectMap<Union> unionMap = unions.get(oldBuffer);
    if (unionMap != null) {
      unionMap.remove(oldPosition);
      if (unionMap.isEmpty()) {
        unions.remove(oldBuffer);
        memCache.remove(oldBuffer);
      }
    }
  }

  private WritableMemory getMemory(ByteBuffer buffer)
  {
    WritableMemory mem = memCache.get(buffer);
    if (mem == null) {
      mem = WritableMemory.wrap(buffer);
      memCache.put(buffer, mem);
    }
    return mem;
  }

}


text:
package site.huozhu.home.controller.form;

/**
 * Created by chuanxue.mcx on 2017/1/15.
 */
public class FolderCreateForm {

    private String name;
    private String nickname;
    private String pwd;
    private Long   parent;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Long getParent() {
        return parent;
    }

    public void setParent(Long parent) {
        this.parent = parent;
    }
}


text:
.class Lcom/mediatek/bluetooth/pan/BluetoothPanService$4;
.super Landroid/os/Handler;
.source "BluetoothPanService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/mediatek/bluetooth/pan/BluetoothPanService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/mediatek/bluetooth/pan/BluetoothPanService;

# direct methods
.method constructor <init>(Lcom/mediatek/bluetooth/pan/BluetoothPanService;)V
    .locals 0
    .parameter

    .prologue
    .line 1149
    iput-object p1, p0, Lcom/mediatek/bluetooth/pan/BluetoothPanService$4;->this$0:Lcom/mediatek/bluetooth/pan/BluetoothPanService;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 5
    .parameter "msg"

    .prologue
    .line 1154
    invoke-super {p0, p1}, Landroid/os/Handler;->handleMessage(Landroid/os/Message;)V

    .line 1156
    const-string v2, "[BT][PAN][BluetoothPANService]"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string v4, "handleMessage(): "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, p1, Landroid/os/Message;->what:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 1158
    invoke-virtual {p1}, Landroid/os/Message;->getData()Landroid/os/Bundle;

    move-result-object v0

    .line 1159
    .local v0, data:Landroid/os/Bundle;
    if-eqz v0, :cond_0

    const-string v2, "show toast"

    invoke-virtual {v0, v2}, Landroid/os/Bundle;->getString(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v1

    .line 1160
    .local v1, toastMsg:Ljava/lang/String;
    :goto_0
    iget v2, p1, Landroid/os/Message;->what:I

    packed-switch v2, :pswitch_data_0

    .line 1167
    :goto_1
    return-void

    .line 1159
    .end local v1           #toastMsg:Ljava/lang/String;
    :cond_0
    const/4 v1, 0x0

    goto :goto_0

    .line 1162
    .restart local v1       #toastMsg:Ljava/lang/String;
    :pswitch_0
    iget-object v2, p0, Lcom/mediatek/bluetooth/pan/BluetoothPanService$4;->this$0:Lcom/mediatek/bluetooth/pan/BluetoothPanService;

    #getter for: Lcom/mediatek/bluetooth/pan/BluetoothPanService;->mContext:Landroid/content/Context;
    invoke-static {v2}, Lcom/mediatek/bluetooth/pan/BluetoothPanService;->access$1300(Lcom/mediatek/bluetooth/pan/BluetoothPanService;)Landroid/content/Context;

    move-result-object v2

    const/4 v3, 0x1

    invoke-static {v2, v1, v3}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;

    move-result-object v2

    invoke-virtual {v2}, Landroid/widget/Toast;->show()V

    goto :goto_1

    .line 1160
    :pswitch_data_0
    .packed-switch 0x0
        :pswitch_0
    .end packed-switch
.end method


text:
/* $Id: QIArrowButtonSwitch.cpp $ */
/** @file
 * VBox Qt GUI - QIArrowButtonSwitch class implementation.
 */

/*
 * Copyright (C) 2006-2014 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else  /* !VBOX_WITH_PRECOMPILED_HEADERS */

/* Qt includes: */
# include <QKeyEvent>

/* GUI includes: */
# include "QIArrowButtonSwitch.h"

#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */

QIArrowButtonSwitch::QIArrowButtonSwitch(QWidget *pParent /* = 0 */)
    : QIRichToolButton(pParent)
    , m_buttonState(ButtonState_Collapsed)
{
    /* Update icon: */
    updateIcon();
}

void QIArrowButtonSwitch::setIconForButtonState(QIArrowButtonSwitch::ButtonState buttonState, const QIcon &icon)
{
    /* Assign icon: */
    m_icons[buttonState] = icon;
    /* Update icon: */
    updateIcon();
}

void QIArrowButtonSwitch::sltButtonClicked()
{
    /* Toggle button-state: */
    m_buttonState = m_buttonState == ButtonState_Collapsed ?
                    ButtonState_Expanded : ButtonState_Collapsed;
    /* Update icon: */
    updateIcon();
}

void QIArrowButtonSwitch::keyPressEvent(QKeyEvent *pEvent)
{
    /* Handle different keys: */
    switch (pEvent->key())
    {
        /* Animate-click for the Space key: */
        case Qt::Key_Minus: if (m_buttonState == ButtonState_Expanded) return animateClick(); break;
        case Qt::Key_Plus: if (m_buttonState == ButtonState_Collapsed) return animateClick(); break;
        default: break;
    }
    /* Call to base-class: */
    QIRichToolButton::keyPressEvent(pEvent);
}

void QIArrowButtonSwitch::updateIcon()
{
    setIcon(m_icons.value(m_buttonState));
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Event Details</title>

    <link rel="stylesheet" href="stylesheets/CategoryEvents.css">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
    <link rel="stylesheet" href="bootstrapcss/bootstrap.min.css">

    <link rel="stylesheet" href="cssFiles/index.css">

            <button style="margin-top: 20px;background-color: #9D9D9D;" type="button" class="btn" onclick="goBack()"></button>

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

        </button>

        <button type="button" style="margin-top: -20px;" class="btn btn-info btn-lg" id="logoutButton" onclick="logout()">Logout</button>

        <button class="btn btn-sm" id="likeButton"> Like</button>
        <button class="btn btn-sm" id="disLikeButton"> Dislike</button>
        <button style="color: white; background-color: #ff8000 " id="eventTicketButton" class="btn btn-sm"> Tickets</button>

FOR MORE INFORMATION

Full details are available on the site at

  Organizer :

  See more at :

  Event Date :

  Location :

 COMMENTS

                    <textarea class="form-control" rows="3"></textarea>

                <button id="getDir" type="button" class="btn btn-block btn-success" >GET DIRECTIONS</button>

                <button id="uber" type="button" class="btn btn-block" >U B E R</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Uber options for you

            Copyright © Tech Patriots. 2015. All rights reserved.

            Boston, Massachusetts


text:
Solutions for the first laboratory work. This code isn't pretty
and I feel ashamed for this but this is my first Win32 application.

Encoding of all files except this file: Windows-1251.

------------------------------

Решения первой лабораторной работы. Код не красивый и мне за него стыдно,
но это - мое первое Win32-приложение.

Кодировка всех файлов, кроме этого: Windows-1251.


text:
/**
 * @file LinearTransforms.cpp
 * @brief Simple program to change contrast and brightness
 * @date Mon, June 6, 2011
 * @author OpenCV team
 */

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"

using namespace cv;

/** Global Variables */
const int alpha_max = 5;
const int beta_max = 125;
int alpha; /**< Simple contrast control */
int beta;  /**< Simple brightness control*/

/** Matrices to store images */
Mat image;

/**
 * @function on_trackbar
 * @brief Called whenever any of alpha or beta changes
 */
static void on_trackbar( int, void* )
{
    Mat new_image = Mat::zeros( image.size(), image.type() );

    for( int y = 0; y < image.rows; y++ )
        for( int x = 0; x < image.cols; x++ )
            for( int c = 0; c < 3; c++ )
                new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*( image.at<Vec3b>(y,x)[c] ) + beta );

    imshow("New Image", new_image);
}

/**
 * @function main
 * @brief Main function
 */
int main( int argc, char** argv )
{
   /// Read image given by user
   String imageName("../data/lena.jpg"); // by default
   if (argc > 1)
   {
      imageName = argv[1];
   }
   image = imread( imageName );

   /// Initialize values
   alpha = 1;
   beta = 0;

   /// Create Windows
   namedWindow("Original Image", 1);
   namedWindow("New Image", 1);

   /// Create Trackbars
   createTrackbar( "Contrast", "New Image", &alpha, alpha_max, on_trackbar );
   createTrackbar( "Brightness", "New Image", &beta, beta_max, on_trackbar );

   /// Show some stuff
   imshow("Original Image", image);
   imshow("New Image", image);

   /// Wait until user press some key
   waitKey();
   return 0;
}


text:
import React, { Component } from 'react'

import Constants from 'Constants'
import MaxAvailableSpaceContainer from 'common/components/MaxAvailableSpaceContainer'
import { withLocation } from 'common/hooks'

class SurveEditPage extends Component {
  render() {
    const path = this.props.location.pathname
    const surveyId = path.substring(path.lastIndexOf('/') + 1)
    return (
      <MaxAvailableSpaceContainer>
        <iframe
          src={Constants.BASE_URL + 'zk/surveydesigner/survey_edit.zul?id=' + surveyId}
          title="Open Foris Collect - Survey Designer"
          width="100%"
          height="100%"
        />
      </MaxAvailableSpaceContainer>
    )
  }
}

export default withLocation(SurveEditPage)


text:
<?php

/*

	EDIT GROUP
		cyle gage, emerson college, 2014

*/

$login_required = true;
require_once('/median-webapp/includes/login_check.php');

require_once('/median-webapp/includes/error_functions.php');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
	bailout('No valid ID provided.', $current_user['userid']);
}

$gid = (int) $_GET['id'] * 1;

require_once('/median-webapp/includes/permission_functions.php');
require_once('/median-webapp/includes/meta_functions.php');
require_once('/median-webapp/includes/user_functions.php');
require_once('/median-webapp/includes/group_functions.php');

$meta_info = getGroupInfo($gid);

if ($meta_info == false) {
	// uhh media does not exist!
	bailout('Sorry, but a group with that ID does not exist!', $current_user['userid']);
}

// permission checks
$can_user_edit = canEditGroup($current_user['userid'], $gid);

if (!$can_user_edit) {
	bailout('Sorry, but you do not have permission to edit this group.', $current_user['userid']);
}

$page_uuid = 'edit-group-page';
$page_title = 'Editing '.$meta_info['n'];
require_once('/median-webapp/includes/header.php');
?>

<?php echo ''; ?>

Edit Group

        <form action="/submit/edit/group/" method="post" id="group-form" enctype="multipart/form-data">
        <input type="hidden" name="gid" value="<?php echo $gid; ?>" />

                Name:

                <input type="text" value="<?php echo $meta_info['n']; ?>" id="group-name" placeholder="The Cool Kids Group" name="n" />

                Visibility:

                <select class="five" name="ul">
                    <option value="0"<?php echo (($meta_info['v'] == 0) ? ' selected="selected"': ''); ?>>Members Only</option>
                    <?php if ($current_user['userlevel'] == 1) { ?><option value="1"<?php echo (($meta_info['v'] == 1) ? ' selected="selected"': ''); ?>>Admins Only</option><?php } ?>
                    <?php if ($current_user['userlevel'] < 5) { ?><option value="4"<?php echo (($meta_info['v'] == 4) ? ' selected="selected"': ''); ?>>Faculty Only</option><?php } ?>
                    <option value="5"<?php echo (($meta_info['v'] == 5) ? ' selected="selected"': ''); ?>>Just Logged-in People</option>
                    <option value="6"<?php echo (($meta_info['v'] == 6) ? ' selected="selected"': ''); ?>>Publicly Visible</option>
                </select>

                Brief Description / Tagline:

                <input type="text" value="<?php if (isset($meta_info['sd'])) { echo $meta_info['sd']; } ?>" name="sd" />

                Description:

                <textarea name="d"><?php if (isset($meta_info['d'])) { echo $meta_info['d']; } ?></textarea>

                iTunes Artwork:

                <input type="file" name="a" /> (Optional; JPG only; 200kb limit; leave alone to keep existing.)

Edit Members

Start typing an ECNet name and select the user from the auto-complete list. Please note that users must have logged into median at least once to be included in that list. Selecting a user as an owner will allow them to edit the group info, member list, and everything associated with the group.

                Add Member:

                <input type="text" id="add-member" />

Owner?	Username

						<?php
						$members = getGroupMembers($gid);
						$owners = getGroupOwners($gid, true);
						foreach ($members as $member) {
							echo '
';
							echo '<input type="hidden" class="member-id" name="m[]" value="'.$member['uid'].'" /><input type="checkbox" '.((in_array($member['uid'], $owners)) ? 'checked="checked"': '').' class="owner-checkbox" name="o[]" value="'.$member['uid'].'" />	';
							echo ''.$member['ecnet'].'	';
							echo '<input type="button" value="remove?" class="button small secondary remove-member-btn" />	';
							echo '
';
						}
						?>

        <input type="submit" value="Save" class="button large" />
        </form>

Delete Group

This will delete the group entirely. It will not delete any media, but will remove the group's ownership of media, events, and categories.

        <a href="/delete/group/<?php echo $gid ?>/" class="delete-major-btn button small alert">Delete Group!

<?php
require_once('/median-webapp/includes/footer.php');


text:
import { schema } from 'normalizr';

export const issueSchema = new schema.Entity(
  'issues',
  {},
  {
    idAttribute: issue => issue.url,
  }
);

// TODO: some events have no id field, i.e. cross-referenced
export const issueTimelineItemSchema = new schema.Entity('issueTimelineItems');


text:
<?xml version='1.0' encoding='utf-8'?>
<widget android-versionCode="1" id="com.your.company.h3notification" ios-CFBundleVersion="1.1.1" version="0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>h3notification</name>
    <description>Plain text description of this app</description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">Author name and email</author>
    <content src="plugins/org.chromium.bootstrap/chromeapp.html" />
    <access origin="http://*/*" />
    <access origin="https://*/*" />
</widget>


text:
package catan.common.game.replays;

import catan.common.event.InternalEvent;

/**
 * Created by greg on 7/9/17.
 * Type of event defining events that can occur to a replay.
 */
public class ReplayEvent extends InternalEvent<ReplayListener, ReplayEventType> {

    protected ReplayEvent(ReplayListener origin, ReplayEventType type, Object payload) {
        super(origin, type, payload);
    }
}


text:
<?php
/**
 * This file is part of the PHP Generics package.
 *
 * @package Generics
 */
namespace Generics\Logger;

use Psr\Log\LogLevel;

/**
 * This class is a standard reference implementation of the PSR LoggerInterface.
 *
 * It logs everything to console. Depending on level it is written to stdout or stderr.
 *
 * @author Maik Greubel <greubel@nkey.de>
 */
class ConsoleLogger extends BasicLogger
{

    protected function logImpl($level, $message, array $context = array())
    {
        $channel = STDOUT;

        if ($level === LogLevel::ALERT || $level === LogLevel::CRITICAL || $level === LogLevel::EMERGENCY || $level === LogLevel::ERROR || $level === LogLevel::WARNING) {
            $channel = STDERR;
        }

        fwrite($channel, $this->getMessage($level, $message, $context)->read(4096));
    }
}


text:
/**
 *
 */
package de.is24.util.monitoring.jmx;

import javax.management.MBeanAttributeInfo;

/**
 * Null-object pattern implementation of {@link JmxReportable}.
 * Returns an empty attributes specification and therefore only null values.
 *
 * @author Stefan Schubert, IT-E, IS24
 */
final class NoJmxReportable implements JmxReportable {
  private static final MBeanAttributeInfo[] NONE = new MBeanAttributeInfo[0];

  private static final NoJmxReportable INSTANCE = new NoJmxReportable();

  public static NoJmxReportable getInstance() {
    return INSTANCE;
  }

  /**
   * Singleton, therefore no constructor.
   */
  private NoJmxReportable() {
  }

  /* (non-Javadoc)
   * @see de.is24.util.monitoring.jmx.JmxReportable#getAttributes()
   */
  public MBeanAttributeInfo[] getAttributes() {
    return NONE;
  }

  /* (non-Javadoc)
   * @see de.is24.util.monitoring.jmx.JmxReportable#getAttribute(java.lang.String)
   */
  public Object getAttribute(String attributeName) {
    return null;
  }
}


text:
package com.github.megatronking.svg.iconlibs;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;

import com.github.megatronking.svg.support.SVGRenderer;

/**
 * AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * SVG-Generator. It should not be modified by hand.
 */
public class ic_signal_cellular_null extends SVGRenderer {

    public ic_signal_cellular_null(Context context) {
        super(context);
        mAlpha = 1.0f;
        mWidth = dip2px(24.0f);
        mHeight = dip2px(24.0f);
    }

    @Override
    public void render(Canvas canvas, int w, int h, ColorFilter filter) {
        final float scaleX = w / 24.0f;
        final float scaleY = h / 24.0f;

        mPath.reset();
        mRenderPath.reset();

        mFinalPathMatrix.setValues(new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f});
        mFinalPathMatrix.postScale(scaleX, scaleY);

        mPath.moveTo(20.0f, 6.83f);
        mPath.lineTo(20.0f, 20.0f);
        mPath.lineTo(6.83f, 20.0f);
        mPath.lineTo(20.0f, 6.83f);
        mPath.moveTo(22.0f, 2.0f);
        mPath.lineTo(2.0f, 22.0f);
        mPath.rLineTo(20.0f, 0f);
        mPath.lineTo(22.0f, 2.0f);
        mPath.close();
        mPath.moveTo(22.0f, 2.0f);

        mRenderPath.addPath(mPath, mFinalPathMatrix);
        if (mFillPaint == null) {
            mFillPaint = new Paint();
            mFillPaint.setStyle(Paint.Style.FILL);
            mFillPaint.setAntiAlias(true);
        }
        mFillPaint.setColor(applyAlpha(-16777216, 1.0f));
        mFillPaint.setColorFilter(filter);
        canvas.drawPath(mRenderPath, mFillPaint);

    }

}


text:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/mman.h>
#include <sys/queue.h>

#include <rte_memory.h>
#include <rte_eal.h>
#include <rte_eal_memconfig.h>
#include <rte_log.h>

#include "eal_private.h"
#include "eal_internal_cfg.h"

/*
 * Return a pointer to a read-only table of struct rte_physmem_desc
 * elements, containing the layout of all addressable physical
 * memory. The last element of the table contains a NULL address.
 */
const struct rte_memseg *
rte_eal_get_physmem_layout(void)
{
	return rte_eal_get_configuration()->mem_config->memseg;
}

/* get the total size of memory */
uint64_t
rte_eal_get_physmem_size(void)
{
	const struct rte_mem_config *mcfg;
	unsigned i = 0;
	uint64_t total_len = 0;

	/* get pointer to global configuration */
	mcfg = rte_eal_get_configuration()->mem_config;

	for (i = 0; i < RTE_MAX_MEMSEG; i++) {
		if (mcfg->memseg[i].addr == NULL)
			break;

		total_len += mcfg->memseg[i].len;
	}

	return total_len;
}

/* Dump the physical memory layout on console */
void
rte_dump_physmem_layout(FILE *f)
{
	const struct rte_mem_config *mcfg;
	unsigned i = 0;

	/* get pointer to global configuration */
	mcfg = rte_eal_get_configuration()->mem_config;

	for (i = 0; i < RTE_MAX_MEMSEG; i++) {
		if (mcfg->memseg[i].addr == NULL)
			break;

		fprintf(f, "Segment %u: IOVA:0x%"PRIx64", len:%zu, "
		       "virt:%p, socket_id:%"PRId32", "
		       "hugepage_sz:%"PRIu64", nchannel:%"PRIx32", "
		       "nrank:%"PRIx32"\n", i,
		       mcfg->memseg[i].iova,
		       mcfg->memseg[i].len,
		       mcfg->memseg[i].addr,
		       mcfg->memseg[i].socket_id,
		       mcfg->memseg[i].hugepage_sz,
		       mcfg->memseg[i].nchannel,
		       mcfg->memseg[i].nrank);
	}
}

/* return the number of memory channels */
unsigned rte_memory_get_nchannel(void)
{
	return rte_eal_get_configuration()->mem_config->nchannel;
}

/* return the number of memory rank */
unsigned rte_memory_get_nrank(void)
{
	return rte_eal_get_configuration()->mem_config->nrank;
}

static int
rte_eal_memdevice_init(void)
{
	struct rte_config *config;

	if (rte_eal_process_type() == RTE_PROC_SECONDARY)
		return 0;

	config = rte_eal_get_configuration();
	config->mem_config->nchannel = internal_config.force_nchannel;
	config->mem_config->nrank = internal_config.force_nrank;

	return 0;
}

/* Lock page in physical memory and prevent from swapping. */
int
rte_mem_lock_page(const void *virt)
{
	unsigned long virtual = (unsigned long)virt;
	int page_size = getpagesize();
	unsigned long aligned = (virtual & ~(page_size - 1));
	return mlock((void *)aligned, page_size);
}

/* init memory subsystem */
int
rte_eal_memory_init(void)
{
	RTE_LOG(DEBUG, EAL, "Setting up physically contiguous memory...\n");

	const int retval = rte_eal_process_type() == RTE_PROC_PRIMARY ?
			rte_eal_hugepage_init() :
			rte_eal_hugepage_attach();
	if (retval < 0)
		return -1;

	if (internal_config.no_shconf == 0 && rte_eal_memdevice_init() < 0)
		return -1;

	return 0;
}


text:
package net.omniscimus.profielwerkstuk;

import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.omniscimus.profielwerkstuk.configuration.ConfigurationManager;
import net.omniscimus.profielwerkstuk.mysql.MySQLManager;
import net.omniscimus.profielwerkstuk.net.NetworkManager;
import net.omniscimus.profielwerkstuk.ui.UIManager;
import net.omniscimus.profielwerkstuk.text.FileManager;

/**
 * Main class voor dit project.
 *
 * @author omniscimus
 */
public class ScheduleChanges {

    private ConfigurationManager configurationManager;
    private FileManager fileManager;
    private MySQLManager mySQLManager;
    private NetworkManager networkManager;
    private UIManager uiManager;

    /**
     * Geeft de DownloadScheduler van dit programma.
     *
     * @return de DownloadScheduler die dit programma gebruikt
     */
    public FileManager getFileManager() {
	return fileManager;
    }

    /**
     * Geeft de MySQLManager van dit programma.
     *
     * @return de MySQLManager die dit programma gebruikt
     */
    public MySQLManager getMySQLManager() {
	return mySQLManager;
    }

    /**
     * Main method van de class, aangeroepen als het programma start.

     * Flags:

     *

     *
-n: print beschikbare network interfaces en sluit af

     *

     *
     * @param args de command-line arguments
     */
    public static void main(String[] args) {
	for (String arg : args) {
	    switch (arg) {
		case "-n":
		    NetworkManager.printNetworkInterfaces();
		    System.exit(0);
		    break;
	    }
	}
	new ScheduleChanges().initiate();
    }

    /**
     * Start het programma.
     */
    public void initiate() {

	// Load de config values.
	configurationManager = new ConfigurationManager(this);
	try {
	    configurationManager.loadConfig();
	} catch (IOException | URISyntaxException ex) {
	    Logger.getLogger(ScheduleChanges.class.getName()).log(
		    Level.SEVERE, "Configuratie kon niet geladen worden", ex);
	    shutdown("Kon de configuratie niet laden.", false);
	}

	// Start de MySQL verbinding.
	try {
	    mySQLManager = new MySQLManager();
	} catch (SQLException | ClassNotFoundException ex) {
	    Logger.getLogger(ScheduleChanges.class.getName()).log(
		    Level.SEVERE, "MySQL kon niet geladen worden", ex);
	    shutdown(ex.getMessage(), false);
	}

	// Start een scheduler die elk uur kijkt of er een nieuw bestand is op de server
	fileManager = new FileManager(this);
	fileManager.load();

	// Start de User Interface.
	uiManager = new UIManager(this);
	uiManager.load();

	// Laad de netwerkmanager en start een scan interval.
	networkManager = new NetworkManager(this);
	networkManager.load();

    }

    /**
     * Stopt het programma.
     *
     * @param error een bericht met de reden voor de shutdown
     * @param force true als het programma onmiddelijk moet worden afgesloten;
     * anders false
     */
    public void shutdown(String error, boolean force) {
	System.out.println(error);
	shutdown(force);
    }

    /**
     * Stopt het programma.
     *
     * @param force true als het programma onmiddelijk moet worden afgesloten;
     * anders false
     */
    public void shutdown(boolean force) {
	if (!force) {
	    networkManager.stop();
	    uiManager.stop();
	    fileManager.stop();
	    if (mySQLManager != null) {
		mySQLManager.closeConnection();
	    }
	}
	System.exit(0);
    }

}