text:
module Rpush
  module Daemon
    module Apns
      class FeedbackReceiver
        include Reflectable
        include Loggable

        TUPLE_BYTES = 38
        HOSTS = {
          :production  => ['feedback.push.apple.com', 2196],
          :development => ['feedback.sandbox.push.apple.com', 2196], # deprecated
          :sandbox     => ['feedback.sandbox.push.apple.com', 2196]
        }

        def initialize(app)
          @app = app
          @host, @port = HOSTS[@app.environment.to_sym]
          @poll = Rpush.config.feedback_poll
          @certificate = app.certificate
          @password = app.password
          @interruptible_sleep = InterruptibleSleep.new
        end

        def start
          return if Rpush.config.push

          @thread = Thread.new do
            loop do
              break if @stop
              check_for_feedback
              @interruptible_sleep.sleep @poll
            end

            Rpush::Daemon.store.release_connection
          end
        end

        def stop
          @stop = true
          @interruptible_sleep.interrupt_sleep
          @thread.join if @thread
        end

        def check_for_feedback
          connection = nil
          begin
            connection = Rpush::Daemon::TcpConnection.new(@app, @host, @port)
            connection.connect

            while tuple = connection.read(TUPLE_BYTES)
              timestamp, device_token = parse_tuple(tuple)
              create_feedback(timestamp, device_token)
            end
          rescue StandardError => e
            log_error(e)
            reflect(:error, e)
          ensure
            connection.close if connection
          end
        end

        protected

        def parse_tuple(tuple)
          failed_at, _, device_token = tuple.unpack("N1n1H*")
          [Time.at(failed_at).utc, device_token]
        end

        def create_feedback(failed_at, device_token)
          formatted_failed_at = failed_at.strftime("%Y-%m-%d %H:%M:%S UTC")
          log_info("[FeedbackReceiver] Delivery failed at #{formatted_failed_at} for #{device_token}.")

          feedback = Rpush::Daemon.store.create_apns_feedback(failed_at, device_token, @app)
          reflect(:apns_feedback, feedback)
        end
      end
    end
  end
end


text:
#include <debug.h>
#include <crypto5_wrapper.h>

/* This file is a wrapper to the crypto5_eng.c.
 * This is required so that we maintian the backward compatibility
 * with the authentication logic in image_verify.c
 */
static struct crypto_dev dev;

void crypto_init_params(struct crypto_init_params * params)
{
	crypto5_init_params(&dev, params);
}

void crypto_eng_cleanup(void)
{
	crypto5_cleanup(&dev);
}

void crypto_unlock(void)
{
	crypto5_unlock_pipes(&dev);
}

void ce_clock_init(void)
{
	/* Clock init is done during crypto_init. */
}

void crypto_eng_reset(void)
{
	/* Reset tied in with the clock init. */
}

void crypto_eng_init(void)
{
	crypto5_init(&dev);
}

void crypto_set_sha_ctx(void *ctx_ptr,
						unsigned int bytes_to_write,
						crypto_auth_alg_type auth_alg,
						bool first,
						bool last)
{
	crypto_SHA256_ctx *sha256_ctx = (crypto_SHA256_ctx *) ctx_ptr;

	sha256_ctx->flags = 0;

	if (first)
		sha256_ctx->flags |= CRYPTO_FIRST_CHUNK;

	if (last)
		sha256_ctx->flags |= CRYPTO_LAST_CHUNK;

	sha256_ctx->bytes_to_write = bytes_to_write;

	crypto5_set_ctx(&dev, ctx_ptr, auth_alg);

	/* Clear the flags. */
	sha256_ctx->flags = 0;
}

void crypto_send_data(void *ctx_ptr,
					  unsigned char *data_ptr,
					  unsigned int buff_size,
					  unsigned int bytes_to_write,
					  unsigned int *ret_status)
{
	*ret_status = crypto5_send_data(&dev, ctx_ptr, data_ptr);
}

void crypto_get_digest(unsigned char *digest_ptr,
					   unsigned int *ret_status,
					   crypto_auth_alg_type auth_alg,
					   bool last)
{
	*ret_status = crypto5_get_digest(&dev, digest_ptr, auth_alg);
}

void crypto_get_ctx(void *ctx_ptr)
{
	crypto5_get_ctx(&dev, ctx_ptr);
}

uint32_t crypto_get_max_auth_blk_size()
{
	return crypto5_get_max_auth_blk_size(&dev);
}

redpajama_set_name: RedPajamaGithub


text:
window.hyper = (function(hyper, socketIoPort)
{
	// Buffer for storing hyper.log messages.
	var hyperLogBuffer = []

	// This variable is true if we are connected to the server.
	hyper.isConnected = false

	// User-defined function that is called when the app is
	// connected to the server.
	hyper.onConnectedFun = null

	// Sets the onConnected function. You can use this function
	// to display a status message, for example.
	hyper.onConnected = function(fun)
	{
		if (hyper.isConnected)
		{
			// Already connected.
			fun()
		}
		else
		{
			// Call when connected.
			hyper.onConnectedFun = fun
		}
	}

	// Send result of evaluating JS to the UI.
	hyper.sendJsResult = function(result)
	{
		hyper.isConnected &&
		hyper.IoSocket.emit('hyper.result', result)
	}

	// Log to remote HyperReload Workbench window.
	hyper.rlog = function(message)
	{
		if (hyper.isConnected)
		{
			hyper.IoSocket.emit('hyper.log', message)
		}
		else
		{
			hyperLogBuffer.push(message)
		}
	}

	// If you want, you can set hyper.log to console.log in your code.
	hyper.log = hyper.log || hyper.rlog

	function sendBufferedHyperLogMessages()
	{
		for (var i = 0; i < hyperLogBuffer.length; ++ i)
		{
			hyper.log(hyperLogBuffer[i])
		}
		hyperLogBuffer = []
	}

	// Called from native code. NOT USED.
	/*hyper.nativeConsoleMessageCallBack = function(message)
	{
		hyper.log(message)
	}*/

	window.onerror = function(msg, url, linenumber)
	{
		url = url || 'unknown'
		//console.log('@@@ url: ' + url)
		// Strip off hostname from url.
		// url: http://192.168.0.102:4042/hyper.reloader
		var pos = url.indexOf('//', 0)
		if (pos < 0) { pos = 0 }
		var pos2 = url.indexOf('/', pos + 2)
		if (pos2 < 0) { pos2 = pos } else { ++pos2 }
		var file = url.substring(pos2)
		var errorMessage = '[ERR] ' + msg + ' [' + file + ': ' + linenumber + ']'
		hyper.log(errorMessage)
		return true
	}

	var baseUrl = 'http://' + window.location.hostname

	function connect()
	{
		// Only connect in the topmost window!
		if (window !== window.top) { return }

		var socket = io(baseUrl + ':' + socketIoPort)
		hyper.IoSocket = socket
		socket.on('hyper.run', function(data)
		{
			if (!hyper.isReloading)
			{
				hyper.isReloading = true

				// Show the loading toast.
				hyper.showMessage('Loading')

				setTimeout(function() {
					window.location.replace(data.url) },
					300)
			}
		})
		socket.on('hyper.reload', function(data)
		{
			if (!hyper.isReloading)
			{
				hyper.isReloading = true

				// Show the loading toast.
				hyper.showMessage('Loading')

				setTimeout(function() {
					window.location.reload(true) },
					300)
			}
		})
		socket.on('hyper.eval', function(data)
		{
			try
			{
				var result = eval(data)
				hyper.sendJsResult(result)
			}
			catch (err)
			{
				hyper.sendJsResult('[ERR] ' + err)
			}
		})
		socket.on('connect', function()
		{
			socket.emit('hyper.client-connected', null)
			hyper.isConnected = true
			if (hyper.onConnectedFun)
			{
				hyper.onConnectedFun()
			}
			sendBufferedHyperLogMessages()
		})
	}

	/**
	 * Go to the start page. When using the
	 * HyperReload app, this is the main screen.
	 */
	hyper.gotoStartPage = function()
	{
		history.go(-(history.length-1))
	}

	/**
	 * Displays a message box similar to a Toast on Android.
	 */
	hyper.showMessage = function(message, id, duration)
	{
		var toast = document.createElement('div')
		var width = Math.min(
			message.length * 16,
			window.innerWidth - 40)
		var left = ((window.innerWidth - width) / 2) - 20 //padding

		toast.id = id || 'hyper-message'
		toast.style.width = width + 'px'
		toast.style.position = 'absolute'
		toast.style.left = left + 'px'
		toast.style.bottom = '40px'
		toast.style.padding = '10px 20px'
		toast.style.borderRadius = '8px'
		toast.style.MozBorderRadius = '8px'
		toast.style.WebkitBorderRadius = '8px'
		toast.style.background = '#FFFFFF'
		toast.style.border = '1px solid #000000'
		toast.style.fontFamily = 'sans-serif'
		toast.style.fontSize = '18px'
		toast.style.fontWeight = 'bold'
		toast.style.color = '#000000'
		toast.style.textAlign = 'center'
		toast.style.visibility = 'visible'
		toast.style.zIndex = '999999'
		toast.innerHTML = message

		document.body.appendChild(toast)

		if (duration)
		{
			setTimeout(function() {
				document.body.removeChild(toast) },
				duration)
		}
	}

	/**
	 * Hides the message box.
	 */
	hyper.hideMessage = function(id)
	{
		var toast  = document.getElementById(id || 'hyper-message')
		document.body.removeChild(toast)
	}

	// Connect when page has loaded (connecting sooner may stall page load).
	window.addEventListener('DOMContentLoaded', function(e) { connect() }, true)

	return hyper

})(window.hyper || {}, __SOCKET_IO_PORT_INSERTED_BY_SERVER__)


text:
@class FavoritesAsyncUploader, FavoritesCDNInfoDB, FavoritesItemDB, NSMutableArray, NSString;

@interface FavoritesAsyncUploadMgr : MMObject <CNetworkStatusExt, FavoritesAsyncUploaderDelegate>
{
    NSMutableArray *_uploadingQueue;
    NSMutableArray *_failedQueue;
    NSMutableArray *_activeQueue;
    _Bool _isUploading;
    FavoritesCDNInfoDB *_favCdnDB;
    FavoritesItemDB *_favItemDB;
    FavoritesAsyncUploader *_favUploader;
    id <FavoritesAsyncUploadMgrDelegate> _delegate;
}

@property(nonatomic) __weak id <FavoritesAsyncUploadMgrDelegate> delegate; // @synthesize delegate=_delegate;
- (void).cxx_destruct;
- (void)ReachabilityChange:(unsigned int)arg1;
- (_Bool)deleteCdnInfoByFavoritesItemLocalId:(unsigned int)arg1;
- (_Bool)updateItemXMLInItemDB:(id)arg1;
- (void)onUploadFavItem:(id)arg1 LocalDataId:(id)arg2 FinishedLength:(int)arg3 TotalLength:(int)arg4;
- (void)onUploadFail:(id)arg1 ErrCode:(int)arg2;
- (void)onUploadFinished:(id)arg1;
- (id)getAsyncUploadFaildItemList;
- (id)getUploadPausedItemList;
- (id)getUploadItemList;
- (void)changeToNoWifi;
- (_Bool)pauseAsyncUploadFavoritesItem:(unsigned int)arg1;
- (_Bool)restartAllAsyncUploadFailedItems;
- (_Bool)startAsyncUploadItem:(id)arg1 IsPriority:(_Bool)arg2;
- (id)getUploadCdnInfoByLocalItemDataId:(id)arg1 andType:(int)arg2;
- (_Bool)updateCdnInfo:(id)arg1;
- (id)getNextAsyncUploadCdnInfoByLocalItemId:(unsigned int)arg1;
- (void)tryStartUpload;
- (void)setItemUploadFail:(id)arg1 ErrCode:(int)arg2;
- (_Bool)delAsyncUploadItem:(id)arg1;
- (_Bool)addAsyncUploadItem:(id)arg1;
- (_Bool)loadAsyncUploadFailedQueue;
- (_Bool)loadAsyncUploadingQueue;
- (void)dealloc;
- (void)initDB:(id)arg1;
- (id)init;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
NS_ASSUME_NONNULL_BEGIN

