text:
package org.reldb.dbrowser.ui.content.recent;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.layout.RowLayout;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Rectangle;
import org.reldb.dbrowser.Core;
import org.reldb.dbrowser.DBrowser;
import org.reldb.dbrowser.ui.DbTab;
import org.reldb.dbrowser.ui.IconLoader;

public class RecentPanel extends ScrolledComposite {

	private void createItem(Composite parent, String prompt, String iconName, String dbURL, Listener action) {
		boolean enabled = true;
		if (dbURL != null)
			enabled = Core.databaseMayExist(dbURL);

		Composite panel = new Composite(parent, SWT.TRANSPARENT);
		panel.setLayout(new RowLayout(SWT.VERTICAL));

		Composite topPanel = new Composite(panel, SWT.TRANSPARENT);
		topPanel.setLayout(new RowLayout(SWT.HORIZONTAL));

		Button icon = new Button(topPanel, SWT.FLAT);
		icon.setImage(IconLoader.loadIcon(iconName));
		icon.addListener(SWT.Selection, action);
		icon.setEnabled(enabled);

		if (dbURL != null) {
			Button removeButton = new Button(topPanel, SWT.NONE);
			removeButton.setText("X");
			removeButton.setToolTipText("Remove this entry from this list of recently-used databases." + ((enabled) ? " The database will not be deleted." : ""));
			removeButton.addListener(SWT.Selection, e -> {
				Core.removeFromRecentlyUsedDatabaseList(dbURL);
				((DbTabContentRecent)getParent()).redisplayed();
			});
		}

		Label urlButton = new Label(panel, SWT.NONE);
		urlButton.setText(prompt);
		urlButton.addListener(SWT.MouseUp, action);
		if (!enabled)
			urlButton.setForeground(getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_FOREGROUND));
	}

	private Composite obtainContent() {
		Composite content = new Composite(this, SWT.TRANSPARENT);

		RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
		rowLayout.wrap = true;
		rowLayout.pack = false;
		content.setLayout(rowLayout);

		if (DBrowser.hasLocalRel()) {
			createItem(content, "Create a new database", "large_database_create", null, e -> Core.newDatabase());
			createItem(content, "Create a new database\nfrom a backup", "large_database_restore", null, e -> Core.restoreDatabase());
			createItem(content, "Open a local database", "large_database_load", null, e -> Core.openLocalDatabase());
		}
		createItem(content, "Open a remote database", "large_database_load", null, e -> Core.openRemoteDatabase());
		for (String dbURL: Core.getRecentlyUsedDatabaseList()) {
			if (dbURL.startsWith("db:") && !DBrowser.hasLocalRel())
				continue;
			createItem(content,
					"Open " + dbURL,
					"large_database_load",
					dbURL,
					e -> Core.openDatabase(dbURL));
		}

		return content;
	}

	/**
	 * Create the composite.
	 *
	 * @param parent
	 * @param style
	 */
	public RecentPanel(DbTabContentRecent parent, DbTab dbTab) {
		super(parent, SWT.V_SCROLL | SWT.TRANSPARENT);

		Composite content = obtainContent();

		setContent(content);
		setExpandVertical(true);
		setExpandHorizontal(true);

		addListener(SWT.Resize, e -> {
			Rectangle clientArea = getClientArea();
			setMinSize(content.computeSize(clientArea.width, SWT.DEFAULT));
		});
	}
}


text: Phinx database migration extension for Nette Framework

redpajama_set_name: RedPajamaGithub


text:
package com.leansoft.nano.demo;

import java.math.BigInteger;
import java.util.ArrayList;

import com.amazon.service.ecommerce.AWSECommerceClient;
import com.amazon.webservices.awsecommerceservice._2011_08_01.Cart;
import com.amazon.webservices.awsecommerceservice._2011_08_01.CartCreate;
import com.amazon.webservices.awsecommerceservice._2011_08_01.CartCreateRequest;
import com.amazon.webservices.awsecommerceservice._2011_08_01.CartCreateResponse;
import com.amazon.webservices.awsecommerceservice._2011_08_01.Errors;
import com.amazon.webservices.awsecommerceservice._2011_08_01.Item;
import com.amazon.webservices.awsecommerceservice._2011_08_01.Offer;
import com.amazon.webservices.awsecommerceservice._2011_08_01.OfferListing;
import com.amazon.webservices.awsecommerceservice._2011_08_01.Offers;
import com.amazon.webservices.awsecommerceservice._2011_08_01.cartcreaterequest.Items;
import com.amazon.webservices.awsecommerceservice._2011_08_01.client.AWSECommerceServicePortType_SOAPClient;
import com.github.droidfu.widgets.WebImageView;
import com.leansoft.nano.log.ALog;
import com.leansoft.nano.sample.R;
import com.leansoft.nano.ws.SOAPServiceCallback;

import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;

public class DetailsActivity extends Activity {

	private static final String TAG = DetailsActivity.class
			.getSimpleName();

	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_detail);

		Item item = (Item) getIntent().getSerializableExtra("ITEM");
		this.updateUI(item);
	}

	private void updateUI(Item item) {
		// item title
		TextView titleView = (TextView) findViewById(R.id.detail_title);
		titleView.setText(item.itemAttributes.title);

		// list price
		TextView priceView = (TextView) findViewById(R.id.detail_price);
		if (item.itemAttributes.listPrice != null) {
			priceView.setText(Html.fromHtml("<b>List Price : </b>  " + item.itemAttributes.listPrice.formattedPrice));
			priceView.setTextColor(Color.BLUE);
		}

		// author
		TextView authorView = (TextView) findViewById(R.id.detail_author);
		authorView.setText(Html.fromHtml("<b>Author : </b>  " + item.itemAttributes.author.get(0)));

		// edition
		TextView bindingView = (TextView) findViewById(R.id.detail_binding);
		bindingView.setText(Html.fromHtml("<b>Binding : </b>  " + item.itemAttributes.binding));

		// edition
		TextView editionView = (TextView) findViewById(R.id.detail_edition);
		editionView.setText(Html.fromHtml("<b>Edition : </b>  " + item.itemAttributes.edition));

		// publisher
		TextView publisherView = (TextView) findViewById(R.id.detail_publisher);
		publisherView.setText(Html.fromHtml("<b>Publisher : </b>  " + item.itemAttributes.publisher));

		// pubdate
		TextView pubdateView = (TextView) findViewById(R.id.detail_pubdate);
		pubdateView.setText(Html.fromHtml("<b>Publish Date : </b>  " + item.itemAttributes.publicationDate));

		// item image
		WebImageView image = (WebImageView) findViewById(R.id.detail_image);
		if (item.mediumImage != null && item.mediumImage.url != null) {
			image.setImageUrl(item.mediumImage.url);
			image.loadImage();
		} else {
			image.setNoImageDrawable(R.drawable.placeholder);
		}
		image.setVisibility(View.VISIBLE);

		// add item to shopping cart
		final Button addBtn = (Button) findViewById(R.id.btn_add);
		addBtn.setOnClickListener(new AddToCartListener(item));
		addBtn.setVisibility(View.VISIBLE);
	}

	private class AddToCartListener implements OnClickListener {
		private Item item;

		public AddToCartListener(Item item) {
			this.item = item;
		}

		@Override
		public void onClick(View v) {
			addToCart(item);
		}
	}

	public void addToCart(Item item) {
		if (!this.checkAvailibility(item)) {
			Toast.makeText(DetailsActivity.this, "Can't add to cart, item not available", Toast.LENGTH_LONG).show();
			return;
		}

    	progressDialog = ProgressDialog.show(DetailsActivity.this,
        		"Please wait...", "Retrieving data...", true, true);

		// Get shared client
		AWSECommerceServicePortType_SOAPClient client = AWSECommerceClient.getSharedClient();
		client.setDebug(true);

		// create request
		CartCreate request = new CartCreate();
		request.associateTag = "tag";

		CartCreateRequest cartCreateRequest = new CartCreateRequest();
		cartCreateRequest.items = new Items();
		cartCreateRequest.items.item = new ArrayList<com.amazon.webservices.awsecommerceservice._2011_08_01.cartcreaterequest.items.Item>();
		com.amazon.webservices.awsecommerceservice._2011_08_01.cartcreaterequest.items.Item cartCreateItem =
				    new com.amazon.webservices.awsecommerceservice._2011_08_01.cartcreaterequest.items.Item();
		cartCreateItem.asin = item.asin;
		cartCreateItem.quantity = BigInteger.valueOf(1);
		cartCreateRequest.items.item.add(cartCreateItem);

		request.shared = cartCreateRequest;
		request.shared.responseGroup = new ArrayList<String>();
		request.shared.responseGroup.add("Cart");

	    // authenticate the request
	    // see : http://docs.aws.amazon.com/AWSECommerceService/latest/DG/NotUsingWSSecurity.html
		AWSECommerceClient.authenticateRequest("CartCreate");
		// make API call with registered callbacks
		client.cartCreate(request, new SOAPServiceCallback<CartCreateResponse>() {

			@Override
			public void onSuccess(CartCreateResponse responseObject) {
	    		if (progressDialog != null) {
    			    progressDialog.dismiss();
    			    progressDialog = null;
    		    }

	    		Cart cart = responseObject.cart.get(0);
	    		if (cart != null) {
	    			if ("True".equals(cart.request.isValid)) {

	    				// Purchase on Amazon
	    				Button purchaseBtn = (Button) findViewById(R.id.btn_purchase);
	    				purchaseBtn.setOnClickListener(new PurchaseOnAmazonListener(
	    						cart.purchaseURL));
	    				purchaseBtn.setVisibility(View.VISIBLE);

	    				Toast.makeText(DetailsActivity.this, "Item was added to your shopping cart successfully", Toast.LENGTH_LONG).show();

	    			} else {
	    				Toast.makeText(DetailsActivity.this, "Invalid request", Toast.LENGTH_LONG).show();
	    			}
	    		} else { // response resident error
					if (responseObject.operationRequest != null && responseObject.operationRequest.errors != null) {
						Errors errors = responseObject.operationRequest.errors;
						if (errors.error != null && errors.error.size() > 0) {
							com.amazon.webservices.awsecommerceservice._2011_08_01.errors.Error error = errors.error.get(0);
							Toast.makeText(DetailsActivity.this, error.message, Toast.LENGTH_LONG).show();
						} else {
							Toast.makeText(DetailsActivity.this, "No result", Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(DetailsActivity.this, "No result", Toast.LENGTH_LONG).show();
					}
	    		}

			}

			@Override
			public void onFailure(Throwable error, String errorMessage) { // http or parse error
	    		if (progressDialog != null) {
    			    progressDialog.dismiss();
    			    progressDialog = null;
    		    }

				ALog.e(TAG, errorMessage);
				Toast.makeText(DetailsActivity.this, errorMessage, Toast.LENGTH_LONG).show();
			}

			@Override
			public void onSOAPFault(Object soapFault) { // soap fault
	    		if (progressDialog != null) {
    			    progressDialog.dismiss();
    			    progressDialog = null;
    		    }

				com.leansoft.nano.soap11.Fault fault = (com.leansoft.nano.soap11.Fault)soapFault;

				ALog.e(TAG, fault.faultstring);

				Toast.makeText(DetailsActivity.this, fault.faultstring, Toast.LENGTH_LONG).show();
			}

		});
	}

	public boolean checkAvailibility(Item item) {
		Offers offers = item.offers;
		if (offers.totalOffers.longValue() > 0) {
			Offer offer = offers.offer.get(0);
			OfferListing offerListing = offer.offerListing.get(0);
			if (offerListing.availability != null) {
				return true;
			}
		}

		return false;
	}

	// Purchase on Amazon Mobile Web
	private class PurchaseOnAmazonListener implements View.OnClickListener {

		private String purchaseUrl;

		public PurchaseOnAmazonListener(String purchaseUrl) {
			this.purchaseUrl = purchaseUrl;
		}

		@Override
		public void onClick(View arg0) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(purchaseUrl));
			startActivity(browserIntent);

		}

	}

}