@class CWVAutofillController;
@class CWVBackForwardList;
@class CWVBackForwardListItem;
@class CWVScriptCommand;
@class CWVTranslationController;
@class CWVWebViewConfiguration;
@protocol CWVNavigationDelegate;
@protocol CWVUIDelegate;
@class CWVSSLStatus;

// A web view component (like WKWebView) which uses iOS Chromium's web view
// implementation.
//
// In addition to WKWebView features, it allows Translate, Find In Page,
// Customizable Context Menus, and maybe more.
//
// Concrete instances can be created through CWV.
CWV_EXPORT
@interface CWVWebView : UIView

// The configuration of the web view.
@property(nonatomic, readonly) CWVWebViewConfiguration* configuration;

// This web view's navigation delegate.
@property(nonatomic, weak, nullable) id<CWVNavigationDelegate>
    navigationDelegate;

// This web view's translation controller.
@property(nonatomic, readonly) CWVTranslationController* translationController;

// This web view's UI delegate
@property(nonatomic, weak, nullable) id<CWVUIDelegate> UIDelegate;

// Whether or not this web view can go backwards or forwards. KVO Compliant.
@property(nonatomic, readonly) BOOL canGoBack;
@property(nonatomic, readonly) BOOL canGoForward;

// Whether or not this web view is loading a page. KVO compliant.
@property(nonatomic, readonly, getter=isLoading) BOOL loading;

// The URL displayed in the URL bar. KVO Compliant.
//
// You should use |lastCommittedURL| instead for most of purposes other than
// rendering the URL bar.
//
// |visibleURL| and |lastCommittedURL| are the same in most cases, but with
// these exceptions:
//
// - The request was made by -loadRequest: method.
//   |visibleURL| changes to the requested URL immediately when -loadRequest:
//   was called. |lastCommittedURL| changes only after the navigation is
//   committed (i.e., the server started to respond with data and the displayed
//   page has actually changed.)
//
// - It has navigated to a page with a bad SSL certificate.
//   (not implemented for CWVWebView)
//   |visibleURL| is the bad cert page URL. |lastCommittedURL| is the previous
//   page URL.
@property(nonatomic, readonly) NSURL* visibleURL;

// A human-friendly string which represents the location of the document
// currently being loaded. KVO compliant.
//
// You can display this string instead of |visibleURL| in the URL bar. This is
// usually the scheme followed by the host name, without the path e.g.,
// @"https://example.com". Precisely speaking:
//
// - Internationalized domain names (IDN) are presented in Unicode if they're
//   regarded safe. Domain names with RTL characters will still be in
//   ACE/punycode for now (crbug.com/650760). See
//   https://dev.chromium.org/developers/design-documents/idn-in-google-chrome
//   for details.
// - Omits the path for standard schemes, excepting file and filesystem.
// - Omits the port if it is the default for the scheme.
@property(nonatomic, readonly) NSString* visibleLocationString;

// The URL of the current document. KVO Compliant.
//
// See the comment of |visibleURL| above for the difference between |visibleURL|
// and |lastCommittedURL|.
@property(nonatomic, readonly) NSURL* lastCommittedURL;

// The SSL status displayed in the URL bar. KVO compliant.
// It is nil when no page is loaded on the web view.
@property(nonatomic, readonly, nullable) CWVSSLStatus* visibleSSLStatus;

// The current page title. KVO compliant.
@property(nonatomic, readonly, copy) NSString* title;

// Page loading progress from 0.0 to 1.0. KVO compliant.
//
// It is 0.0 initially before the first navigation starts. After a navigation
// completes, it remains at 1.0 until a new navigation starts, at which point it
// is reset to 0.0.
@property(nonatomic, readonly) double estimatedProgress;

// The scroll view associated with the web view.
//
// It is reset on state restoration.
@property(nonatomic, readonly) UIScrollView* scrollView;

// A Boolean value indicating whether horizontal swipe gestures will trigger
// back-forward list navigations.
@property(nonatomic) BOOL allowsBackForwardNavigationGestures;

// The web view's autofill controller.
@property(nonatomic, readonly) CWVAutofillController* autofillController;

// An equivalent of
// https://developer.apple.com/documentation/webkit/wkwebview/1414977-backforwardlist
@property(nonatomic, readonly, nonnull) CWVBackForwardList* backForwardList;

// Enables Chrome's custom logic to handle long press and force touch. Defaults
// to NO.
// This class property setting should only be changed BEFORE any
// CWVWebViewConfiguration instance is initialized.
@property(nonatomic, class) BOOL chromeContextMenuEnabled;

// Set this to customize the underlying WKWebView's inputAccessoryView. Setting
// to nil means to use the WKWebView's default inputAccessoryView instead.
//
// In order to be displayed properly, this UIView must:
// - Set |translatesAutoresizingMaskIntoConstraints| to |NO|.
// - Return a non-zero CGSize in |intrinsicContentSize|.
//
// Explicitly redeclared this property to allow customization according to
// https://developer.apple.com/documentation/uikit/uiresponder/1621119-inputaccessoryview?language=objc
@property(nonatomic, strong, nullable) UIView* inputAccessoryView;

// Allows full customization of the user agent.
// Similar to -[WKWebView customUserAgent], but applies to all instances.
// If non-nil, this is used instead of |userAgentProduct|.
@property(nonatomic, class, copy, nullable) NSString* customUserAgent;

// The User Agent product string used to build the full User Agent.
// Deprecated. Use |customUserAgent| instead.
+ (NSString*)userAgentProduct;

// Customizes the User Agent string by inserting |product|. It should be of the
// format "product/1.0". For example:
// "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/603.1.30
// (KHTML, like Gecko) <product> Mobile/16D32 Safari/602.1" where <product>
// will be replaced with |product| or empty string if not set.
//
// NOTE: It is recommended to set |product| before initializing any web views.
// Setting |product| is only guaranteed to affect web views which have not yet
// been initialized. However, exisiting web views could also be affected
// depending upon their internal state.
//
// Deprecated. Use |customUserAgent| instead.
+ (void)setUserAgentProduct:(NSString*)product;

// Use this method to set the necessary credentials used to communicate with
// the Google API for features such as translate. See this link for more info:
// https://support.google.com/googleapi/answer/6158857
// This method must be called before any |CWVWebViews| are instantiated for
// the keys to be used.
+ (void)setGoogleAPIKey:(NSString*)googleAPIKey
               clientID:(NSString*)clientID
           clientSecret:(NSString*)clientSecret;

- (instancetype)initWithFrame:(CGRect)frame
                configuration:(CWVWebViewConfiguration*)configuration;

// If |wkConfiguration| is provided, the underlying WKWebView is
// initialized with |wkConfiguration|, and assigned to
// |*createdWKWebView| if |createdWKWebView| is not nil.
// |*createdWKWebView| will be provided only if |wkConfiguration| is provided,
// otherwise it will always be reset to nil.
// IMPORTANT NOTE: Also create a new WKUserContentController and set it in the
// |wkConfiguration| before calling this method.
//
// IMPORTANT: Use |*createdWKWebView| just as a return value of
// -[WKNavigationDelegate
// webView:createWebViewWithConfiguration:...], but for nothing
// else. e.g., You must not access its properties/methods.
- (instancetype)initWithFrame:(CGRect)frame
                configuration:(CWVWebViewConfiguration*)configuration
              WKConfiguration:(nullable WKWebViewConfiguration*)wkConfiguration
             createdWKWebView:(WKWebView* _Nullable* _Nullable)createdWebView
    NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE;
- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE;

// Navigates backwards or forwards by one page.  Does nothing if the
// corresponding |canGoBack| or |canGoForward| method returns NO.
- (void)goBack;
- (void)goForward;

// Navigates to the specified |item| in the |self.backForwardList| and returns
// YES. Does nothing and returns NO when |item| is the current item, or it
// belongs to an expired list, or the list does not contain |item|.
- (BOOL)goToBackForwardListItem:(CWVBackForwardListItem*)item;

// Reloads the current page.
- (void)reload;

// Stops loading the current page.
- (void)stopLoading;

// Loads the given URL request in this web view.
// Unlike WKWebView, this method supports HTTPBody.
- (void)loadRequest:(NSURLRequest*)request;

// Evaluates a JavaScript string in the main frame of the page content world.
// `completion` is invoked with the result of evaluating the script and a
// boolean representing success (`YES`) or failure (`NO`) of the evaluation.
//
// Evaluation of `javaScriptString` will fail (and return NO to `completion`) if
// there is no current internal representation of the main frame. This can occur
// when the web view is navigating or if the current page content does not allow
// JavaScript execution (ex: JS disabled or PDF content).
- (void)evaluateJavaScript:(NSString*)javaScriptString
                completion:(void (^)(id result, NSError* error))completion;

// Adds a message handler for messages sent from JavaScript.
// `handler` will be called each time a message is sent with the corresponding
// value of `command`. To send messages from JavaScript, use the WebKit
// message handler `CWVWebViewMessage` and provide values for the `command` and
// `payload` keys.
// `command` must be a string and match the registered handler `command` string
// `payload` must be a dictionary.
//
// Example call from JavaScript:
//
//  let message = {
//    'command': 'myFeatureMessage',
//    'payload' : {'key1':'value1', 'key2':42}
//  }
//  window.webkit.messageHandlers['CWVWebViewMessage'].postMessage(message);
//
// NOTE: Only a single `handler` may be registered for a given `command`.
- (void)addMessageHandler:(void (^)(NSDictionary* payload))handler
               forCommand:(NSString*)command;

// Removes the message handler associated with `command` previously added with
// `addMessageHandler:forCommand:`.
- (void)removeMessageHandlerForCommand:(NSString*)command;

@end

NS_ASSUME_NONNULL_END

#endif  // IOS_WEB_VIEW_PUBLIC_CWV_WEB_VIEW_H_


text:
<TITLE> Splat Quick Start </TITLE>

Sections:
Overview
Tabs
WebSpider
More Help

Self Plagiarism:

Self-plagiarism occurs when an author reuses portions of their previous writings in subsequent research papers. Occasionally, the derived paper is simply a re-titled and reformatted version of the original one, but more frequently it is assembled from bits and pieces of previous work.
It is our belief that self-plagiarism is detrimental to scientific progress and bad for our academic community. Flooding conferences and journals with near-identical papers makes searching for information relevant to a particular topic harder than it has to be. It also rewards those authors who are able to break down their results into overlapping least-publishable-units over those who publish each result only once. Finally, whenever a self-plagiarized paper is allowed to be published, another, more deserving paper, is not.

 Get the self-plagiarism paper here.

Back to top

Menu Tabs: Tab selection menu

Home:

This is where you will find this Quick-Start guide along with a simple web browser
should you need to browse the internet.

Local Search:

Perform a plagiarism test on a set of files stored on a local disk

Spider Search:

Launches a WebSpider starting from a "root" html page online. The Spider will
download files linked from this page based on rules specified in the Configurations
panel. After the files are downloaded, they are compared to each other locally.
Note that this option requires a healthy internet connection.

Author Search:

Enter the names of multiple authors to do multiple Spider searches on.

Saved Search:

Recall a saved search from local disk.

Back to top

WebSpider:

The WebSpider is a utility built into SPlaT for automatically downloading relevant documents
for comparison. The spider can follow different search algorithms depending on different
needs. The following four options are currently available:

 WebSearch:
This algorithm forces the spider to follow each and every link on the page exhaustively
looking for documents. Options such as a "timeout" and "max number of files" can be set from
the Configurations panel.

 DomainWebSearch:
This algorithm is similar to the WebSearch one above, except the spider does not search sites
that are outside the "root"'s domain name.

 SmartWebSearch:
This algorithm is similar to the DomainWebSearch one above, with some additional intelligence
such as ignoring common document names and patterns.

 RegExWebSearch:
This is an advanced option, where the spider can be made to only follow links that match
a certain regular expression set by the user.

Back to top

Detailed help:

For more help please visit the "Help" option in the menu-bar.

Back to top

written by Gergely Kota, Shafik Amin, 2003


text:
package com.intellij.util.indexing;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.BitSet;

/**
* Created by Maxim.Mossienko on 8/14/13.
*/
public abstract class IdFilter {
  public static final Logger LOG = Logger.getInstance("#com.intellij.ide.util.gotoByName.DefaultFileNavigationContributor");
  private static final Key<CachedValue<IdFilter>> INSIDE_PROJECT = Key.create("INSIDE_PROJECT");
  private static final Key<CachedValue<IdFilter>> OUTSIDE_PROJECT = Key.create("OUTSIDE_PROJECT");

  public static IdFilter getProjectIdFilter(final Project project, final boolean includeNonProjectItems) {
    Key<CachedValue<IdFilter>> key = includeNonProjectItems ? OUTSIDE_PROJECT : INSIDE_PROJECT;
    return CachedValuesManager.getManager(project).getCachedValue(project, key, new CachedValueProvider<IdFilter>() {
      @Nullable
      @Override
      public Result<IdFilter> compute() {
        return Result.create(buildProjectIdFilter(project, includeNonProjectItems),
                             ProjectRootManager.getInstance(project), VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS);
      }
    }, false);
  }

  @NotNull
  private static IdFilter buildProjectIdFilter(Project project, boolean includeNonProjectItems) {
    long started = System.currentTimeMillis();
    final BitSet idSet = new BitSet();

    ContentIterator iterator = new ContentIterator() {
      @Override
      public boolean processFile(VirtualFile fileOrDir) {
        int id = ((VirtualFileWithId)fileOrDir).getId();
        if (id < 0) id = -id; // workaround for encountering invalid files, see EA-49915, EA-50599
        idSet.set(id);
        ProgressManager.checkCanceled();
        return true;
      }
    };

    if (!includeNonProjectItems) {
      ProjectRootManager.getInstance(project).getFileIndex().iterateContent(iterator);
    } else {
      FileBasedIndex.getInstance().iterateIndexableFiles(iterator, project, null);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("Done filter " + (System.currentTimeMillis()  -started) + ":" + idSet.size());
    }
    return new IdFilter() {
      @Override
      public boolean containsFileId(int id) {
        return id >= 0 && idSet.get(id);
      }
    };
  }

  public abstract boolean containsFileId(int id);
}


text:
@interface PodsDummy_Pods_OLCVideoPlayer_Tests_OLCVideoPlayer : NSObject
@end
@implementation PodsDummy_Pods_OLCVideoPlayer_Tests_OLCVideoPlayer
@end


text:
from __future__ import absolute_import, print_function

from decimal import Decimal
from datetime import datetime

from pony.converting import str2datetime
from pony.orm import *

db = Database("sqlite", "estore.sqlite", create_db=True)

class Customer(db.Entity):
    email = Required(str, unique=True)
    password = Required(str)
    name = Required(str)
    country = Required(str)
    address = Required(str)
    cart_items = Set("CartItem")
    orders = Set("Order")

class Product(db.Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    categories = Set("Category")
    description = Optional(str)
    picture = Optional(buffer)
    price = Required(Decimal)
    quantity = Required(int)
    cart_items = Set("CartItem")
    order_items = Set("OrderItem")

class CartItem(db.Entity):
    quantity = Required(int)
    customer = Required(Customer)
    product = Required(Product)

class OrderItem(db.Entity):
    quantity = Required(int)
    price = Required(Decimal)
    order = Required("Order")
    product = Required(Product)
    PrimaryKey(order, product)

class Order(db.Entity):
    id = PrimaryKey(int, auto=True)
    state = Required(str)
    date_created = Required(datetime)
    date_shipped = Optional(datetime)
    date_delivered = Optional(datetime)
    total_price = Required(Decimal)
    customer = Required(Customer)
    items = Set(OrderItem)

class Category(db.Entity):
    name = Required(str, unique=True)
    products = Set(Product)

sql_debug(True)

db.generate_mapping(create_tables=True)

# Order states
CREATED = 'CREATED'
SHIPPED = 'SHIPPED'
DELIVERED = 'DELIVERED'
CANCELLED = 'CANCELLED'

@db_session
def populate_database():
    c1 = Customer(email='john@example.com', password='***',
                  name='John Smith', country='USA', address='address 1')

    c2 = Customer(email='matthew@example.com', password='***',
                  name='Matthew Reed', country='USA', address='address 2')

    c3 = Customer(email='chuanqin@example.com', password='***',
                  name='Chuan Qin', country='China', address='address 3')

    c4 = Customer(email='rebecca@example.com', password='***',
                  name='Rebecca Lawson', country='USA', address='address 4')

    c5 = Customer(email='oliver@example.com', password='***',
                  name='Oliver Blakey', country='UK', address='address 5')

    tablets = Category(name='Tablets')
    flash_drives = Category(name='USB Flash Drives')
    ssd = Category(name='Solid State Drives')
    storage = Category(name='Data Storage')

    p1 = Product(name='Kindle Fire HD', price=Decimal('284.00'), quantity=120,
                 description='Amazon tablet for web, movies, music, apps, '
                             'games, reading and more',
                 categories=[tablets])

    p2 = Product(name='Apple iPad with Retina Display MD513LL/A (16GB, Wi-Fi, White)',
                 price=Decimal('478.50'), quantity=180,
                 description='iPad with Retina display now features an A6X chip, '
                             'FaceTime HD camera, and faster Wi-Fi',
                 categories=[tablets])

    p3 = Product(name='SanDisk Cruzer 16 GB USB Flash Drive', price=Decimal('9.99'),
                 quantity=400, description='Take it all with you on reliable '
                                           'SanDisk USB flash drive',
                 categories=[flash_drives, storage])

    p4 = Product(name='Kingston Digital DataTraveler SE9 16GB USB 2.0',
                 price=Decimal('9.98'), quantity=350,
                 description='Convenient - small, capless and pocket-sized '
                             'for easy transportability',
                 categories=[flash_drives, storage])

    p5 = Product(name='Samsung 840 Series 2.5 inch 120GB SATA III SSD',
                 price=Decimal('98.95'), quantity=0,
                 description='Enables you to boot up your computer '
                             'in as little as 15 seconds',
                 categories=[ssd, storage])

    p6 = Product(name='Crucial m4 256GB 2.5-Inch SSD SATA 6Gb/s CT256M4SSD2',
                 price=Decimal('188.67'), quantity=60,
                 description='The award-winning SSD delivers '
                             'powerful performance gains for SATA 6Gb/s systems',
                 categories=[ssd, storage])

    CartItem(customer=c1, product=p1, quantity=1)
    CartItem(customer=c1, product=p2, quantity=1)
    CartItem(customer=c2, product=p5, quantity=2)

    o1 = Order(customer=c1, total_price=Decimal('292.00'), state=DELIVERED,
               date_created=str2datetime('2012-10-20 15:22:00'),
               date_shipped=str2datetime('2012-10-21 11:34:00'),
               date_delivered=str2datetime('2012-10-26 17:23:00'))

    OrderItem(order=o1, product=p1, price=Decimal('274.00'), quantity=1)
    OrderItem(order=o1, product=p4, price=Decimal('9.98'), quantity=2)

    o2 = Order(customer=c1, total_price=Decimal('478.50'), state=DELIVERED,
               date_created=str2datetime('2013-01-10 09:40:00'),
               date_shipped=str2datetime('2013-01-10 14:03:00'),
               date_delivered=str2datetime('2013-01-13 11:57:00'))

    OrderItem(order=o2, product=p2, price=Decimal('478.50'), quantity=1)

    o3 = Order(customer=c2, total_price=Decimal('680.50'), state=DELIVERED,
               date_created=str2datetime('2012-11-03 12:10:00'),
               date_shipped=str2datetime('2012-11-04 11:47:00'),
               date_delivered=str2datetime('2012-11-07 18:55:00'))

    OrderItem(order=o3, product=p2, price=Decimal('478.50'), quantity=1)
    OrderItem(order=o3, product=p4, price=Decimal('9.98'), quantity=2)
    OrderItem(order=o3, product=p6, price=Decimal('199.00'), quantity=1)

    o4 = Order(customer=c3, total_price=Decimal('99.80'), state=SHIPPED,
               date_created=str2datetime('2013-03-11 19:33:00'),
               date_shipped=str2datetime('2013-03-12 09:40:00'))

    OrderItem(order=o4, product=p4, price=Decimal('9.98'), quantity=10)

    o5 = Order(customer=c4, total_price=Decimal('722.00'), state=CREATED,
               date_created=str2datetime('2013-03-15 23:15:00'))

    OrderItem(order=o5, product=p1, price=Decimal('284.00'), quantity=1)
    OrderItem(order=o5, product=p2, price=Decimal('478.50'), quantity=1)

@db_session
def test_queries():

    print('All USA customers')
    print()
    result = select(c for c in Customer if c.country == 'USA')[:]

    print(result)
    print()

    print('The number of customers for each country')
    print()
    result = select((c.country, count(c)) for c in Customer)[:]

    print(result)
    print()

    print('Max product price')
    print()
    result = max(p.price for p in Product)

    print(result)
    print()

    print('Max SSD price')
    print()
    result = max(p.price for p in Product for cat in p.categories if cat.name == 'Solid State Drives')

    print(result)
    print()

    print('Three most expensive products:')
    print()
    result = select(p for p in Product).order_by(desc(Product.price))[:3]

    print(result)
    print()

    print('Out of stock products')
    print()
    result = select(p for p in Product if p.quantity == 0)[:]

    print(result)
    print()

    print('Most popular product')
    print()
    result = select(p for p in Product).order_by(lambda p: desc(sum(p.order_items.quantity))).first()

    print(result)
    print()

    print('Products that have never been ordered')
    print()
    result = select(p for p in Product if not p.order_items)[:]

    print(result)
    print()

    print('Customers who made several orders')
    print()
    result = select(c for c in Customer if count(c.orders) > 1)[:]

    print(result)
    print()

    print('Three most valuable customers')
    print()
    result = select(c for c in Customer).order_by(lambda c: desc(sum(c.orders.total_price)))[:3]

    print(result)
    print()

    print('Customers whose orders were shipped')
    print()
    result = select(c for c in Customer if SHIPPED in c.orders.state)[:]

    print(result)
    print()

    print('The same query with the INNER JOIN instead of IN')
    print()
    result = select(c for c in Customer if JOIN(SHIPPED in c.orders.state))[:]

    print(result)
    print()

    print('Customers with no orders')
    print()
    result = select(c for c in Customer if not c.orders)[:]

    print(result)
    print()

    print('The same query with the LEFT JOIN instead of NOT EXISTS')
    print()
    result = left_join(c for c in Customer for o in c.orders if o is None)[:]

    print(result)
    print()

    print('Customers which ordered several different tablets')
    print()
    result = select(c for c in Customer
                      for p in c.orders.items.product
                      if 'Tablets' in p.categories.name and count(p) > 1)[:]

    print(result)
    print()

    print('Customers which ordered several products from the same category')
    print()
    result = select((customer, category.name)
                    for customer in Customer
                    for product in customer.orders.items.product
                    for category in product.categories
                    if count(product) > 1)[:]

    print(result)
    print()

    print('Customers which ordered several products from the same category in the same order')
    print()
    result = select((customer, order, category.name)
                    for customer in Customer
                    for order in customer.orders
                    for product in order.items.product
                    for category in product.categories
                    if count(product) > 1)[:]

    print(result)
    print()

    print('Products whose price varies over time')
    print()
    result = select(p.name for p in Product if count(p.order_items.price) > 1)[:]

    print(result)
    print()

    print('The same query, but with min and max price for each product')
    print()
    result = select((p.name, min(p.order_items.price), max(p.order_items.price))
                    for p in Product if count(p.order_items.price) > 1)[:]

    print(result)
    print()

    print('Orders with a discount (order total price < sum of order item prices)')
    print()
    result = select(o for o in Order if o.total_price < sum(o.items.price * o.items.quantity))[:]

    print(result)
    print()

if __name__ == '__main__':
    with db_session:
        if Customer.select().first() is None:
            populate_database()
    test_queries()


text:
namespace {

const auto kSpvEnv = SPV_ENV_UNIVERSAL_1_2;

enum Task {
  kNoTask = 0,
  kEncode,
  kDecode,
  kTest,
};

struct ScopedContext {
  ScopedContext(spv_target_env env) : context(spvContextCreate(env)) {}
  ~ScopedContext() { spvContextDestroy(context); }
  spv_context context;
};

void print_usage(char* argv0) {
  printf(
      R"(%s - Encodes or decodes a SPIR-V binary to or from a MARK-V binary.

USAGE: %s [e|d|t] [options] [<filename>]

The input binary is read from <filename>. If no file is specified,
or if the filename is "-", then the binary is read from standard input.

If no output is specified then the output is printed to stdout in a human
readable format.

WIP: MARK-V codec is in early stages of development. At the moment it only
can encode and decode some SPIR-V files and only if exacly the same build of
software is used (is doesn't write or handle version numbers yet).

Tasks:
  e               Encode SPIR-V to MARK-V.
  d               Decode MARK-V to SPIR-V.
  t               Test the codec by first encoding the given SPIR-V file to
                  MARK-V, then decoding it back to SPIR-V and comparing results.

Options:
  -h, --help      Print this help.
  --comments      Write codec comments to stderr.
  --version       Display MARK-V codec version.
  --validate      Validate SPIR-V while encoding or decoding.

  -o <filename>   Set the output filename.
                  Output goes to standard output if this option is
                  not specified, or if the filename is "-".
                  Not needed for 't' task (testing).
)",
      argv0, argv0);
}

void DiagnosticsMessageHandler(spv_message_level_t level, const char*,
                               const spv_position_t& position,
                               const char* message) {
  switch (level) {
    case SPV_MSG_FATAL:
    case SPV_MSG_INTERNAL_ERROR:
    case SPV_MSG_ERROR:
      std::cerr << "error: " << position.index << ": " << message
                << std::endl;
      break;
    case SPV_MSG_WARNING:
      std::cerr << "warning: " << position.index << ": " << message
                << std::endl;
      break;
    case SPV_MSG_INFO:
      std::cerr << "info: " << position.index << ": " << message << std::endl;
      break;
    default:
      break;
  }
}

}  // namespace

int main(int argc, char** argv) {
  const char* input_filename = nullptr;
  const char* output_filename = nullptr;

  Task task = kNoTask;

  if (argc < 3) {
    print_usage(argv[0]);
    return 0;
  }

  const char* task_char = argv[1];
  if (0 == strcmp("e", task_char)) {
    task = kEncode;
  } else if (0 == strcmp("d", task_char)) {
    task = kDecode;
  } else if (0 == strcmp("t", task_char)) {
    task = kTest;
  }

  if (task == kNoTask) {
    print_usage(argv[0]);
    return 1;
  }

  bool want_comments = false;
  bool validate_spirv_binary = false;

  for (int argi = 2; argi < argc; ++argi) {
    if ('-' == argv[argi][0]) {
      switch (argv[argi][1]) {
        case 'h':
          print_usage(argv[0]);
          return 0;
        case 'o': {
          if (!output_filename && argi + 1 < argc &&
              (task == kEncode || task == kDecode)) {
            output_filename = argv[++argi];
          } else {
            print_usage(argv[0]);
            return 1;
          }
        } break;
        case '-': {
          if (0 == strcmp(argv[argi], "--help")) {
            print_usage(argv[0]);
            return 0;
          } else if (0 == strcmp(argv[argi], "--comments")) {
            want_comments = true;
          } else if (0 == strcmp(argv[argi], "--version")) {
            fprintf(stderr, "error: Not implemented\n");
            return 1;
          } else if (0 == strcmp(argv[argi], "--validate")) {
            validate_spirv_binary = true;
          } else {
            print_usage(argv[0]);
            return 1;
          }
        } break;
        case '\0': {
          // Setting a filename of "-" to indicate stdin.
          if (!input_filename) {
            input_filename = argv[argi];
          } else {
            fprintf(stderr, "error: More than one input file specified\n");
            return 1;
          }
        } break;
        default:
          print_usage(argv[0]);
          return 1;
      }
    } else {
      if (!input_filename) {
        input_filename = argv[argi];
      } else {
        fprintf(stderr, "error: More than one input file specified\n");
        return 1;
      }
    }
  }

  const auto no_comments = spvtools::MarkvLogConsumer();
  const auto output_to_stderr = [](const std::string& str) {
    std::cerr << str;
  };

  ScopedContext ctx(kSpvEnv);

  std::unique_ptr<spvtools::MarkvModel> model =
      spvtools::CreateMarkvModel(spvtools::kMarkvModelShaderDefault);

  std::vector<uint32_t> spirv;
  std::vector<uint8_t> markv;

  spvtools::MarkvCodecOptions options;
  options.validate_spirv_binary = validate_spirv_binary;

  if (task == kEncode) {
    if (!ReadFile<uint32_t>(input_filename, "rb", &spirv)) return 1;
    assert(!spirv.empty());

    if (SPV_SUCCESS != spvtools::SpirvToMarkv(
        ctx.context, spirv, options, *model, DiagnosticsMessageHandler,
        want_comments ? output_to_stderr : no_comments,
        spvtools::MarkvDebugConsumer(), &markv)) {
      std::cerr << "error: Failed to encode " << input_filename << " to MARK-V "
                << std::endl;
      return 1;
    }

    if (!WriteFile<uint8_t>(output_filename, "wb", markv.data(),
                            markv.size())) return 1;
  } else if (task == kDecode) {
    if (!ReadFile<uint8_t>(input_filename, "rb", &markv)) return 1;
    assert(!markv.empty());

    if (SPV_SUCCESS != spvtools::MarkvToSpirv(
        ctx.context, markv, options, *model, DiagnosticsMessageHandler,
        want_comments ? output_to_stderr : no_comments,
        spvtools::MarkvDebugConsumer(), &spirv)) {
      std::cerr << "error: Failed to decode " << input_filename << " to SPIR-V "
                << std::endl;
      return 1;
    }

    if (!WriteFile<uint32_t>(output_filename, "wb", spirv.data(),
                             spirv.size())) return 1;
  } else if (task == kTest) {
    if (!ReadFile<uint32_t>(input_filename, "rb", &spirv)) return 1;
    assert(!spirv.empty());

    std::vector<uint32_t> spirv_before;
    spvtools::Optimizer optimizer(kSpvEnv);
    optimizer.RegisterPass(spvtools::CreateCompactIdsPass());
    if (!optimizer.Run(spirv.data(), spirv.size(), &spirv_before)) {
      std::cerr << "error: Optimizer failure on: "
                << input_filename << std::endl;
    }

    std::vector<std::string> encoder_instruction_bits;
    std::vector<std::string> encoder_instruction_comments;
    std::vector<std::vector<uint32_t>> encoder_instruction_words;
    std::vector<std::string> decoder_instruction_bits;
    std::vector<std::string> decoder_instruction_comments;
    std::vector<std::vector<uint32_t>> decoder_instruction_words;

    const auto encoder_debug_consumer = [&](
        const std::vector<uint32_t>& words, const std::string& bits,
        const std::string& comment) {
      encoder_instruction_words.push_back(words);
      encoder_instruction_bits.push_back(bits);
      encoder_instruction_comments.push_back(comment);
      return true;
    };

    if (SPV_SUCCESS != spvtools::SpirvToMarkv(
        ctx.context, spirv_before, options, *model, DiagnosticsMessageHandler,
        want_comments ? output_to_stderr : no_comments,
        encoder_debug_consumer, &markv)) {
      std::cerr << "error: Failed to encode " << input_filename << " to MARK-V "
                << std::endl;
      return 1;
    }

    const auto write_bug_report = [&]() {
      for (size_t inst_index = 0; inst_index < decoder_instruction_words.size();
           ++inst_index) {
        std::cerr << "\nInstruction #" << inst_index << std::endl;
        std::cerr << "\nEncoder words: ";
        for (uint32_t word : encoder_instruction_words[inst_index])
          std::cerr << word << " ";
        std::cerr << "\nDecoder words: ";
        for (uint32_t word : decoder_instruction_words[inst_index])
          std::cerr << word << " ";
        std::cerr << std::endl;

        std::cerr << "\nEncoder bits: " << encoder_instruction_bits[inst_index];
        std::cerr << "\nDecoder bits: " << decoder_instruction_bits[inst_index];
        std::cerr << std::endl;

        std::cerr << "\nEncoder comments:\n"
                  << encoder_instruction_comments[inst_index];
        std::cerr << "Decoder comments:\n"
                  << decoder_instruction_comments[inst_index];
        std::cerr << std::endl;
      }
    };

    const auto decoder_debug_consumer = [&](
        const std::vector<uint32_t>& words, const std::string& bits,
        const std::string& comment) {
      const size_t inst_index = decoder_instruction_words.size();
      if (inst_index >= encoder_instruction_words.size()) {
        write_bug_report();
        std::cerr << "error: Decoder has more instructions than encoder: "
                  << input_filename << std::endl;
        return false;
      }

      decoder_instruction_words.push_back(words);
      decoder_instruction_bits.push_back(bits);
      decoder_instruction_comments.push_back(comment);

      if (encoder_instruction_words[inst_index] !=
          decoder_instruction_words[inst_index]) {
        write_bug_report();
        std::cerr << "error: Words of the last decoded instruction differ from "
                  "reference: " << input_filename << std::endl;
        return false;
      }

      if (encoder_instruction_bits[inst_index] !=
          decoder_instruction_bits[inst_index]) {
        write_bug_report();
        std::cerr << "error: Bits of the last decoded instruction differ from "
                  "reference: " << input_filename << std::endl;
        return false;
      }
      return true;
    };

    std::vector<uint32_t> spirv_after;
    const spv_result_t decoding_result = spvtools::MarkvToSpirv(
        ctx.context, markv, options, *model, DiagnosticsMessageHandler,
        want_comments ? output_to_stderr : no_comments,
        decoder_debug_consumer, &spirv_after);

    if (decoding_result == SPV_REQUESTED_TERMINATION) {
      std::cerr << "error: Decoding interrupted by the debugger: "
                << input_filename << std::endl;
      return 1;
    }

    if (decoding_result != SPV_SUCCESS) {
      std::cerr << "error: Failed to decode encoded " << input_filename
                << " back to SPIR-V " << std::endl;
      return 1;
    }

    assert(spirv_before.size() == spirv_after.size());
    assert(std::mismatch(std::next(spirv_before.begin(), 5), spirv_before.end(),
                         std::next(spirv_after.begin(), 5)) ==
           std::make_pair(spirv_before.end(), spirv_after.end()));
  }

  return 0;
}


text:
"""
Module for solving Rubik's Cube F2L.
"""

from pycuber import *
from pycuber.helpers import fill_unknowns
from .util import a_star_search, path_actions

class F2LPairSolver(object):
    """
    F2LPairSolver() => Solver for solving an F2L pair.
    """
    def __init__(self, cube=None, pair=None):
        self.cube = cube
        if pair and pair not in ["FR", "RB", "BL", "LF"]:
            pair = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(pair)]
        self.pair = pair

    def feed(self, cube, pair):
        """
        Feed Cube to the solver.
        """
        self.cube = cube
        if pair not in ["FR", "RB", "BL", "LF"]:
            pair = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(pair)]
        self.pair = pair

    def get_pair(self):
        """
        Get the F2L pair (corner, edge).
        """
        colours = (
            self.cube[self.pair[0]].colour,
            self.cube[self.pair[1]].colour,
            self.cube["D"].colour
            )
        result_corner = self.cube.children.copy()
        for c in colours[:2]:
            result_corner &= self.cube.has_colour(c)
        result_edge = result_corner & self.cube.select_type("edge")
        result_corner &= self.cube.has_colour(colours[2])
        return (list(result_corner)[0], list(result_edge)[0])

    def estimated_position(self):
        """
        Get the estimated cubie of solved pair.
        """
        corner = {"D":self.cube["D"]["D"]}
        edge = {}
        for cubie in (corner, edge):
            for face in self.pair:
                cubie.update({face:self.cube[face][face]})
        return (Corner(**corner), Edge(**edge))

    def get_slot(self):
        """
        Get the slot position of this pair.
        """
        corner, edge = self.get_pair()
        corner_slot, edge_slot = corner.location.replace("D", "", 1), edge.location
        if "U" not in corner_slot and corner_slot not in ["FR", "RB", "BL", "LF"]:
            corner_slot = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(corner_slot)]
        if "U" not in edge_slot and edge_slot not in ["FR", "RB", "BL", "LF"]:
            edge_slot = ["FR", "RB", "BL", "LF"][["RF", "BR", "LB", "FL"].index(edge_slot)]
        if "U" in corner_slot and "U" in edge_slot:
            return ("SLOTFREE", (None, None), (corner, edge))
        if "U" in corner_slot:
            return ("CSLOTFREE", (None, edge_slot), (corner, edge))
        if "U" in edge_slot:
            return ("ESLOTFREE", (corner_slot, None), (corner, edge))
        if corner_slot not in [edge_slot, edge_slot[::-1]]:
            return ("DIFFSLOT", (corner_slot, edge_slot), (corner, edge))
        if (corner, edge) == self.estimated_position():
            return ("SOLVED", (corner_slot, edge_slot), (corner, edge))
        return ("WRONGSLOT", (corner_slot, edge_slot), (corner, edge))

    @staticmethod
    def combining_goal(state):
        """
        Check if two Cubies are combined on the U face.
        """
        ((corner, edge), (L, U, F, D, R, B)) = state
        if "U" not in corner or "U" not in edge: return False
        if set(edge).issubset(set(corner)): return True
        elif set(edge.facings.keys()).issubset(set(corner.facings.keys())): return False
        opposite = {"L":"R", "R":"L", "F":"B", "B":"F"}
        edge_facings = list(edge)
        for i, (face, square) in enumerate(edge_facings):
            if face == "U":
                if square != corner[opposite[edge_facings[(i+1)%2][0]]]:
                    return False
            else:
                if square != corner["U"]:
                    return False
        return True

    @staticmethod
    def _rotate(pair, step):
        """
        Simulate the cube rotation by updating the pair.
        """
        step = Step(step)
        movement = {
            "U": "RFLB",
            "D": "LFRB",
            "R": "FUBD",
            "L": "FDBU",
            "F": "URDL",
            "B": "ULDR",
            }[step.face]
        movement = {
            movement[i]: movement[(i + step.is_clockwise + (-1 * step.is_counter_clockwise) + (2 * step.is_180)) % 4]
            for i in range(4)
            }
        for cubie in pair:
            if step.face not in cubie:
                if cubie.type == "edge":
                    result_edge = cubie.copy()
                else:
                    result_corner = cubie.copy()
            else:
                result = {}
                for face, square in cubie:
                    if face not in movement:
                        result[face] = square
                    else:
                        result[movement[face]] = square
                if len(result) == 2:
                    result_edge = Edge(**result)
                else:
                    result_corner = Corner(**result)
        return (result_corner, result_edge)

    @staticmethod
    def combining_successors(state, last_action=()):
        """
        Successors function for finding path of combining F2L pair.
        """
        ((corner, edge), (L, U, F, D, R, B)) = state
        U_turns = [Formula("U"), Formula("U'"), Formula("U2")] if len(last_action) != 1 else []
        R_turns = [Formula("R U R'"), Formula("R U' R'"), Formula("R U2 R'")] if "R" not in last_action else []
        F_turns = [Formula("F' U F"), Formula("F' U' F"), Formula("F' U2 F")] if "F" not in last_action else []
        for act in (U_turns + R_turns + F_turns):
            new = (corner, edge)
            for q in act:
                new = F2LPairSolver._rotate(new, q)
            yield act, (new, (L, U, F, D, R, B))

    def combining_search(self):
        """
        Searching the path for combining the pair.
        """
        start = (
            self.get_pair(),
            (
                self.cube["L"],
                self.cube["U"],
                self.cube["F"],
                self.cube["D"],
                self.cube["R"],
                self.cube["B"],
                ),
            )
        return sum(path_actions(a_star_search(start,
                       self.combining_successors,
                       lambda x: len(x),
                       self.combining_goal)), Formula())

    def combining_setup(self):
        """
        Setup for some special F2L cases.
        """
        (slot_type, (corner_slot, edge_slot), (corner, edge)) = self.get_slot()
        cycle = ["FR", "RB", "BL", "LF"]
        if slot_type == "SLOTFREE":
            return ("FR", Formula(Step("y") * cycle.index(self.pair) or []))
        elif slot_type == "CSLOTFREE":
            return (cycle[-(cycle.index(edge_slot) - cycle.index(self.pair))],
                    Formula(Step("y") * cycle.index(edge_slot) or []))
        elif slot_type in ("ESLOTFREE", "WRONGSLOT"):
            return (cycle[-(cycle.index(corner_slot) - cycle.index(self.pair))],
                    Formula(Step("y") * cycle.index(corner_slot) or []))
        elif slot_type == "DIFFSLOT":
            if corner_slot != self.pair: corner_slot, edge_slot = edge_slot, corner_slot
            result = Formula(Step("y") * cycle.index(edge_slot) or [])
            result += Formula("R U R'")
            result += Formula(Step("y'") * cycle.index(edge_slot) or [])
            result += Formula(Step("y") * cycle.index(corner_slot) or [])
            if result[-1].face == "y" and result[-2].face == "y":
                result[-2] += result[-1]
                del result[-1]
            return (cycle[-(cycle.index(corner_slot) - cycle.index(self.pair))], result)
        else:
            return (cycle[-cycle.index(self.pair)], Formula())

    def combine(self):
        """
        Combine the pair.
        """
        self.pair, setup = self.combining_setup()
        self.cube(setup)
        actual = self.combining_search()
        self.cube(actual)
        return setup + actual

    def solve(self):
        """
        Solve the pair.
        """
        cycle = ["FR", "RB", "BL", "LF"]
        combine = self.combine()
        put = Formula(Step("y") * cycle.index(self.pair) or [])
        self.cube(put)
        self.pair = "FR"
        estimated = self.estimated_position()
        for U_act in [Formula(), Formula("U"), Formula("U2"), Formula("U'")]:
            self.cube(U_act)
            for put_act in [Formula("R U R'"), Formula("R U' R'"), Formula("R U2 R'"),
                            Formula("F' U F"), Formula("F' U' F"), Formula("F' U2 F")]:
                self.cube(put_act)
                if self.get_pair() == estimated:
                    return combine + put + U_act + put_act
                self.cube(put_act.reverse())
            self.cube(U_act.reverse())

    def is_solved(self):
        """
        Check if the cube is solved.
        """
        return self.get_pair() == self.estimated_position()