text:
A simple asset packer for luxe alpha versions (and other haxe projects).

![](screenshot.png)

# build

`flow run` as a regular luxe project in `tool/`

# requires
- `luxe`
- `mint`
- `linc_dialogs`

# targets

Works for native (mac/windows/linux/android/ios) and web targets.

Used in a few games like [Westport Independent](http://www.doublezeroonezero.com/westport.html) and the [THREES web port](http://play.threesgame.com/).

# tool usage

- click `add folder` to add an asset folder to the session
- once added, assets will be selectable to include in the built parcel
- use select all/none to toggle selections
- click `build` to generate the packed parcel file
- when hovering an asset, spacebar can be used to "quickview" the asset contents in a bigger view

# using the packed files, i.e Pack.hx usage

- This is the way you _use_ a packed parcel in your game
- Drop Pack.hx somewhere in your code
- see `test/` for a simple example
- The parcel is loaded as a whole, putting resources in to `Luxe.resources`
- Use the resources as usual

# using the packed file outside of luxe

The class that does the work for the asset packing and unpacking
doesn't have any dependencies, it uses plain haxe features.
An agnostic version is inside `non-luxe/Packer.hx`.

If you want to use this in any haxe project, you can customize
the types in the AssetPack easily and the rest will still work automatically.
The code is simple and small enough to customize to your own use case.

The asset packs generated by the tool should work for frameworks or code not using luxe, the asset unpacking simply undoes the packing / compression, you have to feed that to your framework as needed!

```haxe
    var to_pack:AssetPack = {
        bytes: ..
        ...
    }
    var bytes = Packer.compress_pack(to_pack);
    var unpacked = Packer.uncompress_pack(bytes);

    for(item in unpacked.bytes) {
        ..
    }
```

# important notes

- This tool was written very quickly, expect messy code (some [dev notes](http://snowkit.org/2015/08/10/snowkit-dev-log-6-community/#assetpackerround2))
- all asset types except streamed audio that luxe supports can be packed
- no streaming audio can be packed with this!
    + a path for audio/music is hardcoded internally to be ignored
- asset paths are relative to the `assets/` once added to the parcel
    + for example, add a folder called `assets/` with `assets/images/level.png`
    + in the packed assets it has the `id` of `assets/images/level.png`
    + when loading the packed assets, the id's will match this pattern
    + based on common usage, this should be transparent

# load time meta data
Some assets want to set load time settings, there is an optional meta file for these types of settings.

This file is currently manually created and matches the format of the parcel json info. Only the shader specifics are currently implemented. It should be in the root of your parcel.

- parcel-shaders-meta - json of [`ShaderInfo`](https://luxeengine.com/docs/api/luxe/ShaderInfo.html)

Other types for sounds and textures were partially implemented but not needed at the time. The UI for editing the metadata was also partially implemented but commented out.

# other notes

http://iconmonstr.com/

# contributing

Feel free to file issues or contributions.

Since this tool is a quick but useful tool written for the earlier alpha versions of luxe, I don't expect it to get significant reworking any time soon.

# license

MIT (LICENSE.md)


text:
package io.cattle.platform.iaas.api.auth.integration.internal.rancher;

import io.cattle.platform.core.model.Account;
import io.cattle.platform.iaas.api.auth.AbstractTokenUtil;
import io.cattle.platform.iaas.api.auth.SecurityConstants;
import io.cattle.platform.iaas.api.auth.integration.external.ExternalServiceTokenUtil;
import io.cattle.platform.iaas.api.auth.integration.interfaces.AccountLookup;
import io.cattle.platform.iaas.api.auth.integration.interfaces.TokenUtil;
import io.cattle.platform.util.type.NamedUtils;
import io.cattle.platform.util.type.Priority;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;

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

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;

public class TokenAuthLookup implements AccountLookup, Priority {

    Map<String, TokenUtil> tokenUtilsMap = new HashMap<String, TokenUtil>();
    @Inject
    List<TokenUtil> tokenUtils;

    @Inject
    ExternalServiceTokenUtil externalTokenUtil;

    @Override
    public int getPriority() {
        return Priority.PRE;
    }

    @PostConstruct
    public void init() {
        for (TokenUtil tu : tokenUtils) {
            tokenUtilsMap.put(NamedUtils.getName(tu), tu);
        }
    }

    @Override
    public Account getAccount(ApiRequest request) {
        if (!StringUtils.equals(AbstractTokenUtil.TOKEN, request.getType()) && isConfigured()) {
            tokenUtils().findAndSetJWT();
            return getAccountAccessInternal();
        }
        return null;
    }

    private Account getAccountAccessInternal() {
        return tokenUtils().getAccountFromJWT();
    }

    public Account getAccountAccess(String token, ApiRequest request) {
        if (!StringUtils.equals(AbstractTokenUtil.TOKEN, request.getType()) && isConfigured()) {
            request.setAttribute(tokenUtils().tokenType(), token);
            return getAccountAccessInternal();
        }
        return null;
    }

    private TokenUtil tokenUtils(){
        if (SecurityConstants.INTERNAL_AUTH_PROVIDERS.contains(SecurityConstants.AUTH_PROVIDER.get())) {
            TokenUtil tokenUtil = tokenUtilsMap.get(SecurityConstants.AUTH_PROVIDER.get());
            if (tokenUtil == null || !tokenUtil.isConfigured()) {
                throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, "TokenUtilNotConfigured");
            }
            return tokenUtil;
        } else {
            return externalTokenUtil;
        }
    }

    @Override
    public boolean challenge(ApiRequest request) {
        return false;
    }

    @Override
    public String getName() {
        return "TokenAuth";
    }

    @Override
    public boolean isConfigured() {
        return StringUtils.isNotBlank(SecurityConstants.AUTH_PROVIDER.get())
                && !SecurityConstants.NO_PROVIDER.equalsIgnoreCase(SecurityConstants.AUTH_PROVIDER.get());
    }

}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.camunda.bpm.engine.impl.bpmn.behavior;

import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.core.model.BaseCallableElement;
import org.camunda.bpm.engine.impl.core.model.CallableElement;
import org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution;
import org.camunda.bpm.engine.impl.scripting.ExecutableScript;
import org.camunda.bpm.engine.impl.scripting.ScriptFactory;
import org.camunda.bpm.engine.impl.util.CallableElementUtil;
import org.camunda.bpm.engine.repository.DecisionDefinition;

public class DecisionRuleTaskActivityBehavior extends ScriptTaskActivityBehavior {

  protected BaseCallableElement callableElement;

  public DecisionRuleTaskActivityBehavior(String resultVariable) {
    super(null, resultVariable);
  }

  @Override
  public void execute(ActivityExecution execution) throws Exception {
    script = createScript(execution);
    super.execute(execution);
  }

  public BaseCallableElement getCallableElement() {
    return callableElement;
  }

  public void setCallableElement(BaseCallableElement callableElement) {
    this.callableElement = callableElement;
  }

  protected ExecutableScript createScript(ActivityExecution execution) {
    DecisionDefinition definition = CallableElementUtil.getDecisionDefinitionToCall(execution, getCallableElement());
    ScriptFactory scriptFactory = getScriptFactory();
    return scriptFactory.createScriptFromDecisionDefinition(definition);
  }

  protected ScriptFactory getScriptFactory() {
    return Context.getProcessEngineConfiguration().getScriptFactory();
  }

}


text:
@interface AsyncImageView : UIView <LoadedImageDelegate> {

	UIActivityIndicatorView *activityIndicator;
	NSString *requestedImageId;
}

- (void)loadWithImageId:(NSString *)imageId;

@property(nonatomic,copy) NSString *requestedImageId;

@end


text:
const loaderUtils = require('loader-utils');
const fs = require('fs');

module.exports = function configLoader(remoteConfig) {
  const options = loaderUtils.getOptions(this);
  return fs.readFileSync(
    `${__dirname}/config.${options.environment}.js`,
    'utf8'
  );
};


text:
<?php

namespace Doctrine\MongoDB;

use Doctrine\Common\EventManager;
use Doctrine\MongoDB\Event\DistinctEventArgs;
use Doctrine\MongoDB\Event\EventArgs;
use Doctrine\MongoDB\Event\GroupEventArgs;
use Doctrine\MongoDB\Event\MapReduceEventArgs;
use Doctrine\MongoDB\Event\NearEventArgs;
use Doctrine\MongoDB\Event\UpdateEventArgs;
use Doctrine\MongoDB\Util\ReadPreference;

/**
 * Wrapper for the PHP MongoCollection class.
 *
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
 * @link        www.doctrine-project.org
 * @since       1.0
 * @author      Jonathan H. Wage <jonwage@gmail.com>
 * @author      Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class Collection
{
    /**
     * The Doctrine Connection object.
     *
     * @var Doctrine\MongoDB\Connection
     */
    protected $connection;

    /**
     * The name of the collection.
     *
     * @var string $name
     */
    protected $name;

    /**
     * The Database instance this collection belongs to.
     *
     * @var Database
     */
    protected $database;

    /**
     * The event manager that is the central point of the event system.
     *
     * @var Doctrine\Common\EventManager
     */
    protected $eventManager;

    /**
     * Mongo command prefix
     *
     * @var string
     */
    protected $cmd;

    /**
     * Number of times to retry queries.
     *
     * @var mixed
     */
    protected $numRetries;

    /**
     * Create a new MongoCollection instance that wraps a PHP MongoCollection instance
     * for a given ClassMetadata instance.
     *
     * @param Connection $connection The Doctrine Connection instance.
     * @param string $name The name of the collection.
     * @param Database $database The Database instance.
     * @param EventManager $evm The EventManager instance.
     * @param string $cmd Mongo cmd character.
     * @param boolean|integer $numRetries Number of times to retry queries.
     */
    public function __construct(Connection $connection, $name, Database $database, EventManager $evm, $cmd, $numRetries = 0)
    {
        $this->connection = $connection;
        $this->name = $name;
        $this->database = $database;
        $this->eventManager = $evm;
        $this->cmd = $cmd;
        $this->numRetries = (integer) $numRetries;
    }

    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the wrapped MongoCollection instance.
     *
     * @return \MongoCollection
     */
    public function getMongoCollection()
    {
        return $this->database->getMongoDB()->selectCollection($this->name);
    }

    /**
     * Gets the database this collection belongs to.
     *
     * @return Database $database
     */
    public function getDatabase()
    {
        return $this->database;
    }

    public function getIndexInfo()
    {
        return $this->getMongoCollection()->getIndexInfo();
    }

    /**
     * Check if a given field name is indexed in mongodb.
     *
     * @param string $fieldName
     * @return bool
     */
    public function isFieldIndexed($fieldName)
    {
        $indexes = $this->getIndexInfo();
        foreach ($indexes as $index) {
            if (isset($index['key']) && isset($index['key'][$fieldName])) {
                return true;
            }
        }
        return false;
    }

    /**
     * Creates a new query builder instnce.
     *
     * @return Query\Builder $qb
     */
    public function createQueryBuilder()
    {
        return new Query\Builder($this->database, $this, $this->cmd);
    }

    /** @override */
    public function batchInsert(array &$a, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preBatchInsert)) {
            $this->eventManager->dispatchEvent(Events::preBatchInsert, new EventArgs($this, $a));
        }

        $result = $this->doBatchInsert($a, $options);

        if ($this->eventManager->hasListeners(Events::postBatchInsert)) {
            $this->eventManager->dispatchEvent(Events::postBatchInsert, new EventArgs($this, $result));
        }

        return $a;
    }

    protected function doBatchInsert(array &$a, array $options = array())
    {
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        return $this->getMongoCollection()->batchInsert($a, $options);
    }

    /** @override */
    public function update($query, array $newObj, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preUpdate)) {
            $this->eventManager->dispatchEvent(Events::preUpdate, new UpdateEventArgs($this, $query, $newObj));
        }

        $result = $this->doUpdate($query, $newObj, $options);

        if ($this->eventManager->hasListeners(Events::postUpdate)) {
            $this->eventManager->dispatchEvent(Events::postUpdate, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doUpdate($query, array $newObj, array $options)
    {
        if (is_scalar($query)) {
            $query = array('_id' => $query);
        }
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        return $this->getMongoCollection()->update($query, $newObj, $options);
    }

    public function upsert($query, array $newObj, array $options = array())
    {
        $options['upsert'] = true;
        return $this->update($query, $newObj, $options);
    }

    /** @override */
    public function find(array $query = array(), array $fields = array())
    {
        if ($this->eventManager->hasListeners(Events::preFind)) {
            $this->eventManager->dispatchEvent(Events::preFind, new EventArgs($this, $query));
        }

        $result = $this->doFind($query, $fields);

        if ($this->eventManager->hasListeners(Events::postFind)) {
            $this->eventManager->dispatchEvent(Events::postFind, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doFind(array $query, array $fields)
    {
        $collection = $this;
        $cursor = $this->retry(function() use ($collection, $query, $fields) {
            return $collection->getMongoCollection()->find($query, $fields);
        });
        return $this->wrapCursor($cursor, $query, $fields);
    }

    protected function wrapCursor(\MongoCursor $cursor, $query, $fields)
    {
        return new Cursor($this->connection, $this, $cursor, $query, $fields, $this->numRetries);
    }

    /** @override */
    public function findOne(array $query = array(), array $fields = array())
    {
        if ($this->eventManager->hasListeners(Events::preFindOne)) {
            $this->eventManager->dispatchEvent(Events::preFindOne, new EventArgs($this, $query));
        }

        $result = $this->doFindOne($query, $fields);

        if ($this->eventManager->hasListeners(Events::postFindOne)) {
            $this->eventManager->dispatchEvent(Events::postFindOne, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doFindOne(array $query, array $fields)
    {
        $collection = $this;
        return $this->retry(function() use ($collection, $query, $fields) {
            return $collection->getMongoCollection()->findOne($query, $fields);
        });
    }

    public function findAndRemove(array $query, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preFindAndRemove)) {
            $this->eventManager->dispatchEvent(Events::preFindAndRemove, new EventArgs($this, $query));
        }

        $document = $this->doFindAndRemove($query, $options);

        if ($this->eventManager->hasListeners(Events::postFindAndRemove)) {
            $this->eventManager->dispatchEvent(Events::postFindAndRemove, new EventArgs($this, $document));
        }

        return $document;
    }

    protected function doFindAndRemove(array $query, array $options = array())
    {
        $command = array();
        $command['findandmodify'] = $this->getMongoCollection()->getName();
        $command['query'] = $query;
        $command['remove'] = true;
        $command = array_merge($command, $options);

        $result = $this->database->command($command);

        return isset($result['value']) ? $result['value'] : null;
    }

    public function findAndUpdate(array $query, array $newObj, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preFindAndUpdate)) {
            $this->eventManager->dispatchEvent(Events::preFindAndUpdate, new UpdateEventArgs($this, $query, $query));
        }

        $document = $this->doFindAndUpdate($query, $newObj, $options);

        if ($this->eventManager->hasListeners(Events::postFindAndUpdate)) {
            $this->eventManager->dispatchEvent(Events::postFindAndUpdate, new EventArgs($this, $document));
        }

        return $document;
    }

    protected function doFindAndUpdate(array $query, array $newObj, array $options)
    {
        $command = array();
        $command['findandmodify'] = $this->getMongoCollection()->getName();
        $command['query'] = $query;
        $command['update'] = $newObj;
        $command = array_merge($command, $options);

        $result = $this->database->command($command);
        return isset($result['value']) ? $result['value'] : null;
    }

    public function near(array $near, array $query = array(), array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preNear)) {
            $this->eventManager->dispatchEvent(Events::preNear, new NearEventArgs($this, $query, $near));
        }

        $result = $this->doNear($near, $query, $options);

        if ($this->eventManager->hasListeners(Events::postNear)) {
            $this->eventManager->dispatchEvent(Events::postNear, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doNear(array $near, array $query, array $options)
    {
        $command = array();
        $command['geoNear'] = $this->getMongoCollection()->getName();
        $command['near'] = $near;
        $command['query'] = $query;
        $command = array_merge($command, $options);

        $database = $this->database;
        $result = $this->retry(function() use ($database, $command) {
            return $database->command($command);
        });
        return new ArrayIterator(isset($result['results']) ? $result['results'] : array());
    }

    public function distinct($field, array $query = array(), array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preDistinct)) {
            $this->eventManager->dispatchEvent(Events::preDistinct, new DistinctEventArgs($this, $field, $query));
        }

        $result = $this->doDistinct($field, $query, $options);

        if ($this->eventManager->hasListeners(Events::postDistinct)) {
            $this->eventManager->dispatchEvent(Events::postDistinct, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doDistinct($field, array $query, array $options)
    {
        $command = array();
        $command['distinct'] = $this->getMongoCollection()->getName();
        $command['key'] = $field;
        $command['query'] = $query;
        $command = array_merge($command, $options);

        $database = $this->database;
        $result = $this->retry(function() use ($database, $command) {
            return $database->command($command);
        });
        return new ArrayIterator(isset($result['values']) ? $result['values'] : array());
    }

    public function mapReduce($map, $reduce, array $out = array('inline' => true), array $query = array(), array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preMapReduce)) {
            $this->eventManager->dispatchEvent(Events::preMapReduce, new MapReduceEventArgs($this, $map, $reduce, $out, $query));
        }

        $result = $this->doMapReduce($map, $reduce, $out, $query, $options);

        if ($this->eventManager->hasListeners(Events::postMapReduce)) {
            $this->eventManager->dispatchEvent(Events::postMapReduce, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doMapReduce($map, $reduce, array $out, array $query, array $options)
    {
        if (is_string($map)) {
            $map = new \MongoCode($map);
        }
        if (is_string($reduce)) {
            $reduce = new \MongoCode($reduce);
        }
        $command = array();
        $command['mapreduce'] = $this->getMongoCollection()->getName();
        $command['map'] = $map;
        $command['reduce'] = $reduce;
        $command['query'] = (object) $query;
        $command['out'] = $out;
        $command = array_merge($command, $options);

        $result = $this->database->command($command);

        if (!$result['ok']) {
            throw new \RuntimeException($result['errmsg']);
        }

        if (isset($out['inline']) && $out['inline'] === true) {
            return new ArrayIterator($result['results']);
        }

        return $this->database->selectCollection($result['result'])->find();
    }

    public function count(array $query = array(), $limit = 0, $skip = 0)
    {
        $collection = $this;
        return $this->retry(function() use ($collection, $query, $limit, $skip) {
            return $collection->getMongoCollection()->count($query, $limit, $skip);
        });
    }

    public function createDBRef(array $a)
    {
        if ($this->eventManager->hasListeners(Events::preCreateDBRef)) {
            $this->eventManager->dispatchEvent(Events::preCreateDBRef, new EventArgs($this, $a));
        }

        $result = $this->doCreateDBRef($a);

        if ($this->eventManager->hasListeners(Events::postCreateDBRef)) {
            $this->eventManager->dispatchEvent(Events::postCreateDBRef, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doCreateDBRef(array $a)
    {
        return $this->getMongoCollection()->createDBRef($a);
    }

    public function deleteIndex($keys)
    {
        return $this->getMongoCollection()->deleteIndex($keys);
    }

    public function deleteIndexes()
    {
        return $this->getMongoCollection()->deleteIndexes();
    }

    public function drop()
    {
        if ($this->eventManager->hasListeners(Events::preDropCollection)) {
            $this->eventManager->dispatchEvent(Events::preDropCollection, new EventArgs($this));
        }

        $result = $this->doDrop();

        if ($this->eventManager->hasListeners(Events::postDropCollection)) {
            $this->eventManager->dispatchEvent(Events::postDropCollection, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doDrop()
    {
        return $this->getMongoCollection()->drop();
    }

    public function ensureIndex(array $keys, array $options = array())
    {
        return $this->getMongoCollection()->ensureIndex($keys, $options);
    }

    public function __get($name)
    {
        return $this->getMongoCollection()->__get($name);
    }

    public function getDBRef(array $reference)
    {
        if ($this->eventManager->hasListeners(Events::preGetDBRef)) {
            $this->eventManager->dispatchEvent(Events::preGetDBRef, new EventArgs($this, $reference));
        }

        $result = $this->doGetDBRef($reference);

        if ($this->eventManager->hasListeners(Events::postGetDBRef)) {
            $this->eventManager->dispatchEvent(Events::postGetDBRef, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doGetDBRef(array $reference)
    {
        $collection = $this;
        return $this->retry(function() use ($collection, $reference) {
            return $collection->getMongoCollection()->getDBRef($reference);
        });
    }

    public function group($keys, array $initial, $reduce, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preGroup)) {
            $this->eventManager->dispatchEvent(Events::preGroup, new GroupEventArgs($this, $keys, $initial, $reduce));
        }

        $result = $this->doGroup($keys, $initial, $reduce, $options);

        if ($this->eventManager->hasListeners(Events::postGroup)) {
            $this->eventManager->dispatchEvent(Events::postGroup, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doGroup($keys, array $initial, $reduce, array $options)
    {
        if (is_string($reduce)) {
            $reduce = new \MongoCode($reduce);
        }

        if (isset($options['finalize']) && is_string($options['finalize'])) {
            $options['finalize'] = new \MongoCode($options['finalize']);
        }

        $collection = $this;
        $result = $this->retry(function() use ($collection, $keys, $initial, $reduce, $options) {
            /* Version 1.2.11+ of the driver yields an E_DEPRECATED notice if an
             * empty array is passed to MongoCollection::group(), as it assumes
             * it is the "condition" option's value being passed instead of a
             * well-formed options array (the actual deprecated behavior).
             */
            return empty($options)
                ? $collection->getMongoCollection()->group($keys, $initial, $reduce)
                : $collection->getMongoCollection()->group($keys, $initial, $reduce, $options);
        });
        return new ArrayIterator($result);
    }

    public function insert(array &$a, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preInsert)) {
            $this->eventManager->dispatchEvent(Events::preInsert, new EventArgs($this, $a));
        }

        $result = $this->doInsert($a, $options);

        if ($this->eventManager->hasListeners(Events::postInsert)) {
            $this->eventManager->dispatchEvent(Events::postInsert, new EventArgs($this, $result));
        }
        return $result;
    }

    protected function doInsert(array &$a, array $options)
    {
        $document = $a;
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        $result = $this->getMongoCollection()->insert($document, $options);
        if (isset($document['_id'])) {
            $a['_id'] = $document['_id'];
        }
        return $result;
    }

    public function remove(array $query, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preRemove)) {
            $this->eventManager->dispatchEvent(Events::preRemove, new EventArgs($this, $query));
        }

        $result = $this->doRemove($query, $options);

        if ($this->eventManager->hasListeners(Events::postRemove)) {
            $this->eventManager->dispatchEvent(Events::postRemove, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doRemove(array $query, array $options)
    {
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        return $this->getMongoCollection()->remove($query, $options);
    }

    public function save(array &$a, array $options = array())
    {
        if ($this->eventManager->hasListeners(Events::preSave)) {
            $this->eventManager->dispatchEvent(Events::preSave, new EventArgs($this, $a));
        }

        $result = $this->doSave($a, $options);

        if ($this->eventManager->hasListeners(Events::postSave)) {
            $this->eventManager->dispatchEvent(Events::postSave, new EventArgs($this, $result));
        }

        return $result;
    }

    protected function doSave(array &$a, array $options)
    {
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        return $this->getMongoCollection()->save($a, $options);
    }

    /**
     * Set whether secondary read queries are allowed for this collection.
     *
     * This method wraps setSlaveOkay() for driver versions before 1.3.0. For
     * newer drivers, this method wraps setReadPreference() and specifies
     * SECONDARY_PREFERRED.
     */
    public function setSlaveOkay($ok = true)
    {
        if (version_compare(phpversion('mongo'), '1.3.0', '<')) {
            return $this->getMongoCollection()->setSlaveOkay($ok);
        }

        $prevSlaveOkay = $this->getSlaveOkay();

        if ($ok) {
            // Preserve existing tags for non-primary read preferences
            $readPref = $this->getMongoCollection()->getReadPreference();
            $tags = !empty($readPref['tagsets']) ? ReadPreference::convertTagSets($readPref['tagsets']) : array();
            $this->getMongoCollection()->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED, $tags);
        } else {
            $this->getMongoCollection()->setReadPreference(\MongoClient::RP_PRIMARY);
        }

        return $prevSlaveOkay;
    }

    /**
     * Get whether secondary read queries are allowed for this collection.
     *
     * This method wraps getSlaveOkay() for driver versions before 1.3.0. For
     * newer drivers, this method considers any read preference other than
     * PRIMARY as a true "slaveOkay" value.
     */
    public function getSlaveOkay()
    {
        if (version_compare(phpversion('mongo'), '1.3.0', '<')) {
            return $this->getMongoCollection()->getSlaveOkay();
        }

        $readPref = $this->getMongoCollection()->getReadPreference();

        if (is_numeric($readPref['type'])) {
            $readPref['type'] = ReadPreference::convertNumericType($readPref['type']);
        }

        return \MongoClient::RP_PRIMARY !== $readPref['type'];
    }

    public function validate($scanData = false)
    {
        return $this->getMongoCollection()->validate($scanData);
    }

    public function __toString()
    {
        return $this->getMongoCollection()->__toString();
    }

    protected function retry(\Closure $retry)
    {
        if ($this->numRetries) {
            $firstException = null;
            for ($i = 0; $i <= $this->numRetries; $i++) {
                try {
                    return $retry();
                } catch (\MongoException $e) {
                    if (!$firstException) {
                        $firstException = $e;
                    }
                    if ($i === $this->numRetries) {
                        throw $firstException;
                    }
                }
            }
        } else {
            return $retry();
        }
    }

    /**
     * Converts "safe" write option to "w" for driver versions 1.3.0+.
     *
     * @param array $options
     * @return array
     */
    protected function convertWriteConcern(array $options)
    {
        if (version_compare(phpversion('mongo'), '1.3.0', '<')) {
            return $options;
        }

        if (isset($options['safe']) && ! isset($options['w'])) {
            $options['w'] = is_bool($options['safe']) ? (integer) $options['safe'] : $options['safe'];
            unset($options['safe']);
        }

        return $options;
    }
}


text:
# usage : python scdl.py <soundcloud track/playlist url>

import soundcloud
import urllib
import re
import time
import os
import sys

from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error

CLIENT_ID = '49009eb8904b11a2a5d2c6bdc162dd32'
MEDIA_STREAM_URL = 'http://media.soundcloud.com/stream/'

# color codes for terminal output
class colors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    END = '\033[0m'

class scdl:
	client = soundcloud.Client(client_id=CLIENT_ID)

	def __init__(self, url, download_path, silent=True):
		self.url = url
		self.download_progress = 0
		self.download_path = os.path.expanduser(download_path)
		self.current_time = time.time()
		self.track_url_dicts = self.resolve(url)
		self.silent = silent

	# resolve a Soundcloud URL
	# return track details in list (i.e. if only a single song,
	#	a single element list will be returned)
	def resolve(self, url):
		returnMedia = []
		resolved_url = self.client.get('/resolve', url=url);
		if resolved_url.kind == 'track':
			# resolved_url is a single track object
			returnMedia.append(self.get_track_detail(resolved_url.id))
		elif resolved_url.kind == 'playlist':
			# resolve_url is a list of song objects
			for track in resolved_url.tracks:
				returnMedia.append(self.get_track_detail(track['id']))
		elif resolved_url.kind == 'user':
			track_list_url = 'https://api.soundcloud.com/users/' + str(resolved_url.id) + '/tracks'
			tracks = self.client.get(track_list_url)
			for track in tracks:
				returnMedia.append(self.get_track_detail(track.id))
		return returnMedia

 	# return a dict of important attributes for a specific track
	def get_track_detail(self, track_id):
		regex = re.compile('\/([a-zA-Z0-9]+)_')
		track = self.client.get('/tracks/' + str(track_id))
		track_detail = {'title':track.title,
						# keep a version of the title that can be used as a filename
						'artist':re.sub('[\/:*?"<>|%]', '-', track.user['username']),
						'safe_title':re.sub('[\/:*?"<>|%]', '-', track.title),
						# find the streaming URL for this track
					 	'stream_url':MEDIA_STREAM_URL + str(regex.search(track.waveform_url).groups()[0]),
					 	# find this track's artwork URL (or substitute with the user's avatar URL)
					 	'artwork_url':(track.artwork_url if track.artwork_url else track.user['avatar_url'])}
		return track_detail

	# iterate through a list of track detail dicts and download each one
	# return a list of filenames where the tracks were downloaded to
	def dl_tracks(self, tracks):
		track_filename_list = []
		for track in tracks:
			try:
				# create a folder to store this artist's tracks
				artist_folder = self.download_path + track['artist'] + '/'
				if not os.path.isdir(artist_folder):
					os.mkdir(artist_folder)
				track_filename = unicode(artist_folder) + u"{0}.mp3".format(track['safe_title'])
				artwork_filename = unicode(artist_folder) + u".{0}-artwork.jpg".format(track['safe_title'])
				if not self.silent:
					sys.stdout.write(unicode(colors.HEADER + "Downloading: " + colors.END + colors.OKBLUE) + u"{0}".format(track['title']) + unicode(colors.END + "\n"))
				urllib.urlretrieve(url=track['stream_url'], filename=track_filename, reporthook=(None if self.silent else self.dl_progress))
				# reset variables so next track's report hook doesn't malfunction
				self.download_progress = 0
				self.current_time = time.time()
				if not self.silent:
					print
				# get the track's artwork
				urllib.urlretrieve(url=track['artwork_url'], filename=artwork_filename)
				embed_artwork(track_filename, artwork_filename)
				os.remove(artwork_filename)
				track_filename_list.append(track_filename)
			except e:
				# in case of failure, just move on to next track
				print e
				continue
		return track_filename_list

	# a basic report hook that monitors a download's progress
	def dl_progress(self, block_no, block_size, file_size):
		self.download_progress += block_size
		if int(self.download_progress / 1024 * 8) > 1000:
			speed = "{0:7.2f} Mbps".format(round((self.download_progress / 1024 / 1024 * 8) / (time.time() - self.current_time), 2))
		else:
			speed = "{0:7.2f} Kbps".format(round((self.download_progress / 1024 * 8) / (time.time() - self.current_time), 2))
		rProgress = round(self.download_progress / 1024.00 / 1024.00, 2)
		rFile = round(file_size / 1024.00 / 1024.00, 2)
		percent = round(100 * float(self.download_progress) / float(file_size))
		percent = min(percent, 100)
		sys.stdout.write("\r" + colors.OKGREEN + "{3} ({0:.2f}/{1:.2f}MB): {2:6.2f}%".format(rProgress, rFile, percent, speed) + colors.END)
		sys.stdout.flush()

# takes a track's filename and it's artwork's filename and uses ID3 to embed
# 	the artwork within the track file
def embed_artwork(track_filename, artwork_filename):
	audio = MP3(track_filename, ID3=ID3)
	# add ID3 tag if it doesn't exist
	try:
	    audio.add_tags()
	except error:
	    pass
	audio.tags.add(
	    APIC(
	        encoding=3, # 3 is for utf-8
	        mime='image/jpg', # image/jpeg or image/png
	        type=3, # 3 is for the cover image
	        desc=u'Cover',
	        data=open(artwork_filename).read()
	    )
	)
	audio.save()

# easy download method to download a track specified by 'url' to a folder 'download_path'
# returns a list of full filenames and paths of downloaded tracks
def download(url, download_path, silent=True):
	skipper = scdl(url, download_path, silent)
	track_urls = skipper.track_url_dicts
	return skipper.dl_tracks(track_urls)

if __name__ == "__main__":
	dest = os.path.expanduser('~/Music/Soundcloud/')
	list_of_downloaded_filenames = []
	for i in range(1, len(sys.argv)):
		link = sys.argv[i]
		list_of_downloaded_filenames += download(link, dest, silent=False)
	print
	print colors.HEADER + "The following files were downloaded successfully:" + colors.END
	for i, filename in enumerate(list_of_downloaded_filenames):
		print unicode("\t" + colors.HEADER + str(i+1) + ". " + colors.END + colors.OKBLUE) + u" {0}".format(filename[len(dest):].split('/')[1]) + unicode(colors.END)
	print colors.OKGREEN + "Finished." + colors.END


text:
package org.cvit.cabig.dmr.cmef.server;

import org.restlet.data.Status ;
import org.restlet.ext.json.JsonRepresentation ;
import org.restlet.representation.Representation ;
import org.restlet.resource.Get ;

public class JobResource extends AbstractJobResource {

    @Get("json")
    public Representation getJson() {
	setStatus(Status.SUCCESS_OK) ;
	return new JsonRepresentation(jsonJob(job)) ;
    }

    @Get("htm|html")
    public Representation getHtml() {
	return buildHtmlJob() ;
    }
}


text:
package com.intellij.debugger.ui.tree.render;

import com.intellij.debugger.DebuggerContext;
import com.intellij.debugger.engine.DebugProcess;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContext;
import com.intellij.debugger.settings.NodeRendererSettings;
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
import com.intellij.debugger.ui.overhead.OverheadProducer;
import com.intellij.debugger.ui.tree.DebuggerTreeNode;
import com.intellij.debugger.ui.tree.NodeDescriptor;
import com.intellij.psi.PsiElement;
import com.intellij.ui.SimpleColoredComponent;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.Value;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public abstract class NodeRendererImpl implements NodeRenderer {
  public static final String DEFAULT_NAME = "unnamed";

  protected BasicRendererProperties myProperties;
  private final String myDefaultName;

  protected NodeRendererImpl() {
    this(DEFAULT_NAME, false);
  }

  protected NodeRendererImpl(@NotNull String presentableName) {
    this(presentableName, false);
  }

  protected NodeRendererImpl(@NotNull String presentableName, boolean enabledDefaultValue) {
    myDefaultName = presentableName;
    myProperties = new BasicRendererProperties(enabledDefaultValue);
    myProperties.setName(presentableName);
    myProperties.setEnabled(enabledDefaultValue);
  }

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

  @Override
  public void setName(String name) {
    myProperties.setName(name);
  }

  @Override
  public boolean isEnabled() {
    return myProperties.isEnabled();
  }

  @Override
  public void setEnabled(boolean enabled) {
    myProperties.setEnabled(enabled);
  }

  public boolean isShowType() {
    return myProperties.isShowType();
  }

  public void setShowType(boolean showType) {
    myProperties.setShowType(showType);
  }

  @Override
  public void buildChildren(Value value, ChildrenBuilder builder, EvaluationContext evaluationContext) {
  }

  @Override
  public PsiElement getChildValueExpression(DebuggerTreeNode node, DebuggerContext context) throws EvaluateException {
    return null;
  }

  @Override
  public boolean isExpandable(Value value, EvaluationContext evaluationContext, NodeDescriptor parentDescriptor) {
    return false;
  }

  @Override
  public NodeRendererImpl clone() {
    try {
      final NodeRendererImpl cloned = (NodeRendererImpl)super.clone();
      cloned.myProperties = myProperties.clone();
      return cloned;
    }
    catch (CloneNotSupportedException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void readExternal(Element element) {
    myProperties.readExternal(element, myDefaultName);
  }

  @Override
  public void writeExternal(Element element) {
    myProperties.writeExternal(element, myDefaultName);
  }

  public String toString() {
    return getName();
  }

  @Nullable
  public String getIdLabel(Value value, DebugProcess process) {
    return value instanceof ObjectReference && isShowType() ? ValueDescriptorImpl.getIdLabel((ObjectReference)value) : null;
  }

  public boolean hasOverhead() {
    return false;
  }

  public static class Overhead implements OverheadProducer {
    private final NodeRendererImpl myRenderer;

    public Overhead(@NotNull NodeRendererImpl renderer) {
      myRenderer = renderer;
    }

    @Override
    public boolean isEnabled() {
      return myRenderer.isEnabled();
    }

    @Override
    public void setEnabled(boolean enabled) {
      myRenderer.setEnabled(enabled);
      NodeRendererSettings.getInstance().fireRenderersChanged();
    }

    @Override
    public void customizeRenderer(SimpleColoredComponent renderer) {
      renderer.append(myRenderer.getName() + " renderer");
    }

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

    @Override
    public boolean equals(Object obj) {
      return obj instanceof CompoundTypeRenderer.Overhead && myRenderer.equals(((CompoundTypeRenderer.Overhead)obj).myRenderer);
    }
  }
}


text:
package com.example.nfcapp1;

import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class InstalledApplicationListActivity extends ListActivity implements OnItemClickListener {

	//Ó¦ÓóÌÐòËùÓеİüÃûÐÅÏ¢·ÅÔÚÕâ¸ö¼¯ºÏÀïÃæ
	private List<String> mPackages = new ArrayList<String>();

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PackageManager packageManager = getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES);
        for(PackageInfo p : packageInfos){
        	mPackages.add( p.applicationInfo.loadLabel(packageManager) + "\n" + p.packageName );
        }

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1 , android.R.id.text1 , mPackages);
        setListAdapter(arrayAdapter);
        getListView().setOnItemClickListener(this);

    }

	@Override
	public void onItemClick(AdapterView<?> parent , View view , int position , long id) {
		Intent intent = new Intent();
		intent.putExtra("package_name" , mPackages.get(position));
		setResult(1 , intent);
		finish();

	}

}


text:
namespace AccessExport.DataEntities
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("westbluegolf.team")]
    public partial class team
    {
        public team()
        {
            leaderboarddatas = new HashSet<leaderboarddata>();
            playeryeardatas = new HashSet<playeryeardata>();
            results = new HashSet<result>();
            teammatchups = new HashSet<teammatchup>();
        }

        public int id { get; set; }

        [Required]
        [StringLength(120)]
        public string teamName { get; set; }

        public bool validTeam { get; set; }

        public DateTime? modifiedDate { get; set; }

        public virtual ICollection<leaderboarddata> leaderboarddatas { get; set; }

        public virtual ICollection<playeryeardata> playeryeardatas { get; set; }

        public virtual ICollection<result> results { get; set; }

        public virtual ICollection<teammatchup> teammatchups { get; set; }
    }
}


text:
"""
Copyright 2014-2016 University of Illinois

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

file: contact/admin.py

Author: Jon Gunderson

"""
# contact/admin.py
from __future__ import absolute_import
from django.contrib import admin

from contact.models import Contact
from contact.models import Announcement

class ContactAdmin(admin.ModelAdmin):
  list_display = ('user', 'topic', 'date','status' )
  list_filter = ('user', 'date', 'topic', 'status')

admin.site.register(Contact, ContactAdmin)

class AnnouncementAdmin(admin.ModelAdmin):
  list_display = ('topic', 'date', 'scope', 'end_date', 'status', 'email', 'web' )
  list_filter = ('topic', 'scope')

admin.site.register( Announcement,  AnnouncementAdmin)


text:
package graph;

import game.MonsterMapGameException;
import game.MonsterMapGameMap;
import game.MonsterMapGameNodeContent;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import serialization.DirectedNetworkSerializer;
import serialization.SimpleJavaSerialization;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class GameGraphTest {

    private MonsterMapGameMap graph = null;

    @Before
    public void initialize_game_graph()
    throws GraphException, MonsterMapGameException {
        this.graph = new MonsterMapGameMap();
        MonsterMapGameMap.NodeReference origin = this.graph.entrance(); //0
        origin = origin
                .left(MonsterMapGameNodeContent.Monster) //1
                .left(MonsterMapGameNodeContent.Monster) //2
                .left(MonsterMapGameNodeContent.Treasure) //3
                .getPrevious(2);
        origin = origin
                .down(MonsterMapGameNodeContent.Nothing) //4
                .down(MonsterMapGameNodeContent.Treasure) //5
                .getPrevious(3);
        origin = origin
                .right(MonsterMapGameNodeContent.Nothing) //6
                .right(MonsterMapGameNodeContent.Monster) //7
                .right(MonsterMapGameNodeContent.Treasure) //8
                .getPrevious();
        origin = origin
                .up(MonsterMapGameNodeContent.Treasure) //9
                .getPrevious(2);
        origin = origin
                .down(MonsterMapGameNodeContent.Monster) //10
                .down(MonsterMapGameNodeContent.Nothing) //11
                .down(MonsterMapGameNodeContent.Monster) //12
                .getPrevious();
        origin = origin
                .right(MonsterMapGameNodeContent.Treasure) //13
                .right(MonsterMapGameNodeContent.Exit); //14
    }

    @Test
    public void test_create_example_graph() {
        checkSampleGraphStructure(this.graph);
    }

    private static void checkSampleGraphStructure(MonsterMapGameMap graph) {
        Assert.assertEquals("Graph order incorrect", 15, graph.getNetwork().getOrder());
        Assert.assertEquals("Graph size incorrect", 14, graph.getNetwork().getSize());

        Assert.assertEquals("Entrance node in degree incorrect", 0, graph.getNetwork().getIncidentNodes(0).size());
        Assert.assertEquals("Entrance node out degree incorrect", 2, graph.getNetwork().getReachableNodes(0).size());
        Assert.assertArrayEquals("Entrance reachable nodes invalid", new Integer[]{1, 6}, graph.getNetwork().getReachableNodes(0).toArray());

        Assert.assertEquals("Exit node in degree incorrect", 1, graph.getNetwork().getIncidentNodes(14).size());
        Assert.assertEquals("Exit node out degree incorrect", 0, graph.getNetwork().getReachableNodes(14).size());

        Assert.assertEquals("Left walk intersection #1 in degree incorrect", 1, graph.getNetwork().getIncidentNodes(1).size());
        Assert.assertEquals("Left walk intersection #1 out degree incorrect", 2, graph.getNetwork().getReachableNodes(1).size());

        Assert.assertEquals("Right walk intersection #1 in degree incorrect", 1, graph.getNetwork().getIncidentNodes(6).size());
        Assert.assertEquals("Right walk intersection #1 out degree incorrect", 2, graph.getNetwork().getReachableNodes(6).size());

    }

    @Test
    public void test_graph_simple_serialization()
    throws IOException, ClassNotFoundException, MonsterMapGameException {
        File testFile = File.createTempFile("treasureMap", ".map", null);
        FileOutputStream fos = new FileOutputStream(testFile);
        DirectedNetworkSerializer serializer = new SimpleJavaSerialization();
        serializer.writeToStream(fos, this.graph.getNetwork());
        fos.close();

        FileInputStream fis = new FileInputStream(testFile);
        DirectedNetwork<MonsterMapGameNodeContent> network = serializer.readFromStream(fis, MonsterMapGameNodeContent.class);
        fis.close();
        checkSampleGraphStructure(new MonsterMapGameMap(network));
    }

    @Test
    public void test_find_exit_path()
    throws NoSuchPathException {
        DirectedNetwork<MonsterMapGameNodeContent> network = this.graph.getNetwork();
        int exitNodeId = network.findNodesWithValue(MonsterMapGameNodeContent.Exit).get(0);
        PathFinder pathFinder = new RecursivePathFinder();
        List<Integer> path = pathFinder.findPath(network, this.graph.getEntranceNodeId(), exitNodeId);
        Assert.assertEquals("Path length from entrance to exit incorrect", 6, path.size());
        Assert.assertArrayEquals("Path elements are invalid", new Integer[] {0, 6, 10, 11, 13, 14}, path.toArray(new Integer[0]));
    }
}


text:
clean:
	find . -name *.pyc -delete
	find var/conf/ -name *.conf -delete
	find var/log/ -name *.bak-* -delete
	find var/log/ -name *.log -delete

clean-bench:
	find var/log/ -name *.xml -delete
	rm -rf var/report/**

clean-all: clean clean-bench

install:
	python setup.py develop

runserver:
	djfunkdemo runserver

bench:
	djfunkdemo runbench index

test:
	djfunkdemo test --liveserver=localhost:8000 djfunkdemo


text:
package org.apache.juddi.v3.tck;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.assertNotNull;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.juddi.jaxb.EntityCreator;
import org.junit.Assert;
import org.uddi.api_v3.BindingDetail;
import org.uddi.api_v3.BindingTemplate;
import org.uddi.api_v3.BindingTemplates;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessEntity;
import org.uddi.api_v3.BusinessInfo;
import org.uddi.api_v3.BusinessInfos;
import org.uddi.api_v3.BusinessList;
import org.uddi.api_v3.BusinessService;
import org.uddi.api_v3.FindBinding;
import org.uddi.api_v3.FindBusiness;
import org.uddi.api_v3.FindRelatedBusinesses;
import org.uddi.api_v3.FindService;
import org.uddi.api_v3.FindTModel;
import org.uddi.api_v3.GetBusinessDetail;
import org.uddi.api_v3.GetServiceDetail;
import org.uddi.api_v3.RelatedBusinessInfo;
import org.uddi.api_v3.RelatedBusinessInfos;
import org.uddi.api_v3.RelatedBusinessesList;
import org.uddi.api_v3.ServiceDetail;
import org.uddi.api_v3.ServiceInfo;
import org.uddi.api_v3.ServiceInfos;
import org.uddi.api_v3.ServiceList;
import org.uddi.api_v3.TModel;
import org.uddi.api_v3.TModelInfo;
import org.uddi.api_v3.TModelInfos;
import org.uddi.api_v3.TModelList;
import org.uddi.api_v3.DispositionReport;
import org.uddi.v3_service.DispositionReportFaultMessage;
import org.uddi.v3_service.UDDIInquiryPortType;

/**
 * @author Kurt T Stam
 * @author Jeff Faath
 */
public class TckFindEntity
{
	final static String FIND_BUSINESS_XML             = "uddi_data/find/findBusiness1.xml";
	final static String FIND_ALL_BUSINESSES_XML       = "uddi_data/find/findAllBusinesses.xml";
	final static String FIND_RELATED_BUSINESS_SORT_BY_NAME_XML = "uddi_data/find/findRelatedBusinesses_sortByName.xml";
	final static String FIND_RELATED_BUSINESS_FROM_KEY= "uddi_data/find/findRelatedBusinesses_fromKey.xml";
	final static String FIND_RELATED_BUSINESS_TO_KEY  = "uddi_data/find/findRelatedBusinesses_toKey.xml";
	final static String FIND_SERVICE_XML              = "uddi_data/find/findService1.xml";
	final static String FIND_BINDING_XML              = "uddi_data/find/findBinding1.xml";
	final static String FIND_TMODEL_XML               = "uddi_data/find/findTModel1.xml";
	final static String COMBINE_CAT_FIND_SERVICES     = "uddi_data/joepublisher/combineCatBagsFindServices.xml";

	private Log logger = LogFactory.getLog(this.getClass());
	UDDIInquiryPortType inquiry =null;

	public TckFindEntity(UDDIInquiryPortType inquiry) {
		super();
		this.inquiry = inquiry;
	}

	public void findBusiness() {
		try {
			FindBusiness body = (FindBusiness)EntityCreator.buildFromDoc(FIND_BUSINESS_XML, "org.uddi.api_v3");
			BusinessList result = inquiry.findBusiness(body);
			if (result == null)
				Assert.fail("Null result from find business operation");
			BusinessInfos bInfos = result.getBusinessInfos();
			if (bInfos == null)
				Assert.fail("No result from find business operation");
			List<BusinessInfo> biList = bInfos.getBusinessInfo();
			if (biList == null || biList.size() == 0)
				Assert.fail("No result from find business operation");
			BusinessInfo biOut = biList.get(0);

			BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(TckBusiness.JOE_BUSINESS_XML, "org.uddi.api_v3");

			assertEquals(beIn.getBusinessKey(), biOut.getBusinessKey());

			TckValidator.checkNames(beIn.getName(), biOut.getName());
			TckValidator.checkDescriptions(beIn.getDescription(), biOut.getDescription());
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}

	public void getNonExitingBusiness() {
		String nonExistingKey = "nonexistingKey";
		try {
			GetBusinessDetail body = new GetBusinessDetail();
			body.getBusinessKey().add(nonExistingKey);
			BusinessDetail  result = inquiry.getBusinessDetail(body);
			Assert.fail("No business should be found");
			System.out.println(result.getBusinessEntity().size());
		} catch (Exception e) {
			try {
				DispositionReport report = DispositionReportFaultMessage.getDispositionReport(e);
				assertNotNull(report);
				assertTrue(report.countainsErrorCode(DispositionReport.E_INVALID_KEY_PASSED));
			} catch (Exception e1) {
				Assert.fail("We only expect DispositionReportFaultMessage, not " + e1.getClass());
				logger.error(e.getMessage(), e1);
			}
		}
	}

	public void findAllBusiness() {
		try {
			FindBusiness body = (FindBusiness)EntityCreator.buildFromDoc(FIND_ALL_BUSINESSES_XML, "org.uddi.api_v3");
			BusinessList result = inquiry.findBusiness(body);
			if (result == null)
				Assert.fail("Null result from find business operation");
			BusinessInfos bInfos = result.getBusinessInfos();
			if (bInfos == null)
				Assert.fail("No result from find business operation");
			List<BusinessInfo> biList = bInfos.getBusinessInfo();
			if (biList == null || biList.size() == 0)
				Assert.fail("No result from find business operation");
			//expecting more than 2 businesses
			Assert.assertTrue(biList.size()>1);

		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}

	public void findRelatedBusiness_sortByName(boolean isOneSided) {
		try {
			FindRelatedBusinesses body = (FindRelatedBusinesses)EntityCreator.buildFromDoc(FIND_RELATED_BUSINESS_SORT_BY_NAME_XML, "org.uddi.api_v3");
			RelatedBusinessesList result = inquiry.findRelatedBusinesses(body);
			if (result == null)
				Assert.fail("Null result from find related business operation");
			RelatedBusinessInfos bInfos = result.getRelatedBusinessInfos();

			//both parties need to register the assertion for it to be live.
			if (isOneSided) {
				Assert.assertNull(bInfos);
			} else {
				if (bInfos == null)
					Assert.fail("No result from find related business operation");
				List<RelatedBusinessInfo> biList = bInfos.getRelatedBusinessInfo();
				if (biList == null || biList.size() == 0)
					Assert.fail("No result from find related business operation");
				Set<String> keys = new HashSet<String>();
				for (RelatedBusinessInfo relatedBusinessInfo : biList) {
					keys.add(relatedBusinessInfo.getBusinessKey());
				}
				Assert.assertTrue(keys.contains("uddi:www.samco.com:samco"));
				Assert.assertTrue(keys.contains("uddi:uddi.marypublisher.com:marybusinessone"));
			}
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}

	public void findRelatedBusinessToKey(boolean isOneSided) {
		try {
			FindRelatedBusinesses body = (FindRelatedBusinesses)EntityCreator.buildFromDoc(FIND_RELATED_BUSINESS_TO_KEY, "org.uddi.api_v3");
			RelatedBusinessesList result = inquiry.findRelatedBusinesses(body);
			if (result == null)
				Assert.fail("Null result from find related business operation");
			RelatedBusinessInfos bInfos = result.getRelatedBusinessInfos();

			//both parties need to register the assertion for it to be live.
			if (isOneSided) {
				Assert.assertNull(bInfos);
			} else {
				if (bInfos == null)
					Assert.fail("No result from find related business operation");
				List<RelatedBusinessInfo> biList = bInfos.getRelatedBusinessInfo();
				if (biList == null || biList.size() == 0)
					Assert.fail("No result from find related business operation");
				Set<String> keys = new HashSet<String>();
				for (RelatedBusinessInfo relatedBusinessInfo : biList) {
					keys.add(relatedBusinessInfo.getBusinessKey());
				}
				Assert.assertTrue(keys.contains("uddi:uddi.joepublisher.com:businessone"));
			}
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}

	public void findRelatedBusinessFromKey(boolean isOneSided) {
		try {
			FindRelatedBusinesses body = (FindRelatedBusinesses)EntityCreator.buildFromDoc(FIND_RELATED_BUSINESS_FROM_KEY, "org.uddi.api_v3");
			RelatedBusinessesList result = inquiry.findRelatedBusinesses(body);
			if (result == null)
				Assert.fail("Null result from find related business operation");
			RelatedBusinessInfos bInfos = result.getRelatedBusinessInfos();

			//both parties need to register the assertion for it to be live.
			if (isOneSided) {
				Assert.assertNull(bInfos);
			} else {
				if (bInfos == null)
					Assert.fail("No result from find related business operation");
				List<RelatedBusinessInfo> biList = bInfos.getRelatedBusinessInfo();
				if (biList == null || biList.size() == 0)
					Assert.fail("No result from find related business operation");
				Set<String> keys = new HashSet<String>();
				for (RelatedBusinessInfo relatedBusinessInfo : biList) {
					keys.add(relatedBusinessInfo.getBusinessKey());
				}
				Assert.assertTrue(keys.contains("uddi:www.samco.com:samco"));
			}
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}

	public String findService() {
		String serviceKey = null;
		try {
			FindService body = (FindService)EntityCreator.buildFromDoc(FIND_SERVICE_XML, "org.uddi.api_v3");
			ServiceList result = inquiry.findService(body);
			if (result == null)
				Assert.fail("Null result from find service operation");
			ServiceInfos sInfos = result.getServiceInfos();
			if (sInfos == null)
				Assert.fail("No result from find service operation");
			List<ServiceInfo> siList = sInfos.getServiceInfo();
			if (siList == null || siList.size() == 0)
				Assert.fail("No result from find service operation");
			ServiceInfo siOut = siList.get(0);

			BusinessService bsIn = (BusinessService)EntityCreator.buildFromDoc(TckBusinessService.JOE_SERVICE_XML, "org.uddi.api_v3");

			assertEquals(bsIn.getServiceKey(), siOut.getServiceKey());

			TckValidator.checkNames(bsIn.getName(), siOut.getName());
			serviceKey = siOut.getServiceKey();
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
		return serviceKey;
	}

	public String findService_CombinedCatBag() {
		String serviceKey = null;
		try {
			FindService body = (FindService)EntityCreator.buildFromDoc(COMBINE_CAT_FIND_SERVICES, "org.uddi.api_v3");
			ServiceList result = inquiry.findService(body);
			if (result == null)
				Assert.fail("Null result from find service operation");
			ServiceInfos sInfos = result.getServiceInfos();
			if (sInfos == null)
				Assert.fail("No result from find service operation");
			List<ServiceInfo> siList = sInfos.getServiceInfo();
			if (siList == null || siList.size() == 0)
				Assert.fail("No result from find service operation");
			ServiceInfo siOut = siList.get(0);

			serviceKey = siOut.getServiceKey();
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
		return serviceKey;
	}

	public void findServiceDetail(String serviceKey) {
		try {
			GetServiceDetail getServiceDetail = new GetServiceDetail();
			getServiceDetail.getServiceKey().add(serviceKey);

			ServiceDetail result = inquiry.getServiceDetail(getServiceDetail);

			if (result == null)
				Assert.fail("Null result from find service operation");

			BindingTemplates templates = result.getBusinessService().get(0).getBindingTemplates();
			if (templates!=null && templates.getBindingTemplate()!=null) {
				System.out.println(templates.getBindingTemplate().size());
				System.out.println("key=" + templates.getBindingTemplate().get(0).getBindingKey());
			}
//			ServiceInfos sInfos = result.getServiceInfos();
//			if (sInfos == null)
//				Assert.fail("No result from find service operation");
//			List<ServiceInfo> siList = sInfos.getServiceInfo();
//			if (siList == null || siList.size() == 0)
//				Assert.fail("No result from find service operation");
//			ServiceInfo siOut = siList.get(0);
//
//			BusinessService bsIn = (BusinessService)EntityCreator.buildFromDoc(TckBusinessService.JOE_SERVICE_XML, "org.uddi.api_v3");
//
//			assertEquals(bsIn.getServiceKey(), siOut.getServiceKey());
//
//			TckValidator.checkNames(bsIn.getName(), siOut.getName());
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}
	public void findBinding() {
		try {
			FindBinding body = (FindBinding)EntityCreator.buildFromDoc(FIND_BINDING_XML, "org.uddi.api_v3");
			BindingDetail result = inquiry.findBinding(body);
			if (result == null)
				Assert.fail("Null result from find binding operation");
			List<BindingTemplate> btList = result.getBindingTemplate();
			if (btList == null || btList.size() == 0)
				Assert.fail("No result from find binding operation");
			BindingTemplate btOut = btList.get(0);

			BindingTemplate btIn = (BindingTemplate)EntityCreator.buildFromDoc(TckBindingTemplate.JOE_BINDING_XML, "org.uddi.api_v3");

			assertEquals(btIn.getServiceKey(), btOut.getServiceKey());
			assertEquals(btIn.getBindingKey(), btOut.getBindingKey());

			TckValidator.checkDescriptions(btIn.getDescription(), btOut.getDescription());
			TckValidator.checkCategories(btIn.getCategoryBag(), btOut.getCategoryBag());
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown:  " + e.getMessage());
		}
	}

	public void findTModel() {
		try {
			FindTModel body = (FindTModel)EntityCreator.buildFromDoc(FIND_TMODEL_XML, "org.uddi.api_v3");
			TModelList result = inquiry.findTModel(body);
			if (result == null)
				Assert.fail("Null result from find tModel operation");
			TModelInfos tInfos = result.getTModelInfos();
			if (tInfos == null)
				Assert.fail("No result from find tModel operation");
			List<TModelInfo> tiList = tInfos.getTModelInfo();
			if (tiList == null || tiList.size() == 0)
				Assert.fail("No result from find tModel operation");
			TModelInfo tiOut = tiList.get(0);

			TModel tmIn = (TModel)EntityCreator.buildFromDoc(TckTModel.JOE_PUBLISHER_TMODEL_XML, "org.uddi.api_v3");

			assertEquals(tmIn.getTModelKey(), tiOut.getTModelKey());
			assertEquals(tmIn.getName().getLang(), tiOut.getName().getLang());
			assertEquals(tmIn.getName().getValue(), tiOut.getName().getValue());

			TckValidator.checkDescriptions(tmIn.getDescription(), tiOut.getDescription());
		}
		catch(Exception e) {
			logger.error(e.getMessage(), e);
			Assert.fail("No exception should be thrown.");
		}
	}
}


text:
module S3 where

import S3.Internal


text:
(function () {
    'use strict';

    function data($http, $q, authorization, notifier, baseServiceUrl) {
        function getErrorMsg(responce) {
            var error = responce.data.modelState;
            if (error && error[Object.keys(error)[0]][0]) {
                error = error[Object.keys(error)[0]][0];
            } else {
                error = responce.data.message;
            }

            return error;
        }

        function get(url, queryParams) {
            var deferred = $q.defer(),
                authHeader = authorization.getAuthorizationHeader();

            $http.get(baseServiceUrl + '/' + url, {params: queryParams, headers: authHeader})
                .then(function (responce) {
                    deferred.resolve(responce.data);
                }, function (err) {
                    err = getErrorMsg(err);
                    notifier.error(err);
                    deferred.reject(err);
                });

            return deferred.promise;
        }

        function post(url, postData) {
            var deferred = $q.defer(),
                authHeader = authorization.getAuthorizationHeader();

            $http.post(baseServiceUrl + '/' + url, postData, {headers: authHeader})
                .then(function (responce) {
                    deferred.resolve(responce.data);
                }, function (err) {
                    err = getErrorMsg(err);
                    notifier.error(err);
                    deferred.reject(err);
                });

            return deferred.promise;
        }

        function put(url, putData) {
            var deferred = $q.defer(),
                authHeader = authorization.getAuthorizationHeader();

            $http.put(baseServiceUrl + '/' + url, putData, {headers: authHeader})
                .then(function (responce) {
                    deferred.resolve(responce.data);
                }, function (err) {
                    err = getErrorMsg(err);
                    notifier.error(err);
                    deferred.reject(err);
                });

            return deferred.promise;
        }

        return {
            get: get,
            post: post,
            put: put
        };
    }

    angular.module('myApp.services')
        .factory('data', ['$http', '$q', 'authorization', 'notifier', 'baseServiceUrl', data]);
}());


text:
package org.rundeck.api.parser;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Node;
import org.rundeck.api.domain.WorkflowState;
import org.rundeck.api.domain.WorkflowStepContextState;
import org.rundeck.api.domain.WorkflowStepState;

/**
 * Returns a WorkflowStepContextState by looking up the given Rundeck node's state in the workflow, using the step
 * context path of the "stepctx" element of the selected DOM node.
 */
public class IndexedWorkflowStepStateParser implements XmlNodeParser<WorkflowStepContextState> {
    private final WorkflowState workflowState;
    private String rundeckNodeName;

    @Override
    public WorkflowStepContextState parseXmlNode(final Node node) {
        //look for workflow step state based on node name and stepctx found on the node
        final String stepctx = StringUtils.trimToNull(node.valueOf("stepctx"));
        final WorkflowStepState foundStep = lookupContext(stepctx, workflowState);
        //look up node state for this node
        if (null != foundStep
                && null != foundStep.getNodeStates()
                && null != foundStep.getNodeStates().get(rundeckNodeName)) {
            return foundStep.getNodeStates().get(rundeckNodeName);
        }

        return null;
    }

    /**
     * look up the workflow step state for the step context, from the root workflow
     *
     * @param stepctx
     * @param initial
     *
     * @return
     */
    public static WorkflowStepState lookupContext(final String stepctx, final WorkflowState initial) {
        final String[] parts = stepctx.split("/");
        //descend workflow steps to find correct step
        WorkflowState current = initial;
        WorkflowStepState currentStep = null;
        for (int i = 0; i < parts.length; i++) {
            final String part = parts[i];
            final WorkflowStepState workflowStepState = current.getSteps().get(Integer.parseInt(part) - 1);
            currentStep = workflowStepState;
            if (i < parts.length - 1) {
                current = currentStep.getSubWorkflow();
            }
        }
        return currentStep;
    }

    public IndexedWorkflowStepStateParser(final WorkflowState workflowState, final String rundeckNodeName) {
        this.workflowState = workflowState;
        this.rundeckNodeName = rundeckNodeName;
    }
}


text:
package sun.security.rsa;

import java.util.*;

import java.security.*;
import java.security.spec.*;

import javax.crypto.BadPaddingException;
import javax.crypto.spec.PSource;
import javax.crypto.spec.OAEPParameterSpec;

import sun.security.jca.JCAUtil;

/**
 * RSA padding and unpadding.
 *
 * The various PKCS#1 versions can be found in the IETF RFCs
 * tracking the corresponding PKCS#1 standards.
 *
 *     RFC 2313: PKCS#1 v1.5
 *     RFC 2437: PKCS#1 v2.0
 *     RFC 3447: PKCS#1 v2.1
 *     RFC 8017: PKCS#1 v2.2
 *
 * The format of PKCS#1 v1.5 padding is:
 *
 *   0x00 | BT | PS...PS | 0x00 | data...data
 *
 * where BT is the blocktype (1 or 2). The length of the entire string
 * must be the same as the size of the modulus (i.e. 128 byte for a 1024 bit
 * key). Per spec, the padding string must be at least 8 bytes long. That
 * leaves up to (length of key in bytes) - 11 bytes for the data.
 *
 * OAEP padding was introduced in PKCS#1 v2.0 and is a bit more complicated
 * and has a number of options. We support:
 *
 *   . arbitrary hash functions ('Hash' in the specification), MessageDigest
 *     implementation must be available
 *   . MGF1 as the mask generation function
 *   . the empty string as the default value for label L and whatever
 *     specified in javax.crypto.spec.OAEPParameterSpec
 *
 * The algorithms (representations) are forwards-compatible: that is,
 * the algorithm described in previous releases are in later releases.
 * However, additional comments/checks/clarifications were added to the
 * later versions based on real-world experience (e.g. stricter v1.5
 * format checking.)
 *
 * Note: RSA keys should be at least 512 bits long
 *
 * @since   1.5
 * @author  Andreas Sterbenz
 */
public final class RSAPadding {

    // NOTE: the constants below are embedded in the JCE RSACipher class
    // file. Do not change without coordinating the update

    // PKCS#1 v1.5 padding, blocktype 1 (signing)
    public static final int PAD_BLOCKTYPE_1    = 1;
    // PKCS#1 v1.5 padding, blocktype 2 (encryption)
    public static final int PAD_BLOCKTYPE_2    = 2;
    // nopadding. Does not do anything, but allows simpler RSACipher code
    public static final int PAD_NONE           = 3;
    // PKCS#1 v2.1 OAEP padding
    public static final int PAD_OAEP_MGF1 = 4;

    // type, one of PAD_*
    private final int type;

    // size of the padded block (i.e. size of the modulus)
    private final int paddedSize;

    // PRNG used to generate padding bytes (PAD_BLOCKTYPE_2, PAD_OAEP_MGF1)
    private SecureRandom random;

    // maximum size of the data
    private final int maxDataSize;

    // OAEP: main message digest
    private MessageDigest md;

    // OAEP: MGF1
    private MGF1 mgf;

    // OAEP: value of digest of data (user-supplied or zero-length) using md
    private byte[] lHash;

    /**
     * Get a RSAPadding instance of the specified type.
     * Keys used with this padding must be paddedSize bytes long.
     */
    public static RSAPadding getInstance(int type, int paddedSize)
            throws InvalidKeyException, InvalidAlgorithmParameterException {
        return new RSAPadding(type, paddedSize, null, null);
    }

    /**
     * Get a RSAPadding instance of the specified type.
     * Keys used with this padding must be paddedSize bytes long.
     */
    public static RSAPadding getInstance(int type, int paddedSize,
            SecureRandom random) throws InvalidKeyException,
            InvalidAlgorithmParameterException {
        return new RSAPadding(type, paddedSize, random, null);
    }

    /**
     * Get a RSAPadding instance of the specified type, which must be
     * OAEP. Keys used with this padding must be paddedSize bytes long.
     */
    public static RSAPadding getInstance(int type, int paddedSize,
            SecureRandom random, OAEPParameterSpec spec)
        throws InvalidKeyException, InvalidAlgorithmParameterException {
        return new RSAPadding(type, paddedSize, random, spec);
    }

    // internal constructor
    private RSAPadding(int type, int paddedSize, SecureRandom random,
            OAEPParameterSpec spec) throws InvalidKeyException,
            InvalidAlgorithmParameterException {
        this.type = type;
        this.paddedSize = paddedSize;
        this.random = random;
        if (paddedSize < 64) {
            // sanity check, already verified in RSASignature/RSACipher
            throw new InvalidKeyException("Padded size must be at least 64");
        }
        switch (type) {
        case PAD_BLOCKTYPE_1:
        case PAD_BLOCKTYPE_2:
            maxDataSize = paddedSize - 11;
            break;
        case PAD_NONE:
            maxDataSize = paddedSize;
            break;
        case PAD_OAEP_MGF1:
            String mdName = "SHA-1";
            String mgfMdName = mdName;
            byte[] digestInput = null;
            try {
                if (spec != null) {
                    mdName = spec.getDigestAlgorithm();
                    String mgfName = spec.getMGFAlgorithm();
                    if (!mgfName.equalsIgnoreCase("MGF1")) {
                        throw new InvalidAlgorithmParameterException
                            ("Unsupported MGF algo: " + mgfName);
                    }
                    mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters())
                            .getDigestAlgorithm();
                    PSource pSrc = spec.getPSource();
                    String pSrcAlgo = pSrc.getAlgorithm();
                    if (!pSrcAlgo.equalsIgnoreCase("PSpecified")) {
                        throw new InvalidAlgorithmParameterException
                            ("Unsupported pSource algo: " + pSrcAlgo);
                    }
                    digestInput = ((PSource.PSpecified) pSrc).getValue();
                }
                md = MessageDigest.getInstance(mdName);
                mgf = new MGF1(mgfMdName);
            } catch (NoSuchAlgorithmException e) {
                throw new InvalidKeyException("Digest not available", e);
            }
            lHash = getInitialHash(md, digestInput);
            int digestLen = lHash.length;
            maxDataSize = paddedSize - 2 - 2 * digestLen;
            if (maxDataSize <= 0) {
                throw new InvalidKeyException
                        ("Key is too short for encryption using OAEPPadding" +
                         " with " + mdName + " and " + mgf.getName());
            }
            break;
        default:
            throw new InvalidKeyException("Invalid padding: " + type);
        }
    }

    // cache of hashes of zero length data
    private static final Map<String,byte[]> emptyHashes =
        Collections.synchronizedMap(new HashMap<String,byte[]>());

    /**
     * Return the value of the digest using the specified message digest
     * md and the digest input digestInput.
     * if digestInput is null or 0-length, zero length
     * is used to generate the initial digest.
     * Note: the md object must be in reset state
     */
    private static byte[] getInitialHash(MessageDigest md,
        byte[] digestInput) {
        byte[] result;
        if ((digestInput == null) || (digestInput.length == 0)) {
            String digestName = md.getAlgorithm();
            result = emptyHashes.get(digestName);
            if (result == null) {
                result = md.digest();
                emptyHashes.put(digestName, result);
            }
        } else {
            result = md.digest(digestInput);
        }
        return result;
    }

    /**
     * Return the maximum size of the plaintext data that can be processed
     * using this object.
     */
    public int getMaxDataSize() {
        return maxDataSize;
    }

    /**
     * Pad the data and return the padded block.
     */
    public byte[] pad(byte[] data) throws BadPaddingException {
        return pad(data, 0, data.length);
    }

    /**
     * Pad the data and return the padded block.
     */
    public byte[] pad(byte[] data, int ofs, int len)
            throws BadPaddingException {
        if (len > maxDataSize) {
            throw new BadPaddingException("Data must be shorter than "
                + (maxDataSize + 1) + " bytes but received "
                + len + " bytes.");
        }
        switch (type) {
        case PAD_NONE:
            return RSACore.convert(data, ofs, len);
        case PAD_BLOCKTYPE_1:
        case PAD_BLOCKTYPE_2:
            return padV15(data, ofs, len);
        case PAD_OAEP_MGF1:
            return padOAEP(data, ofs, len);
        default:
            throw new AssertionError();
        }
    }

    /**
     * Unpad the padded block and return the data.
     */
    public byte[] unpad(byte[] padded) throws BadPaddingException {
        if (padded.length != paddedSize) {
            throw new BadPaddingException("Decryption error." +
                "The padded array length (" + padded.length +
                ") is not the specified padded size (" + paddedSize + ")");
        }
        switch (type) {
        case PAD_NONE:
            return padded;
        case PAD_BLOCKTYPE_1:
        case PAD_BLOCKTYPE_2:
            return unpadV15(padded);
        case PAD_OAEP_MGF1:
            return unpadOAEP(padded);
        default:
            throw new AssertionError();
        }
    }

    /**
     * PKCS#1 v1.5 padding (blocktype 1 and 2).
     */
    private byte[] padV15(byte[] data, int ofs, int len) throws BadPaddingException {
        byte[] padded = new byte[paddedSize];
        System.arraycopy(data, ofs, padded, paddedSize - len, len);
        int psSize = paddedSize - 3 - len;
        int k = 0;
        padded[k++] = 0;
        padded[k++] = (byte)type;
        if (type == PAD_BLOCKTYPE_1) {
            // blocktype 1: all padding bytes are 0xff
            while (psSize-- > 0) {
                padded[k++] = (byte)0xff;
            }
        } else {
            // blocktype 2: padding bytes are random non-zero bytes
            if (random == null) {
                random = JCAUtil.getSecureRandom();
            }
            // generate non-zero padding bytes
            // use a buffer to reduce calls to SecureRandom
            while (psSize > 0) {
                // extra bytes to avoid zero bytes,
                // number of zero bytes <= 4 in 98% cases
                byte[] r = new byte[psSize + 4];
                random.nextBytes(r);
                for (int i = 0; i < r.length && psSize > 0; i++) {
                    if (r[i] != 0) {
                        padded[k++] = r[i];
                        psSize--;
                    }
                }
            }
        }
        return padded;
    }

    /**
     * PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).
     *
     * Note that we want to make it a constant-time operation
     */
    private byte[] unpadV15(byte[] padded) throws BadPaddingException {
        int k = 0;
        boolean bp = false;

        if (padded[k++] != 0) {
            bp = true;
        }
        if (padded[k++] != type) {
            bp = true;
        }
        int p = 0;
        while (k < padded.length) {
            int b = padded[k++] & 0xff;
            if ((b == 0) && (p == 0)) {
                p = k;
            }
            if ((k == padded.length) && (p == 0)) {
                bp = true;
            }
            if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&
                    (p == 0)) {
                bp = true;
            }
        }
        int n = padded.length - p;
        if (n > maxDataSize) {
            bp = true;
        }

        // copy useless padding array for a constant-time method
        byte[] padding = new byte[p];
        System.arraycopy(padded, 0, padding, 0, p);

        byte[] data = new byte[n];
        System.arraycopy(padded, p, data, 0, n);

        BadPaddingException bpe = new BadPaddingException("Decryption error");

        if (bp) {
            throw bpe;
        } else {
            return data;
        }
    }

    /**
     * PKCS#1 v2.0 OAEP padding (MGF1).
     * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002)
     */
    private byte[] padOAEP(byte[] M, int ofs, int len) throws BadPaddingException {
        if (random == null) {
            random = JCAUtil.getSecureRandom();
        }
        int hLen = lHash.length;

        // 2.d: generate a random octet string seed of length hLen
        // if necessary
        byte[] seed = new byte[hLen];
        random.nextBytes(seed);

        // buffer for encoded message EM
        byte[] EM = new byte[paddedSize];

        // start and length of seed (as index into EM)
        int seedStart = 1;
        int seedLen = hLen;

        // copy seed into EM
        System.arraycopy(seed, 0, EM, seedStart, seedLen);

        // start and length of data block DB in EM
        // we place it inside of EM to reduce copying
        int dbStart = hLen + 1;
        int dbLen = EM.length - dbStart;

        // start of message M in EM
        int mStart = paddedSize - len;

        // build DB
        // 2.b: Concatenate lHash, PS, a single octet with hexadecimal value
        // 0x01, and the message M to form a data block DB of length
        // k - hLen -1 octets as DB = lHash || PS || 0x01 || M
        // (note that PS is all zeros)
        System.arraycopy(lHash, 0, EM, dbStart, hLen);
        EM[mStart - 1] = 1;
        System.arraycopy(M, ofs, EM, mStart, len);

        // produce maskedDB
        mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);

        // produce maskSeed
        mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);

        return EM;
    }

    /**
     * PKCS#1 v2.1 OAEP unpadding (MGF1).
     */
    private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {
        byte[] EM = padded;
        boolean bp = false;
        int hLen = lHash.length;

        if (EM[0] != 0) {
            bp = true;
        }

        int seedStart = 1;
        int seedLen = hLen;

        int dbStart = hLen + 1;
        int dbLen = EM.length - dbStart;

        mgf.generateAndXor(EM, dbStart, dbLen, seedLen, EM, seedStart);
        mgf.generateAndXor(EM, seedStart, seedLen, dbLen, EM, dbStart);

        // verify lHash == lHash'
        for (int i = 0; i < hLen; i++) {
            if (lHash[i] != EM[dbStart + i]) {
                bp = true;
            }
        }

        int padStart = dbStart + hLen;
        int onePos = -1;

        for (int i = padStart; i < EM.length; i++) {
            int value = EM[i];
            if (onePos == -1) {
                if (value == 0x00) {
                    // continue;
                } else if (value == 0x01) {
                    onePos = i;
                } else {  // Anything other than {0,1} is bad.
                    bp = true;
                }
            }
        }

        // We either ran off the rails or found something other than 0/1.
        if (onePos == -1) {
            bp = true;
            onePos = EM.length - 1;  // Don't inadvertently return any data.
        }

        int mStart = onePos + 1;

        // copy useless padding array for a constant-time method
        byte [] tmp = new byte[mStart - padStart];
        System.arraycopy(EM, padStart, tmp, 0, tmp.length);

        byte [] m = new byte[EM.length - mStart];
        System.arraycopy(EM, mStart, m, 0, m.length);

        BadPaddingException bpe = new BadPaddingException("Decryption error");

        if (bp) {
            throw bpe;
        } else {
            return m;
        }
    }
}