class F2LSolver(object):
    """
    F2LSolver(cube) => An F2L solver.
    """
    def __init__(self, cube):
        self.cube = cube

    def feed(self, cube):
        """
        Feed a cube to the solver.
        """
        self.cube = cube

    def solve(self):
        """
        Solve the entire F2L. (Generator)
        """
        for i in range(4):
            for slot in ["FR", "RB", "BL", "LF"]:
                solver = F2LPairSolver(self.cube, slot)
                if not solver.is_solved():
                    yield tuple([self.cube[slot[i]].colour for i in range(2)]), solver.solve()
                    break

    def is_solved(self):
        """
        Check if Cube's F2L is solved.
        """
        if self.cube.D == [[Square(self.cube["D"].colour)] * 3] * 3:
            for face in "LFRB":
                if self.cube.get_face(face)[1:] != [[Square(self.cube[face].colour)] * 3] * 2:
                    return False
            return True
        return False


text:
"""Testing methods that need no server access."""

import sys
if sys.version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

import json
import mock
import pyhandle
import pyhandle.handlesystemconnector as connector
from pyhandle.handleexceptions import HandleSyntaxError, CredentialsFormatError, GenericHandleError, HandleNotFoundException
from pyhandle.utilhandle import check_handle_syntax, check_handle_syntax_with_index, remove_index_from_handle
from pyhandle.tests.mockresponses import MockResponse, MockSearchResponse
from pyhandle.tests.utilities import replace_timestamps, failure_message

# Load some data that is needed for testing
PATH_CRED = pyhandle.util.get_neighbour_directory(__file__, 'testcredentials')
CRED_FILE = PATH_CRED+'/fake_certs_and_keys/fake_certi_and_bothkeys.pem'
PATH_RES = pyhandle.util.get_neighbour_directory(__file__, 'resources')
RECORD = open(PATH_RES+'/handlerecord_for_reading_PUBLIC.json').read()

class RESTHandleConnectorAccessPatchedTestCase(unittest.TestCase):

    def setUp(self):

        self.inst = connector.HandleSystemConnector(
            certificate_and_key=CRED_FILE,
            handle_server_url='http://foo.com'
        )

    def get_payload_from_mockresponse(self, putpatch):
        # For help, please see: http://www.voidspace.org.uk/python/mock/examples.html#checking-multiple-calls-with-mock
        kwargs_passed_to_put = putpatch.call_args_list[len(putpatch.call_args_list)-1][1]
        passed_payload = None
        try:
            passed_payload = json.loads(kwargs_passed_to_put['data'])
            replace_timestamps(passed_payload)
        except KeyError:
            pass
        return passed_payload

    def get_kw_attribute_from_mockresponse(self, attrname, methodpatch):
        # For help, please see: http://www.voidspace.org.uk/python/mock/examples.html#checking-multiple-calls-with-mock
        kwargs_passed_to_patch = methodpatch.call_args_list[len(methodpatch.call_args_list)-1][1]
        passed_attr = kwargs_passed_to_patch[attrname]
        return passed_attr

    def get_pos_attribute_from_mockresponse(self, pos, methodpatch):
        posargs_passed_to_patch = methodpatch.call_args_list[len(methodpatch.call_args_list)-1][0]
        passed_attr = posargs_passed_to_patch[pos]
        return passed_attr

    @mock.patch('requests.Session.get')
    def test_get_request(self, getpatch):

        # Define the replacement for the patched GET method:
        mock_response_get = MockResponse()
        getpatch.return_value = mock_response_get

        # Test variables
        handle = '123/456'

        # Run code to be tested
        self.inst.send_handle_get_request(handle)

        # Check if the GET request was sent exactly once:
        self.assertEqual(getpatch.call_count, 1,
            'The method "requests.get" was not called once, but '+str(getpatch.call_count)+' times.')

    @mock.patch('requests.Session.put')
    def test_put_request(self, putpatch):

        # Define the replacement for the patched PUT method:
        mock_response_put = MockResponse(wascreated=True)
        putpatch.return_value = mock_response_put

        # Test variables
        handle = '123/456'
        list_of_entries = [{"index":2, "type":"XYZ", "data":"xyz"}]

        # Run code to be tested
        self.inst.send_handle_put_request(handle=handle, list_of_entries=list_of_entries)

        # Check if the PUT request was sent exactly once:
        self.assertEqual(putpatch.call_count, 1,
            'The method "requests.put" was not called once, but '+str(putpatch.call_count)+' times.')

        # Get the payload+headers passed to "requests.put"
        passed_payload = self.get_payload_from_mockresponse(putpatch)

        # Compare with expected payload:
        expected_payload = {"values": list_of_entries}
        self.assertEqual(passed_payload, expected_payload,
            failure_message(expected=expected_payload, passed=passed_payload, methodname='put_request'))

    @mock.patch('requests.Session.delete')
    def test_delete_request_via_cert(self, deletepatch):

        # Define the replacement for the patched DELETE method:
        mock_response_del = MockResponse(success=True)
        deletepatch.return_value = mock_response_del

        # Test variables
        handle = '123/456'

        # Run code to be tested
        self.inst.send_handle_delete_request(handle=handle)

        # Check if the DELETE request was sent exactly once:
        self.assertEqual(deletepatch.call_count, 1,
            'The method "requests.delete" was not called once, but '+str(deletepatch.call_count)+' times.')

        # Get the payload+headers passed to "requests.delete"
        headers = self.get_kw_attribute_from_mockresponse('headers',deletepatch)

        # Compare with expected payload:
        self.assertEquals(headers['Authorization'], 'Handle clientCert="true"',
            'Authorization header not sent correctly: '+headers['Authorization'])

    @mock.patch('requests.Session.delete')
    def test_delete_request_via_cert(self, deletepatch):

        # Define the replacement for the patched DELETE method:
        mock_response_del = MockResponse(success=True)
        deletepatch.return_value = mock_response_del

        # Test variables
        handle = '123/456'
        indices = [1,4,5]

        # Run code to be tested
        self.inst.send_handle_delete_request(handle=handle, indices=indices)

        # Check if the DELETE request was sent exactly once:
        self.assertEqual(deletepatch.call_count, 1,
            'The method "requests.delete" was not called once, but '+str(deletepatch.call_count)+' times.')

        # Get the url passed to "requests.delete"
        url = self.get_pos_attribute_from_mockresponse(0,deletepatch)

        # Compare with expected payload:
        self.assertIn('index=1', url, 'Index 1 missing')
        self.assertIn('index=4', url, 'Index 4 missing')
        self.assertIn('index=5', url, 'Index 5 missing')

    @mock.patch('pyhandle.handlesystemconnector.HandleSystemConnector.check_if_username_exists')
    @mock.patch('requests.Session.delete')
    def test_delete_request_via_basic_auth(self, deletepatch, username_check_patch):

        # Make a new test instance with different authorization:
        inst = connector.HandleSystemConnector(
            username='300:user/name',
            password='mypassword',
            handle_server_url='http://foo.com'
        )

        # Define the replacement for the patched DELETE method:
        mock_response_del = MockResponse(success=True)
        deletepatch.return_value = mock_response_del

        # Define replacement for the patched check for username existence:
        username_check_patch = mock.Mock()
        username_check_patch.response_value = True

        # Test variables
        handle = '123/456'

        # Run code to be tested
        inst.send_handle_delete_request(handle=handle)

        # Check if the DELETE request was sent exactly once:
        self.assertEqual(deletepatch.call_count, 1,
            'The method "requests.delete" was not called once, but '+str(deletepatch.call_count)+' times.')

        # Get the payload+headers passed to "requests.delete"
        headers = self.get_kw_attribute_from_mockresponse('headers',deletepatch)

        # Compare with expected payload:
        self.assertIn('Basic ', headers['Authorization'],
            'Authorization header not sent correctly: '+headers['Authorization'])

    # check if username exists

    @mock.patch('requests.Session.get')
    def test_check_if_username_exists_normal(self, getpatch):
        """Test whether username exists."""

        # Test variables
        handlerecord_string = RECORD
        handlerecord_json = json.loads(handlerecord_string)
        testhandle = '100:'+handlerecord_json['handle']

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        res = self.inst.check_if_username_exists(testhandle)
        self.assertTrue(res,
            'The handle exists, so "check_if_username_exists" should return true!')

    @mock.patch('requests.Session.get')
    def test_check_if_username_exists_inconsistent_info(self, getpatch):
        """Test exception when contradictory inputs are given."""

        # Test variables
        handlerecord_string = RECORD
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(success=True, content=handlerecord_string)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(GenericHandleError):
            self.inst.check_if_username_exists(testhandle)

    @mock.patch('requests.Session.get')
    def test_check_if_username_exists_it_doesnot(self, getpatch):
        """Test exception"""

        # Test variables
        testhandle = 'who/cares'

        # Define the replacement for the patched method:
        mock_response = MockResponse(notfound=True)
        getpatch.return_value = mock_response

        # Call method and check result:
        with self.assertRaises(HandleNotFoundException):
            self.inst.check_if_username_exists(testhandle)


text:
import Mixin from '@ember/object/mixin';
import { A } from '@ember/array';

export default Mixin.create({

  __deserialzieShoeboxDocument(doc) {
    return this._deserializeDocument(doc, 'shoebox');
  },

  _deserializeShoebox(payload) {
    let { documents } = payload;
    return A(documents).map(doc => this.__deserialzieShoeboxDocument(doc));
  },

  __serializeShoeboxDocuments() {
    let all = this._documents.all;
    return all.reduce((arr, internal) => {
      let json = internal.serialize('shoebox');
      if(json) {
        arr.push(json);
      }
      return arr;
    }, A());
  },

  _serializeShoebox() {
    let documents = this.__serializeShoeboxDocuments();
    return {
      documents
    };
  }

});


text:
<?php

namespace ZendTest\Amf\Util;
use Zend\Amf\Util;

/**
 * Test case for Zend_Amf_Util_BinaryStream
 *
 * @category   Zend
 * @package    Zend_Amf
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Amf
 */
class BinaryStreamTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException Zend\Amf\Exception
     */
    public function testConstructorShouldThrowExceptionForInvalidStream()
    {
        $test = new Util\BinaryStream(array('foo', 'bar'));
    }

    /**
     * @expectedException Zend\Amf\Exception
     */
    public function testReadBytesShouldRaiseExceptionForBufferUnderrun()
    {
        $string = 'this is a short stream';
        $stream = new Util\BinaryStream($string);
        $length = strlen($string);
        $test   = $stream->readBytes(10 * $length);
    }

    public function testReadBytesShouldReturnSubsetOfStringFromCurrentNeedle()
    {
        $string = 'this is a short stream';
        $stream = new Util\BinaryStream($string);
        $test   = $stream->readBytes(4);
        $this->assertEquals('this', $test);
        $test   = $stream->readBytes(5);
        $this->assertEquals(' is a', $test);
    }

    public function testBinaryStreamsShouldAllowWritingUtf8()
    {
        $string = str_repeat('赵勇', 1000);
        $stream = new Util\BinaryStream('');
        $stream->writeLongUtf($string);
        $test = $stream->getStream();
        $this->assertContains($string, $test);
    }
}


text:
template<typename T>
inline void DeleteElements(vector<T>& v)
{
	for(vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
		delete *it;
	v.clear();
}

template<typename T>
inline void DeleteElements(vector<T>* v)
{
	DeleteElements(*v);
}

template<typename T, typename Hash, typename Equals>
inline void DeleteElements(std::unordered_set<T, Hash, Equals>& v)
{
	for(auto e : v)
		delete e;
	v.clear();
}

template<typename Key, typename Value>
inline void DeleteElements(std::map<Key, Value>& v)
{
	for(auto& e : v)
		delete e.second;
	v.clear();
}

template<typename Key, typename Value>
inline void DeleteElements(std::unordered_map<Key, Value>& v)
{
	for(auto& e : v)
		delete e.second;
	v.clear();
}

template<typename T>
inline void DeleteElementsChecked(vector<T>& v)
{
	for(T& item : v)
	{
		assert(item);
		delete item;
	}
	v.clear();
}

template<typename T>
inline void DeleteElement(vector<T>& v, T& e)
{
	for(typename vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(e == *it)
		{
			delete *it;
			std::iter_swap(it, end - 1);
			v.pop_back();
			return;
		}
	}
	assert(0 && "Missing element to delete.");
}

template<typename T>
void DeleteElement(vector<T>* v, T& e)
{
	DeleteElement(*v, e);
}

template<typename T>
inline bool DeleteElementTry(vector<T>& v, T& e)
{
	for(typename vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(e == *it)
		{
			delete *it;
			std::iter_swap(it, end - 1);
			v.pop_back();
			return true;
		}
	}

	return false;
}

template<typename T>
inline void RemoveElement(vector<T>& v, const T& e)
{
	for(typename vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(e == *it)
		{
			std::iter_swap(it, end - 1);
			v.pop_back();
			return;
		}
	}
	assert(0 && "Missing element to remove.");
}

template<typename T>
inline void RemoveElement(vector<T>* v, const T& e)
{
	RemoveElement(*v, e);
}

template<typename T>
inline void RemoveElementOrder(vector<T>& v, const T& e)
{
	for(typename vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(e == *it)
		{
			v.erase(it);
			return;
		}
	}
	assert(0 && "Missing element to remove.");
}

template<typename T>
inline void RemoveElementOrder(vector<T>* v, const T& e)
{
	RemoveElementOrder(*v, e);
}

template<typename T>
inline bool RemoveElementTry(vector<T>& v, const T& e)
{
	for(typename vector<T>::iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(e == *it)
		{
			std::iter_swap(it, end - 1);
			v.pop_back();
			return true;
		}
	}
	return false;
}

template<typename T>
inline bool RemoveElementTry(vector<T>* v, const T& e)
{
	return RemoveElementTry(*v, e);
}

template<typename T>
inline void RemoveElementIndex(vector<T>& v, int index)
{
	std::iter_swap(v.begin() + index, v.end() - 1);
	v.pop_back();
}

template<typename T>
inline void RemoveElementIndexOrder(vector<T>& v, int index)
{
	v.erase(v.begin() + index);
}

template<typename T>
inline bool is_null(const T ptr)
{
	return !ptr;
}

template<typename T>
inline void RemoveNullElements(vector<T>& v)
{
	auto it = std::remove_if(v.begin(), v.end(), is_null<T>);
	auto end = v.end();
	if(it != end)
		v.erase(it, end);
}

template<typename T>
inline void RemoveNullElements(vector<T>* v)
{
	assert(v);
	RemoveNullElements(*v);
}

template<typename T, typename T2>
inline void RemoveElements(vector<T>& v, T2 pred)
{
	auto it = std::remove_if(v.begin(), v.end(), pred);
	auto end = v.end();
	if(it != end)
		v.erase(it, end);
}

template<typename T, typename T2>
inline void RemoveElements(vector<T>* v, T2 pred)
{
	assert(v);
	RemoveElements(*v, pred);
}

template<typename T>
inline T& Add1(vector<T>& v)
{
	v.resize(v.size() + 1);
	return v.back();
}

template<typename T>
inline T& Add1(vector<T>* v)
{
	v->resize(v->size() + 1);
	return v->back();
}

template<typename T>
inline T& Add1(list<T>& v)
{
	v.resize(v.size() + 1);
	return v.back();
}

// Returns random item from vector
template<typename T>
T& RandomItem(vector<T>& v)
{
	return v[Rand() % v.size()];
}

template<typename T>
T RandomItemPop(vector<T>& v)
{
	uint index = Rand() % v.size();
	T item = v[index];
	v.erase(v.begin() + index);
	return item;
}

template<class T>
inline T RandomItem(std::initializer_list<T> cont)
{
	int index = Rand() % cont.size();
	auto it = cont.begin();
	std::advance(it, index);
	return *it;
}

template<typename T>
inline bool IsInside(const vector<T>& v, const T& elem)
{
	for(vector<T>::const_iterator it = v.begin(), end = v.end(); it != end; ++it)
	{
		if(*it == elem)
			return true;
	}
	return false;
}

template<typename T>
inline bool IsInside(const vector<T>* v, const T& elem)
{
	return IsInside(*v, elem);
}

//-----------------------------------------------------------------------------
// Object pool pattern
//-----------------------------------------------------------------------------
#if defined(_DEBUG) && !defined(COMMON_ONLY)
#	define CHECK_POOL_LEAKS
#endif
#ifdef CHECK_POOL_LEAKS
struct ObjectPoolLeakManager
{
	struct CallStackEntry;
	~ObjectPoolLeakManager();
	void Register(void* ptr);
	void Unregister(void* ptr);
	static ObjectPoolLeakManager instance;
private:
	vector<CallStackEntry*> call_stack_pool;
	std::unordered_map<void*, CallStackEntry*> call_stacks;
};
#endif

template<typename T>
struct ObjectPool
{
	ObjectPool() : destroyed(false)
	{
	}
	~ObjectPool()
	{
		Cleanup();
		destroyed = true;
	}

	T* Get()
	{
		T* t;
		if(pool.empty())
			t = new T;
		else
		{
			t = pool.back();
			pool.pop_back();
		}
		__if_exists(T::OnGet)
		{
			t->OnGet();
		}
#ifdef CHECK_POOL_LEAKS
		ObjectPoolLeakManager::instance.Register(t);
#endif
		return t;
	}

private:
	void VerifyElement(T* t)
	{
		for(T* e : pool)
			assert(t != e);
	}

	void CheckDuplicates(vector<T*>& elems)
	{
		for(uint i = 0, count = elems.size(); i < count; ++i)
		{
			T* t = elems[i];
			if(!t)
				continue;
			for(uint j = i + 1; j < count; ++j)
				assert(t != elems[j]);
		}
	}

public:
	void Free(T* e)
	{
		assert(e && !destroyed);
#ifdef CHECK_POOL_LEAKS
		VerifyElement(e);
		ObjectPoolLeakManager::instance.Unregister(e);
#endif
		__if_exists(T::OnFree)
		{
			e->OnFree();
		}
		pool.push_back(e);
	}

	void Free(vector<T*>& elems)
	{
		assert(!destroyed);
		if(elems.empty())
			return;

		__if_exists(T::OnFree)
		{
			for(T* e : elems)
			{
				assert(e);
				e->OnFree();
			}
		}

#ifdef CHECK_POOL_LEAKS
		CheckDuplicates(elems);
		for(T* e : elems)
		{
			assert(e);
			VerifyElement(e);
			ObjectPoolLeakManager::instance.Unregister(e);
		}
#endif

		pool.insert(pool.end(), elems.begin(), elems.end());
		elems.clear();
	}

	void SafeFree(T* e)
	{
		if(!destroyed)
			Free(e);
		else
		{
			assert(e);
			__if_exists(T::OnFree)
			{
				e->OnFree();
#ifdef CHECK_POOL_LEAKS
				ObjectPoolLeakManager::instance.Unregister(e);
#endif
			}
			delete e;
		}
	}

	void SafeFree(vector<T*>& elems)
	{
#ifdef CHECK_POOL_LEAKS
		CheckDuplicates(elems);
#endif
		if(!destroyed)
		{
			for(T* e : elems)
			{
				if(e)
				{
#ifdef CHECK_POOL_LEAKS
					VerifyElement(e);
					ObjectPoolLeakManager::instance.Unregister(e);
#endif
					__if_exists(T::OnFree)
					{
						e->OnFree();
					}
					pool.push_back(e);
				}
			}
		}
		else
		{
			for(T* e : elems)
			{
				if(e)
				{
					__if_exists(T::OnFree)
					{
						e->OnFree();
					}
#ifdef CHECK_POOL_LEAKS
					ObjectPoolLeakManager::instance.Unregister(e);
#endif
					delete e;
				}
			}
		}
		elems.clear();
	}

	void Cleanup()
	{
		DeleteElements(pool);
	}

private:
	vector<T*> pool;
	bool destroyed;
};

template<typename T>
class ObjectPoolProxy
{
public:
	static T* Get() { return GetPool().Get(); }
	static void Free(T* t) { GetPool().Free(t); }
	static void Free(vector<T*>& ts) { GetPool().Free(ts); }
	static void SafeFree(T* t) { GetPool().SafeFree(t); }
	static void SafeFree(vector<T*>& ts) { GetPool().SafeFree(ts); }
	static void Cleanup() { GetPool().Cleanup(); }
	void Free() { Free((T*)this); }
	void SafeFree() { SafeFree((T*)this); }

private:
	static ObjectPool<T>& GetPool() { static ObjectPool<T> pool; return pool; }
};

template<typename T>
class Pooled
{
public:
	Pooled() { ptr = ObjectPoolProxy<T>::Get(); }
	Pooled(T* ptr) : ptr(ptr) {}
	~Pooled() { if(ptr) ptr->Free(); }
	T* operator -> () { return ptr; }
	operator T& () { return *ptr; }
	T* Get() { return ptr; }
	T* Pin()
	{
		T* tmp = ptr;
		ptr = nullptr;
		return tmp;
	}

private:
	T* ptr;
};

namespace internal
{
	template<typename T>
	struct ObjectPoolAllocator : IAllocator<T>
	{
		static_assert(std::is_base_of<ObjectPoolProxy<T>, T>::value, "T must inherit from ObjectPoolProxy<T>");

		T* Create()
		{
			return T::Get();
		}

		void Destroy(T* item)
		{
			T::Free(item);
		}
	};

	template<typename T>
	struct ObjectPoolVectorAllocator : IVectorAllocator<T>
	{
		static_assert(std::is_base_of<ObjectPoolProxy<T>, T>::value, "T must inherit from ObjectPoolProxy<T>");

		void Destroy(vector<T*>& items)
		{
			T::Free(items);
		}
	};
}

template<typename T>
using ObjectPoolRef = Ptr<T, internal::ObjectPoolAllocator<T>>;

template<typename T>
using ObjectPoolVectorRef = VectorPtr<T, internal::ObjectPoolVectorAllocator<T>>;

// global pools
extern ObjectPool<string> StringPool;
extern ObjectPool<vector<void*>> VectorPool;

//-----------------------------------------------------------------------------
// Local string using string pool
//-----------------------------------------------------------------------------
struct LocalString
{
	LocalString()
	{
		s = StringPool.Get();
		s->clear();
	}

	LocalString(cstring str)
	{
		assert(str);
		s = StringPool.Get();
		*s = str;
	}

	LocalString(cstring str, cstring str_to)
	{
		s = StringPool.Get();
		uint len = str_to - str;
		s->resize(len);
		memcpy((char*)s->data(), str, len);
	}

	LocalString(const string& str)
	{
		s = StringPool.Get();
		*s = str;
	}

	~LocalString()
	{
		if(s)
			StringPool.Free(s);
	}

	void operator = (cstring str)
	{
		*s = str;
	}

	void operator = (const string& str)
	{
		*s = str;
	}

	char at_back(uint offset) const
	{
		assert(offset < s->size());
		return s->at(s->size() - 1 - offset);
	}

	void pop(uint count)
	{
		assert(s->size() > count);
		s->resize(s->size() - count);
	}

	void operator += (cstring str)
	{
		*s += str;
	}

	void operator += (const string& str)
	{
		*s += str;
	}

	void operator += (char c)
	{
		*s += c;
	}

	operator cstring() const
	{
		return s->c_str();
	}

	string& operator * ()
	{
		return *s;
	}

	string& get_ref()
	{
		return *s;
	}

	string* get_ptr()
	{
		return s;
	}

	string* operator -> ()
	{
		return s;
	}

	const string* operator -> () const
	{
		return s;
	}

	bool operator == (cstring str) const
	{
		return *s == str;
	}

	bool operator == (const string& str) const
	{
		return *s == str;
	}

	bool operator == (const LocalString& str) const
	{
		return *s == *str.s;
	}

	bool operator != (cstring str) const
	{
		return *s != str;
	}

	bool operator != (const string& str) const
	{
		return *s != str;
	}

	bool operator != (const LocalString& str) const
	{
		return *s != *str.s;
	}

	bool empty() const
	{
		return s->empty();
	}

	cstring c_str() const
	{
		return s->c_str();
	}

	void clear()
	{
		s->clear();
	}

	uint length() const
	{
		return s->length();
	}

	string* Pin()
	{
		string* str = s;
		s = nullptr;
		return str;
	}

private:
	string* s;
};

//-----------------------------------------------------------------------------
// Local vector using pool, can only store pointers
//-----------------------------------------------------------------------------
template<typename T>
struct LocalVector
{
	static_assert(sizeof(T) == sizeof(void*), "LocalVector element must be pointer or have sizeof pointer.");

	typedef typename vector<T>::iterator Iterator;
	typedef typename vector<T>::const_iterator ConstIterator;

	LocalVector()
	{
		v = (vector<T>*)VectorPool.Get();
		v->clear();
	}

	explicit LocalVector(vector<T>& v2)
	{
		v = (vector<T>*)VectorPool.Get();
		*v = v2;
	}

	~LocalVector()
	{
		VectorPool.Free((vector<void*>*)v);
	}

	operator vector<T>& ()
	{
		return *v;
	}

	operator vector<T>* ()
	{
		return v;
	}

	vector<T>* operator -> ()
	{
		return v;
	}

	const vector<T>* operator -> () const
	{
		return v;
	}

	T& operator [] (int n)
	{
		return v->at(n);
	}

	void Shuffle()
	{
		std::random_shuffle(v->begin(), v->end(), MyRand);
	}

	Iterator begin()
	{
		return v->begin();
	}
	ConstIterator begin() const
	{
		return v->begin();
	}

	Iterator end()
	{
		return v->end();
	}
	ConstIterator end() const
	{
		return v->end();
	}

private:
	vector<T>* v;
};

template<typename T>
struct LocalVector2
{
	typedef vector<T> Vector;
	typedef Vector* VectorPtr;
	typedef typename Vector::iterator Iter;

	static_assert(sizeof(T) == sizeof(void*), "LocalVector2 element must be pointer or have sizeof pointer.");

	LocalVector2()
	{
		v = (VectorPtr)VectorPool.Get();
		v->clear();
	}

	explicit LocalVector2(Vector& v2)
	{
		v = (VectorPtr*)VectorPool.Get();
		*v = v2;
	}

	~LocalVector2()
	{
		VectorPool.Free((vector<void*>*)v);
	}

	void push_back(T e)
	{
		v->push_back(e);
	}

	bool empty() const
	{
		return v->empty();
	}

	Iter begin()
	{
		return v->begin();
	}

	Iter end()
	{
		return v->end();
	}

	uint size() const
	{
		return v->size();
	}

	T& RandomItem()
	{
		return v->at(Rand() % v->size());
	}

	T& operator [] (int n)
	{
		return v->at(n);
	}

	const T& operator [] (int n) const
	{
		return v->at(n);
	}

	vector<T>& Get()
	{
		return *v;
	}

	void clear()
	{
		v->clear();
	}

private:
	VectorPtr v;
};

template<typename T>
inline T& RandomItem(LocalVector2<T>& v)
{
	return v.RandomItem();
}

//-----------------------------------------------------------------------------
template<typename T>
struct rvector
{

	struct iter
	{
		typedef typename vector<T*>::iterator InnerIt;

		bool operator != (const iter& it2)
		{
			return it != it2.it;
		}
		iter& operator ++ ()
		{
			++it;
			return *this;
		}
		T& operator * ()
		{
			return **it;
		}

		InnerIt it;
	};

	T& operator [](uint index) { return *ptrs[index]; }

	iter begin() { return iter{ ptrs.begin() }; }
	iter end() { return iter{ ptrs.end() }; }
	uint size() const { return ptrs.size(); }
	void push_back(T* ptr)
	{
		assert(ptr);
		ptrs.push_back(ptr);
	}
	void erase(int index) { ptrs.erase(ptrs.begin() + index); }
	void erase(iter it) { ptrs.erase(it.it); }
	void erase(iter start, iter end) { ptrs.erase(start.it, end.it); }
	void clear() { ptrs.clear(); }
	T& front() { return *ptrs.front(); }

	vector<T*> ptrs;
};

template<typename T>
void DeleteElements(rvector<T>& v)
{
	DeleteElements(v.ptrs);
}

//-----------------------------------------------------------------------------
// Loop over items and erase elements that returned true
template<typename T, typename Action>
inline void LoopAndRemove(vector<T>& items, Action action)
{
	items.erase(std::remove_if(items.begin(), items.end(), action), items.end());
}
template<typename T, typename Action>
inline void LoopAndRemove(rvector<T>& items, Action action)
{
	items.erase(std::remove_if(items.begin(), items.end(), action), items.end());
}
template<typename Key, typename Value, typename Action>
inline void LoopAndRemove(std::map<Key, Value>& items, Action action)
{
	for(auto it = items.begin(), end = items.end(); it != end;)
	{
		if(action(it->second))
		{
			it = items.erase(it);
			end = items.end();
		}
		else
			++it;
	}
}

//-----------------------------------------------------------------------------
// Return random weighted item
template<typename T>
struct WeightPair
{
	T item;
	int weight;

	WeightPair(T& item, int weight) : item(item), weight(weight) {}
};

template<typename T>
inline T& RandomItemWeight(vector<WeightPair<T>>& items, int max_weight)
{
	if(items.size() == (uint)max_weight)
		return RandomItem(items).item;
	int a = Rand() % max_weight, b = 0;
	for(auto& item : items)
	{
		b += item.weight;
		if(a < b)
			return item.item;
	}
	// if it gets here max_count is wrong, return random item
	return RandomItem(items).item;
}

//-----------------------------------------------------------------------------
// Like LocalVector but can store any data
extern ObjectPool<vector<byte>> BufPool;

template<typename T>
class LocalVector3
{
public:
	struct iterator : std::iterator<std::input_iterator_tag, T>
	{
		friend class LocalVector3;

		T& operator * ()
		{
			return v->at(offset);
		}

		bool operator == (const iterator& it) const
		{
			assert(it.v == v);
			return offset == it.offset;
		}

		bool operator != (const iterator& it) const
		{
			assert(it.v == v);
			return offset != it.offset;
		}

		bool operator < (const iterator& it) const
		{
			assert(it.v == v);
			return offset < it.offset;
		}

		iterator& operator ++ ()
		{
			++offset;
			return *this;
		}

		iterator operator ++ (int)
		{
			iterator it(v, offset);
			++offset;
			return it;
		}

		iterator& operator -- ()
		{
			--offset;
			return *this;
		}

		iterator& operator + (uint count)
		{
			offset += count;
			return *this;
		}

		iterator& operator - (uint count)
		{
			offset -= count;
			return *this;
		}

		int operator - (const iterator& it) const
		{
			assert(it.v == v);
			return offset - it.offset;
		}

	private:
		iterator(LocalVector3* v, uint offset) : v(v), offset(offset) {}

		LocalVector3* v;
		uint offset;
	};

	LocalVector3()
	{
		buf = BufPool.Get();
	}

	~LocalVector3()
	{
		buf->clear();
		BufPool.Free(buf);
	}

	T& at(uint offset)
	{
		assert(offset < size());
		return ((T*)buf->data())[offset];
	}

	T& back()
	{
		assert(!empty());
		return ((T*)buf->data())[size() - 1];
	}

	iterator begin()
	{
		return iterator(this, 0);
	}

	bool empty() const
	{
		return buf->empty();
	}

	iterator end()
	{
		return iterator(this, size());
	}

	void push_back(T& item)
	{
		uint s = buf->size();
		buf->resize(buf->size() + sizeof(T));
		memcpy(buf->data() + s, &item, sizeof(T));
	}

	uint size() const
	{
		return buf->size() / sizeof(T);
	}

	template<typename Pred>
	void sort(Pred pred)
	{
		std::sort((T*)buf->data(), (T*)(buf->data() + buf->size()), pred);
	}

private:
	vector<byte>* buf;
};

//-----------------------------------------------------------------------------
// Find index of item
template<typename T>
inline int GetIndex(const vector<T>& items, const T& item)
{
	int index = 0;
	for(const T& it : items)
	{
		if(it == item)
			return index;
		++index;
	}
	return -1;
}

template<typename T, typename Pred>
inline int GetIndex(const vector<T>& items, Pred pred)
{
	int index = 0;
	for(const T& it : items)
	{
		if(pred(it))
			return index;
		++index;
	}
	return -1;
}

//-----------------------------------------------------------------------------
// Vector using critical section protection
template<typename T>
class SafeVector
{
public:
	SafeVector()
	{
		cs.Create();
	}

	~SafeVector()
	{
		cs.Free();
	}

	inline void Push(T& e)
	{
		StartCriticalSection section(cs);
		v.push_back(e);
	}

	inline T Pop()
	{
		StartCriticalSection section(cs);
		T e = v.back();
		v.pop_back();
		return e;
	}

	inline bool Any()
	{
		return !v.empty();
	}

private:
	vector<T> v;
	CriticalSection cs;
};

namespace helper
{
	template<typename T>
	struct DerefEnumerator
	{
		struct Iterator
		{
			typedef typename vector<T*>::iterator It;

			Iterator(It it) : it(it)
			{
			}

			bool operator != (const Iterator& i) const
			{
				return it != i.it;
			}

			void operator ++ ()
			{
				++it;
			}

			T& operator * ()
			{
				return **it;
			}

			It it;
		};

		DerefEnumerator(vector<T*>& v) : v(v)
		{
		}

		Iterator begin()
		{
			return Iterator(v.begin());
		}

		Iterator end()
		{
			return Iterator(v.end());
		}

		vector<T*>& v;
	};
}

template<typename T>
helper::DerefEnumerator<T> Deref(vector<T*>& v)
{
	return helper::DerefEnumerator<T>(v);
}

//-----------------------------------------------------------------------------
namespace internal
{
	template<typename T>
	struct Hash
	{
		size_t operator () (const T* obj) const
		{
			std::hash<string> hasher;
			return hasher(obj->id);
		}
	};

	template<typename T>
	struct Equals
	{
		bool operator () (const T* obj1, const T* obj2) const
		{
			return obj1->id == obj2->id;
		}
	};
}

template<typename T>
using SetContainer = std::unordered_set<T*, internal::Hash<T>, internal::Equals<T>>;

//-----------------------------------------------------------------------------
template<typename T>
struct PointerVector
{
	typedef typename vector<T*> Vector;
	typedef typename vector<T*>::iterator Iter;
	typedef typename vector<T*>::const_iterator ConstIter;

	struct Iterator
	{
		Iter it;

		Iterator(Iter it) : it(it) {}
		bool operator != (const Iterator& i)
		{
			return it != i.it;
		}
		void operator ++ ()
		{
			++it;
		}
		T& operator * ()
		{
			return **it;
		}
		T* operator -> ()
		{
			return *it;
		}
		Iterator operator + (int offset) const
		{
			return Iterator(it + offset);
		}
		Iterator operator - (int offset) const
		{
			return Iterator(it - offset);
		}
		T* ptr()
		{
			return *it;
		}
	};

	struct ConstIterator
	{
		ConstIter it;

		ConstIterator(ConstIter it) : it(it) {}
		bool operator != (const ConstIterator& i)
		{
			return it != i.it;
		}
		void operator ++ ()
		{
			++it;
		}
		const T& operator * ()
		{
			return **it;
		}
		const T* operator -> () const
		{
			return *it;
		}
		ConstIterator operator + (int offset) const
		{
			return Iterator(it + offset);
		}
		ConstIterator operator - (int offset) const
		{
			return Iterator(it  offset);
		}
		const T* ptr() const
		{
			return *it;
		}
	};

	Iterator begin()
	{
		return Iterator(v.begin());
	}
	ConstIterator begin() const
	{
		return ConstIterator(v.begin());
	}
	Iterator end()
	{
		return Iterator(v.end());
	}
	ConstIterator end() const
	{
		return ConstIterator(v.end());
	}

	bool empty() const
	{
		return v.empty();
	}
	uint size() const
	{
		return v.size();
	}
	T& operator [] (uint index)
	{
		return *v[index];
	}
	T* ptr(uint index)
	{
		return v[index];
	}
	void reserve(uint size)
	{
		v.reserve(size);
	}
	void resize(uint size)
	{
		v.resize(size);
	}
	void push_back(T* e)
	{
		v.push_back(e);
	}
	Iterator erase(Iterator it)
	{
		return Iterator(v.erase(it.it));
	}
	ConstIterator erase(ConstIterator it) const
	{
		return ConstIterator(v.erase(it.it));
	}
	void pop_back()
	{
		v.pop_back();
	}
	void clear()
	{
		v.clear();
	}

	Vector v;
};

//-----------------------------------------------------------------------------
// Buffer - used by MemoryStream
class Buffer : public ObjectPoolProxy<Buffer>
{
public:
	void* At(uint offset)
	{
		return data.data() + offset;
	}
	void* Data()
	{
		return data.data();
	}
	// decompress buffer to new buffer and return it, old one is freed
#ifndef COMMON_ONLY
	Buffer* Decompress(uint real_size);
#endif
	void Resize(uint size)
	{
		data.resize(size);
	}
	uint Size() const
	{
		return data.size();
	}

private:
	vector<byte> data;
};

//-----------------------------------------------------------------------------
struct BufferHandle
{
	BufferHandle(Buffer* buf) : buf(buf) {}
	~BufferHandle()
	{
		if(buf)
			buf->Free();
	}

	operator bool() const
	{
		return buf != nullptr;
	}

	Buffer* operator -> ()
	{
		return buf;
	}

	Buffer* Pin()
	{
		Buffer* b = buf;
		buf = nullptr;
		return b;
	}

private:
	Buffer* buf;
};

//-----------------------------------------------------------------------------
template<typename T>
struct RemoveRandomPred
{
	int chance, a, b;

	RemoveRandomPred(int chance, int a, int b)
	{
	}

	bool operator () (const T&)
	{
		return Random(a, b) < chance;
	}
};


text:
/*
 *   6.   Write a function that groups an array of persons by age,
 *        first or last name. The function must return an associative array,
 *        with keys - the groups, and values -arrays with persons in this groups
 *        Use function overloading (i.e. just one function)
 */
function group(persons, property) {
    var propValues = {},
        result = {},
        i = 0,
        length = persons.length,
        prop;

    // colect all values
    for (i = 0; i < length; i += 1) {
        if (!propValues[persons[i][property]]) {
            propValues[persons[i][property]] = undefined;
        }
    }

    for (prop in propValues) {
        result[prop] = [];

        for (i = 0; i < length; i += 1) {
            if (persons[i][property].toString() === prop) {
                result[prop].push(persons[i]);
            }
        }
    }

    return result;
}

function person(fName, lName, age) {
    return {
        fName: fName,
        lName: lName,
        age: age,
        toString: function () {
            return this.fName + ' ' + this.lName + ' ' + this.age;
        }
    };
}

function printGroup(groupToPrint) {
    var i;

    for (i in groupToPrint) {
        jsConsole.writeLine('groupe: ' + i);
        jsConsole.writeLine(groupToPrint[i].join('<br />'));
        jsConsole.writeLine('');
    }
}

var persons = [
    person('Gosho', 'Geshev', 21),
    person('Pesho', 'Petrov', 19),
    person('Stamat', 'Iliev', 28),
    person('Mimi', 'Mileva', 19),
    person('Gosho', 'Toshev', 28),
    person('Gosho', 'Angelov', 33),
    person('Mimi', 'Petrova', 28),
    person('Nikoleta', 'Emilova', 19)
];

var groupedByFname = group(persons, 'fName');
var groupedByAge = group(persons, 'age');

jsConsole.writeLine('persons grouped by fName:');
printGroup(groupedByFname);

jsConsole.writeLine('***********************************');
jsConsole.writeLine('persons grouped by age:');
printGroup(groupedByAge);