text:
package com.huassit.imenu.android.biz;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;

import com.huassit.imenu.android.http.BaseInvoker;
import com.huassit.imenu.android.model.API;
import com.huassit.imenu.android.model.Cart;
import com.huassit.imenu.android.parser.BaseParser;
import com.huassit.imenu.android.parser.CartParser;

public class GetCartResp extends BaseInvoker{

	private String token;
	private String memberId;
	private CartParser cartParser;

	public GetCartResp(Context ctx, Handler handler,String token,String memberId) {
		super(ctx, handler);
		this.token =token;
		this.memberId =memberId;
		cartParser =new CartParser();
	}

	@Override
	public List<NameValuePair> getParameters() {
		List<NameValuePair> nvp =new ArrayList<NameValuePair>();
		nvp.add(new BasicNameValuePair("route", API.GET_CART));
		nvp.add(new BasicNameValuePair("token", token));
		nvp.add(new BasicNameValuePair("jsonText", makeJsonText()));
		return nvp;
	}

	private String makeJsonText() {
		JSONObject json =new JSONObject();
		try {
			json.put("member_id", memberId);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return json.toString();
	}

	@Override
	public String getRequestUrl() {
		return API.server;
	}

	@Override
	public HTTP_METHOD getRequestMethod() {
		return HTTP_METHOD.METHOD_POST;
	}

	@Override
	protected void handleResponse(String response) {
		try {
			Cart cart =cartParser.doParse(response);
			if(cartParser.getResponseCode()==BaseParser.SUCCESS && cart!=null){
				sendMessage(ON_SUCCESS, cart);
			}else{
				sendMessage(ON_FAILURE, null);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: zein
 * Date: 7/3/14
 * Time: 3:24 PM
 */

namespace common\assets;

use yii\web\AssetBundle;

class FontAwesome extends AssetBundle
{
    public $sourcePath = '@bower/fontawesome';
    public $css = [
        'css/font-awesome.min.css'
    ];
}

redpajama_set_name: RedPajamaGithub


text:
package io.cattle.platform.agent.instance.service.impl;

import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.ServiceExposeMap;
import io.cattle.platform.object.ObjectManager;
import static io.cattle.platform.core.model.tables.NicTable.*;

import java.util.List;

import javax.inject.Inject;

/*
 * Triggers selector containers use case. When container joins service, serviceExposeMap gets created
 */
public class ServiceExposeMapCreateNicLookup extends NicPerVnetNicLookup implements InstanceNicLookup {

    @Inject
    ObjectManager objectManager;

    @Override
    public List<? extends Nic> getNics(Object obj) {
        if (!(obj instanceof ServiceExposeMap)) {
            return null;
        }

        ServiceExposeMap map = (ServiceExposeMap) obj;
        return create().selectFrom(NIC)
                .where(NIC.INSTANCE_ID.eq(map.getInstanceId())
                        .and(NIC.REMOVED.isNull()))
                .fetch();
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 32: 25 (1949)

#### Original name
Dasyscyphus apalus var. apalus (Berk. & Broome) Dennis

### Remarks
null


text:
Simple gem that parses the [HTTP prefer header](http://tools.ietf.org/html/rfc7240).

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'rack-prefer'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rack-prefer

## Usage

```ruby
# rack app (sinatra, lotus, grape etc)
require 'rack/prefer'
```

Rails automatically includes the `rack/prefer` file.

Once you have access to Rack::Request object (Rails ActionDispatch::Request object
inherits from Rack's Rack::Request) you also have access to Prefer header. So for
a request like the following prefer headers:

```http
Prefer: respond-async, wait=10
Prefer: priority=5
Prefer: handling=strict
```

you can do:
```ruby
request.prefer.values #{"respond-async"=>nil, "wait"=>"10", "priority"=>"5"}
request.prefer.response_async? #true
request.prefer.return_minimal? #false
request.prefer.wait? #true
request.prefer.wait # 10 (integer)
request.prefer.handling_strict? #true
request.prefer.values['handling'] #'strict'
#Rails only
request.prefer.values[:handling] #strict
```

Happy coding!

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/rack-prefer/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
static MSActiveControllerFinder *finder = nil;

@implementation MSActiveControllerFinder

+ (void)setFinder:(id<MSActiveControllerFinder>)aFinder {
    finder = aFinder;
}

+ (instancetype)finder {
    if (finder) {
        return finder;
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        finder = [[self alloc] init];
    });
    return finder;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setUpDefaultRootTabBarController];
        [self setUpDefaultActiveTabBarController];
        [self setUpDefaultActiveNavigationController];
        [self setUpDefaultActiveTopViewController];
        [self setUpDefaultResetStatus];
    }
    return self;
}

- (void)setUpDefaultRootTabBarController {
    __weak __typeof(self)weakSelf = self;
    self.activeTabBarController = ^ UITabBarController * {
        return [weakSelf defaultActiveTabBarController];
    };
}

- (void)setUpDefaultActiveTabBarController {
    __weak __typeof(self)weakSelf = self;
    self.activeTabBarController = ^ UITabBarController * {
        return [weakSelf defaultActiveTabBarController];
    };
}

- (void)setUpDefaultActiveNavigationController {
    __weak __typeof(self)weakSelf = self;
    self.activeNavigationController = ^ UINavigationController *{
        return [weakSelf defaultActiveNavigationController];
    };
}

- (void)setUpDefaultActiveTopViewController {
    __weak __typeof(self)weakSelf = self;
    self.activeTopController = ^UIViewController * {
        return [weakSelf defaultActiveTopController];
    };
}

- (void)setUpDefaultResetStatus {
    self.resetStatus = ^{
    };
 }

- (UITabBarController *)defaultActiveTabBarController {
    UITabBarController *tabBarController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if ([tabBarController isKindOfClass:[UITabBarController class]]) {
        return tabBarController;
    }
    return nil;
}

- (UINavigationController *)defaultActiveNavigationController {
    UITabBarController *tabBarController = [self defaultActiveTabBarController];
    if ([tabBarController isKindOfClass:[UITabBarController class]]) {
        UINavigationController *navigationController = [tabBarController selectedViewController];
        if ([navigationController isKindOfClass:[UINavigationController class]]) {
            return navigationController;
        }
        return nil;
    }

    UITabBarController *navigationController = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    if ([navigationController isKindOfClass:[UINavigationController class]]) {
        return navigationController;
    }

    return nil;
}

- (UIViewController *)defaultActiveTopController {
    return [[self defaultActiveNavigationController] topViewController];
}

@end


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * Namespace for utility functions.
 */
var util = {};

/**
 * Returns a function that console.log's its arguments, prefixed by |msg|.
 *
 * @param {string} msg The message prefix to use in the log.
 * @param {function(...string)=} opt_callback A function to invoke after
 *     logging.
 * @return {function(...string)} Function that logs.
 */
util.flog = function(msg, opt_callback) {
  return function() {
    var ary = Array.apply(null, arguments);
    console.log(msg + ': ' + ary.join(', '));
    if (opt_callback)
      opt_callback.apply(null, arguments);
  };
};

/**
 * Returns a function that throws an exception that includes its arguments
 * prefixed by |msg|.
 *
 * @param {string} msg The message prefix to use in the exception.
 * @return {function(...string)} Function that throws.
 */
util.ferr = function(msg) {
  return function() {
    var ary = Array.apply(null, arguments);
    throw new Error(msg + ': ' + ary.join(', '));
  };
};

/**
 * @param {string} name File error name.
 * @return {string} Translated file error string.
 */
util.getFileErrorString = function(name) {
  var candidateMessageFragment;
  switch (name) {
    case 'NotFoundError':
      candidateMessageFragment = 'NOT_FOUND';
      break;
    case 'SecurityError':
      candidateMessageFragment = 'SECURITY';
      break;
    case 'NotReadableError':
      candidateMessageFragment = 'NOT_READABLE';
      break;
    case 'NoModificationAllowedError':
      candidateMessageFragment = 'NO_MODIFICATION_ALLOWED';
      break;
    case 'InvalidStateError':
      candidateMessageFragment = 'INVALID_STATE';
      break;
    case 'InvalidModificationError':
      candidateMessageFragment = 'INVALID_MODIFICATION';
      break;
    case 'PathExistsError':
      candidateMessageFragment = 'PATH_EXISTS';
      break;
    case 'QuotaExceededError':
      candidateMessageFragment = 'QUOTA_EXCEEDED';
      break;
  }

  return loadTimeData.getString('FILE_ERROR_' + candidateMessageFragment) ||
      loadTimeData.getString('FILE_ERROR_GENERIC');
};

/**
 * Mapping table for FileError.code style enum to DOMError.name string.
 *
 * @enum {string}
 * @const
 */
util.FileError = Object.freeze({
  ABORT_ERR: 'AbortError',
  INVALID_MODIFICATION_ERR: 'InvalidModificationError',
  INVALID_STATE_ERR: 'InvalidStateError',
  NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
  NOT_FOUND_ERR: 'NotFoundError',
  NOT_READABLE_ERR: 'NotReadable',
  PATH_EXISTS_ERR: 'PathExistsError',
  QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
  TYPE_MISMATCH_ERR: 'TypeMismatchError',
  ENCODING_ERR: 'EncodingError',
});

/**
 * @param {string} str String to escape.
 * @return {string} Escaped string.
 */
util.htmlEscape = function(str) {
  return str.replace(/[<>&]/g, function(entity) {
    switch (entity) {
      case '<': return '<';
      case '>': return '>';
      case '&': return '&';
    }
  });
};

/**
 * @param {string} str String to unescape.
 * @return {string} Unescaped string.
 */
util.htmlUnescape = function(str) {
  return str.replace(/&(lt|gt|amp);/g, function(entity) {
    switch (entity) {
      case '<': return '<';
      case '>': return '>';
      case '&': return '&';
    }
  });
};

/**
 * Iterates the entries contained by dirEntry, and invokes callback once for
 * each entry. On completion, successCallback will be invoked.
 *
 * @param {DirectoryEntry} dirEntry The entry of the directory.
 * @param {function(Entry, function())} callback Invoked for each entry.
 * @param {function()} successCallback Invoked on completion.
 * @param {function(FileError)} errorCallback Invoked if an error is found on
 *     directory entry reading.
 */
util.forEachDirEntry = function(
    dirEntry, callback, successCallback, errorCallback) {
  var reader = dirEntry.createReader();
  var iterate = function() {
    reader.readEntries(function(entries) {
      if (entries.length == 0) {
        successCallback();
        return;
      }

      AsyncUtil.forEach(
          entries,
          function(forEachCallback, entry) {
            // Do not pass index nor entries.
            callback(entry, forEachCallback);
          },
          iterate);
    }, errorCallback);
  };
  iterate();
};

/**
 * Reads contents of directory.
 * @param {DirectoryEntry} root Root entry.
 * @param {string} path Directory path.
 * @param {function(Array.<Entry>)} callback List of entries passed to callback.
 */
util.readDirectory = function(root, path, callback) {
  var onError = function(e) {
    callback([], e);
  };
  root.getDirectory(path, {create: false}, function(entry) {
    var reader = entry.createReader();
    var r = [];
    var readNext = function() {
      reader.readEntries(function(results) {
        if (results.length == 0) {
          callback(r, null);
          return;
        }
        r.push.apply(r, results);
        readNext();
      }, onError);
    };
    readNext();
  }, onError);
};

/**
 * Utility function to resolve multiple directories with a single call.
 *
 * The successCallback will be invoked once for each directory object
 * found.  The errorCallback will be invoked once for each
 * path that could not be resolved.
 *
 * The successCallback is invoked with a null entry when all paths have
 * been processed.
 *
 * @param {DirEntry} dirEntry The base directory.
 * @param {Object} params The parameters to pass to the underlying
 *     getDirectory calls.
 * @param {Array.<string>} paths The list of directories to resolve.
 * @param {function(!DirEntry)} successCallback The function to invoke for
 *     each DirEntry found.  Also invoked once with null at the end of the
 *     process.
 * @param {function(FileError)} errorCallback The function to invoke
 *     for each path that cannot be resolved.
 */
util.getDirectories = function(dirEntry, params, paths, successCallback,
                               errorCallback) {

  // Copy the params array, since we're going to destroy it.
  params = [].slice.call(params);

  var onComplete = function() {
    successCallback(null);
  };

  var getNextDirectory = function() {
    var path = paths.shift();
    if (!path)
      return onComplete();

    dirEntry.getDirectory(
        path, params,
        function(entry) {
          successCallback(entry);
          getNextDirectory();
        },
        function(err) {
          errorCallback(err);
          getNextDirectory();
        });
  };

  getNextDirectory();
};

/**
 * Utility function to resolve multiple files with a single call.
 *
 * The successCallback will be invoked once for each directory object
 * found.  The errorCallback will be invoked once for each
 * path that could not be resolved.
 *
 * The successCallback is invoked with a null entry when all paths have
 * been processed.
 *
 * @param {DirEntry} dirEntry The base directory.
 * @param {Object} params The parameters to pass to the underlying
 *     getFile calls.
 * @param {Array.<string>} paths The list of files to resolve.
 * @param {function(!FileEntry)} successCallback The function to invoke for
 *     each FileEntry found.  Also invoked once with null at the end of the
 *     process.
 * @param {function(FileError)} errorCallback The function to invoke
 *     for each path that cannot be resolved.
 */
util.getFiles = function(dirEntry, params, paths, successCallback,
                         errorCallback) {
  // Copy the params array, since we're going to destroy it.
  params = [].slice.call(params);

  var onComplete = function() {
    successCallback(null);
  };

  var getNextFile = function() {
    var path = paths.shift();
    if (!path)
      return onComplete();

    dirEntry.getFile(
        path, params,
        function(entry) {
          successCallback(entry);
          getNextFile();
        },
        function(err) {
          errorCallback(err);
          getNextFile();
        });
  };

  getNextFile();
};

/**
 * Renames the entry to newName.
 * @param {Entry} entry The entry to be renamed.
 * @param {string} newName The new name.
 * @param {function(Entry)} successCallback Callback invoked when the rename
 *     is successfully done.
 * @param {function(FileError)} errorCallback Callback invoked when an error
 *     is found.
 */
util.rename = function(entry, newName, successCallback, errorCallback) {
  entry.getParent(function(parent) {
    // Before moving, we need to check if there is an existing entry at
    // parent/newName, since moveTo will overwrite it.
    // Note that this way has some timing issue. After existing check,
    // a new entry may be create on background. However, there is no way not to
    // overwrite the existing file, unfortunately. The risk should be low,
    // assuming the unsafe period is very short.
    (entry.isFile ? parent.getFile : parent.getDirectory).call(
        parent, newName, {create: false},
        function(entry) {
          // The entry with the name already exists.
          errorCallback(util.createDOMError(util.FileError.PATH_EXISTS_ERR));
        },
        function(error) {
          if (error.name != util.FileError.NOT_FOUND_ERR) {
            // Unexpected error is found.
            errorCallback(error);
            return;
          }

          // No existing entry is found.
          entry.moveTo(parent, newName, successCallback, errorCallback);
        });
  }, errorCallback);
};

/**
 * Remove a file or a directory.
 * @param {Entry} entry The entry to remove.
 * @param {function()} onSuccess The success callback.
 * @param {function(FileError)} onError The error callback.
 */
util.removeFileOrDirectory = function(entry, onSuccess, onError) {
  if (entry.isDirectory)
    entry.removeRecursively(onSuccess, onError);
  else
    entry.remove(onSuccess, onError);
};

/**
 * Convert a number of bytes into a human friendly format, using the correct
 * number separators.
 *
 * @param {number} bytes The number of bytes.
 * @return {string} Localized string.
 */
util.bytesToString = function(bytes) {
  // Translation identifiers for size units.
  var UNITS = ['SIZE_BYTES',
               'SIZE_KB',
               'SIZE_MB',
               'SIZE_GB',
               'SIZE_TB',
               'SIZE_PB'];

  // Minimum values for the units above.
  var STEPS = [0,
               Math.pow(2, 10),
               Math.pow(2, 20),
               Math.pow(2, 30),
               Math.pow(2, 40),
               Math.pow(2, 50)];

  var str = function(n, u) {
    return strf(u, n.toLocaleString());
  };

  var fmt = function(s, u) {
    var rounded = Math.round(bytes / s * 10) / 10;
    return str(rounded, u);
  };

  // Less than 1KB is displayed like '80 bytes'.
  if (bytes < STEPS[1]) {
    return str(bytes, UNITS[0]);
  }

  // Up to 1MB is displayed as rounded up number of KBs.
  if (bytes < STEPS[2]) {
    var rounded = Math.ceil(bytes / STEPS[1]);
    return str(rounded, UNITS[1]);
  }

  // This loop index is used outside the loop if it turns out |bytes|
  // requires the largest unit.
  var i;

  for (i = 2 /* MB */; i < UNITS.length - 1; i++) {
    if (bytes < STEPS[i + 1])
      return fmt(STEPS[i], UNITS[i]);
  }

  return fmt(STEPS[i], UNITS[i]);
};

/**
 * Utility function to read specified range of bytes from file
 * @param {File} file The file to read.
 * @param {number} begin Starting byte(included).
 * @param {number} end Last byte(excluded).
 * @param {function(File, Uint8Array)} callback Callback to invoke.
 * @param {function(FileError)} onError Error handler.
 */
util.readFileBytes = function(file, begin, end, callback, onError) {
  var fileReader = new FileReader();
  fileReader.onerror = onError;
  fileReader.onloadend = function() {
    callback(file, new ByteReader(fileReader.result));
  };
  fileReader.readAsArrayBuffer(file.slice(begin, end));
};

/**
 * Write a blob to a file.
 * Truncates the file first, so the previous content is fully overwritten.
 * @param {FileEntry} entry File entry.
 * @param {Blob} blob The blob to write.
 * @param {function(Event)} onSuccess Completion callback. The first argument is
 *     a 'writeend' event.
 * @param {function(FileError)} onError Error handler.
 */
util.writeBlobToFile = function(entry, blob, onSuccess, onError) {
  var truncate = function(writer) {
    writer.onerror = onError;
    writer.onwriteend = write.bind(null, writer);
    writer.truncate(0);
  };

  var write = function(writer) {
    writer.onwriteend = onSuccess;
    writer.write(blob);
  };

  entry.createWriter(truncate, onError);
};

/**
 * Returns a string '[Ctrl-][Alt-][Shift-][Meta-]' depending on the event
 * modifiers. Convenient for writing out conditions in keyboard handlers.
 *
 * @param {Event} event The keyboard event.
 * @return {string} Modifiers.
 */
util.getKeyModifiers = function(event) {
  return (event.ctrlKey ? 'Ctrl-' : '') +
         (event.altKey ? 'Alt-' : '') +
         (event.shiftKey ? 'Shift-' : '') +
         (event.metaKey ? 'Meta-' : '');
};

/**
 * @param {HTMLElement} element Element to transform.
 * @param {Object} transform Transform object,
 *                           contains scaleX, scaleY and rotate90 properties.
 */
util.applyTransform = function(element, transform) {
  element.style.webkitTransform =
      transform ? 'scaleX(' + transform.scaleX + ') ' +
                  'scaleY(' + transform.scaleY + ') ' +
                  'rotate(' + transform.rotate90 * 90 + 'deg)' :
      '';
};

/**
 * Extracts path from filesystem: URL.
 * @param {string} url Filesystem URL.
 * @return {string} The path.
 */
util.extractFilePath = function(url) {
  var match =
      /^filesystem:[\w-]*:\/\/[\w]*\/(external|persistent|temporary)(\/.*)$/.
      exec(url);
  var path = match && match[2];
  if (!path) return null;
  return decodeURIComponent(path);
};

/**
 * Traverses a directory tree whose root is the given entry, and invokes
 * callback for each entry. Upon completion, successCallback will be called.
 * On error, errorCallback will be called.
 *
 * @param {Entry} entry The root entry.
 * @param {function(Entry):boolean} callback Callback invoked for each entry.
 *     If this returns false, entries under it won't be traversed. Note that
 *     its siblings (and their children) will be still traversed.
 * @param {function()} successCallback Called upon successful completion.
 * @param {function(error)} errorCallback Called upon error.
 */
util.traverseTree = function(entry, callback, successCallback, errorCallback) {
  if (!callback(entry)) {
    successCallback();
    return;
  }

  util.forEachDirEntry(
      entry,
      function(child, iterationCallback) {
        util.traverseTree(child, callback, iterationCallback, errorCallback);
      },
      successCallback,
      errorCallback);
};

/**
 * A shortcut function to create a child element with given tag and class.
 *
 * @param {HTMLElement} parent Parent element.
 * @param {string=} opt_className Class name.
 * @param {string=} opt_tag Element tag, DIV is omitted.
 * @return {Element} Newly created element.
 */
util.createChild = function(parent, opt_className, opt_tag) {
  var child = parent.ownerDocument.createElement(opt_tag || 'div');
  if (opt_className)
    child.className = opt_className;
  parent.appendChild(child);
  return child;
};

/**
 * Updates the app state.
 *
 * @param {string} currentDirectoryURL Currently opened directory as an URL.
 *     If null the value is left unchanged.
 * @param {string} selectionURL Currently selected entry as an URL. If null the
 *     value is left unchanged.
 * @param {string|Object=} opt_param Additional parameters, to be stored. If
 *     null, then left unchanged.
 */
util.updateAppState = function(currentDirectoryURL, selectionURL, opt_param) {
  window.appState = window.appState || {};
  if (opt_param !== undefined && opt_param !== null)
    window.appState.params = opt_param;
  if (currentDirectoryURL !== null)
    window.appState.currentDirectoryURL = currentDirectoryURL;
  if (selectionURL !== null)
    window.appState.selectionURL = selectionURL;
  util.saveAppState();
};

/**
 * Returns a translated string.
 *
 * Wrapper function to make dealing with translated strings more concise.
 * Equivalent to loadTimeData.getString(id).
 *
 * @param {string} id The id of the string to return.
 * @return {string} The translated string.
 */
function str(id) {
  return loadTimeData.getString(id);
}

/**
 * Returns a translated string with arguments replaced.
 *
 * Wrapper function to make dealing with translated strings more concise.
 * Equivalent to loadTimeData.getStringF(id, ...).
 *
 * @param {string} id The id of the string to return.
 * @param {...string} var_args The values to replace into the string.
 * @return {string} The translated string with replaced values.
 */
function strf(id, var_args) {
  return loadTimeData.getStringF.apply(loadTimeData, arguments);
}

/**
 * @return {boolean} True if Files.app is running as an open files or a select
 *     folder dialog. False otherwise.
 */
util.runningInBrowser = function() {
  return !window.appID;
};

/**
 * Attach page load handler.
 * @param {function()} handler Application-specific load handler.
 */
util.addPageLoadHandler = function(handler) {
  document.addEventListener('DOMContentLoaded', function() {
    handler();
  });
};

/**
 * Save app launch data to the local storage.
 */
util.saveAppState = function() {
  if (!window.appState)
    return;
  var items = {};

  items[window.appID] = JSON.stringify(window.appState);
  chrome.storage.local.set(items);
};

/**
 *  AppCache is a persistent timestamped key-value storage backed by
 *  HTML5 local storage.
 *
 *  It is not designed for frequent access. In order to avoid costly
 *  localStorage iteration all data is kept in a single localStorage item.
 *  There is no in-memory caching, so concurrent access is _almost_ safe.
 *
 *  TODO(kaznacheev) Reimplement this based on Indexed DB.
 */
util.AppCache = function() {};

/**
 * Local storage key.
 */
util.AppCache.KEY = 'AppCache';

/**
 * Max number of items.
 */
util.AppCache.CAPACITY = 100;

/**
 * Default lifetime.
 */
util.AppCache.LIFETIME = 30 * 24 * 60 * 60 * 1000;  // 30 days.

/**
 * @param {string} key Key.
 * @param {function(number)} callback Callback accepting a value.
 */
util.AppCache.getValue = function(key, callback) {
  util.AppCache.read_(function(map) {
    var entry = map[key];
    callback(entry && entry.value);
  });
};

/**
 * Update the cache.
 *
 * @param {string} key Key.
 * @param {string} value Value. Remove the key if value is null.
 * @param {number=} opt_lifetime Maximum time to keep an item (in milliseconds).
 */
util.AppCache.update = function(key, value, opt_lifetime) {
  util.AppCache.read_(function(map) {
    if (value != null) {
      map[key] = {
        value: value,
        expire: Date.now() + (opt_lifetime || util.AppCache.LIFETIME)
      };
    } else if (key in map) {
      delete map[key];
    } else {
      return;  // Nothing to do.
    }
    util.AppCache.cleanup_(map);
    util.AppCache.write_(map);
  });
};

/**
 * @param {function(Object)} callback Callback accepting a map of timestamped
 *   key-value pairs.
 * @private
 */
util.AppCache.read_ = function(callback) {
  chrome.storage.local.get(util.AppCache.KEY, function(values) {
    var json = values[util.AppCache.KEY];
    if (json) {
      try {
        callback(JSON.parse(json));
      } catch (e) {
        // The local storage item somehow got messed up, start fresh.
      }
    }
    callback({});
  });
};

/**
 * @param {Object} map A map of timestamped key-value pairs.
 * @private
 */
util.AppCache.write_ = function(map) {
  var items = {};
  items[util.AppCache.KEY] = JSON.stringify(map);
  chrome.storage.local.set(items);
};

/**
 * Remove over-capacity and obsolete items.
 *
 * @param {Object} map A map of timestamped key-value pairs.
 * @private
 */
util.AppCache.cleanup_ = function(map) {
  // Sort keys by ascending timestamps.
  var keys = [];
  for (var key in map) {
    if (map.hasOwnProperty(key))
      keys.push(key);
  }
  keys.sort(function(a, b) { return map[a].expire > map[b].expire; });

  var cutoff = Date.now();

  var obsolete = 0;
  while (obsolete < keys.length &&
         map[keys[obsolete]].expire < cutoff) {
    obsolete++;
  }

  var overCapacity = Math.max(0, keys.length - util.AppCache.CAPACITY);

  var itemsToDelete = Math.max(obsolete, overCapacity);
  for (var i = 0; i != itemsToDelete; i++) {
    delete map[keys[i]];
  }
};

/**
 * Load an image.
 *
 * @param {Image} image Image element.
 * @param {string} url Source url.
 * @param {Object=} opt_options Hash array of options, eg. width, height,
 *     maxWidth, maxHeight, scale, cache.
 * @param {function()=} opt_isValid Function returning false iff the task
 *     is not valid and should be aborted.
 * @return {?number} Task identifier or null if fetched immediately from
 *     cache.
 */
util.loadImage = function(image, url, opt_options, opt_isValid) {
  return ImageLoaderClient.loadToImage(url,
                                       image,
                                       opt_options || {},
                                       function() {},
                                       function() { image.onerror(); },
                                       opt_isValid);
};

/**
 * Cancels loading an image.
 * @param {number} taskId Task identifier returned by util.loadImage().
 */
util.cancelLoadImage = function(taskId) {
  ImageLoaderClient.getInstance().cancel(taskId);
};

/**
 * Finds proerty descriptor in the object prototype chain.
 * @param {Object} object The object.
 * @param {string} propertyName The property name.
 * @return {Object} Property descriptor.
 */
util.findPropertyDescriptor = function(object, propertyName) {
  for (var p = object; p; p = Object.getPrototypeOf(p)) {
    var d = Object.getOwnPropertyDescriptor(p, propertyName);
    if (d)
      return d;
  }
  return null;
};

/**
 * Calls inherited property setter (useful when property is
 * overridden).
 * @param {Object} object The object.
 * @param {string} propertyName The property name.
 * @param {*} value Value to set.
 */
util.callInheritedSetter = function(object, propertyName, value) {
  var d = util.findPropertyDescriptor(Object.getPrototypeOf(object),
                                      propertyName);
  d.set.call(object, value);
};

/**
 * Returns true if the board of the device matches the given prefix.
 * @param {string} boardPrefix The board prefix to match against.
 *     (ex. "x86-mario". Prefix is used as the actual board name comes with
 *     suffix like "x86-mario-something".
 * @return {boolean} True if the board of the device matches the given prefix.
 */
util.boardIs = function(boardPrefix) {
  // The board name should be lower-cased, but making it case-insensitive for
  // backward compatibility just in case.
  var board = str('CHROMEOS_RELEASE_BOARD');
  var pattern = new RegExp('^' + boardPrefix, 'i');
  return board.match(pattern) != null;
};

/**
 * Adds an isFocused method to the current window object.
 */
util.addIsFocusedMethod = function() {
  var focused = true;

  window.addEventListener('focus', function() {
    focused = true;
  });

  window.addEventListener('blur', function() {
    focused = false;
  });

  /**
   * @return {boolean} True if focused.
   */
  window.isFocused = function() {
    return focused;
  };
};

/**
 * Makes a redirect to the specified Files.app's window from another window.
 * @param {number} id Window id.
 * @param {string} url Target url.
 * @return {boolean} True if the window has been found. False otherwise.
 */
util.redirectMainWindow = function(id, url) {
  // TODO(mtomasz): Implement this for Apps V2, once the photo importer is
  // restored.
  return false;
};

/**
 * Checks, if the Files.app's window is in a full screen mode.
 *
 * @param {AppWindow} appWindow App window to be maximized.
 * @return {boolean} True if the full screen mode is enabled.
 */
util.isFullScreen = function(appWindow) {
  if (appWindow) {
    return appWindow.isFullscreen();
  } else {
    console.error('App window not passed. Unable to check status of ' +
                  'the full screen mode.');
    return false;
  }
};

/**
 * Toggles the full screen mode.
 *
 * @param {AppWindow} appWindow App window to be maximized.
 * @param {boolean} enabled True for enabling, false for disabling.
 */
util.toggleFullScreen = function(appWindow, enabled) {
  if (appWindow) {
    if (enabled)
      appWindow.fullscreen();
    else
      appWindow.restore();
    return;
  }

  console.error(
      'App window not passed. Unable to toggle the full screen mode.');
};

/**
 * The type of a file operation.
 * @enum {string}
 * @const
 */
util.FileOperationType = Object.freeze({
  COPY: 'COPY',
  MOVE: 'MOVE',
  ZIP: 'ZIP',
});

/**
 * The type of a file operation error.
 * @enum {number}
 * @const
 */
util.FileOperationErrorType = Object.freeze({
  UNEXPECTED_SOURCE_FILE: 0,
  TARGET_EXISTS: 1,
  FILESYSTEM_ERROR: 2,
});

/**
 * The kind of an entry changed event.
 * @enum {number}
 * @const
 */
util.EntryChangedKind = Object.freeze({
  CREATED: 0,
  DELETED: 1,
});

/**
 * Obtains whether an entry is fake or not.
 * @param {!Entry|!Object} entry Entry or a fake entry.
 * @return {boolean} True if the given entry is fake.
 */
util.isFakeEntry = function(entry) {
  return !('getParent' in entry);
};

/**
 * Creates an instance of UserDOMError with given error name that looks like a
 * FileError except that it does not have the deprecated FileError.code member.
 *
 * TODO(uekawa): remove reference to FileError.
 *
 * @param {string} name Error name for the file error.
 * @return {UserDOMError} FileError instance
 */
util.createDOMError = function(name) {
  return new util.UserDOMError(name);
};

/**
 * Creates a DOMError-like object to be used in place of returning file errors.
 *
 * @param {string} name Error name for the file error.
 * @constructor
 */
util.UserDOMError = function(name) {
  /**
   * @type {string}
   * @private
   */
  this.name_ = name;
  Object.freeze(this);
};

util.UserDOMError.prototype = {
  /**
   * @return {string} File error name.
   */
  get name() { return this.name_;
  }
};

/**
 * Compares two entries.
 * @param {Entry|Object} entry1 The entry to be compared. Can be a fake.
 * @param {Entry|Object} entry2 The entry to be compared. Can be a fake.
 * @return {boolean} True if the both entry represents a same file or
 *     directory. Returns true if both entries are null.
 */
util.isSameEntry = function(entry1, entry2) {
  if (!entry1 && !entry2)
    return true;
  if (!entry1 || !entry2)
    return false;
  return entry1.toURL() === entry2.toURL();
};

/**
 * Compares two file systems.
 * @param {DOMFileSystem} fileSystem1 The file system to be compared.
 * @param {DOMFileSystem} fileSystem2 The file system to be compared.
 * @return {boolean} True if the both file systems are equal. Also, returns true
 *     if both file systems are null.
 */
util.isSameFileSystem = function(fileSystem1, fileSystem2) {
  if (!fileSystem1 && !fileSystem2)
    return true;
  if (!fileSystem1 || !fileSystem2)
    return false;
  return util.isSameEntry(fileSystem1.root, fileSystem2.root);
};

/**
 * Collator for sorting.
 * @type {Intl.Collator}
 */
util.collator = new Intl.Collator(
    [], {usage: 'sort', numeric: true, sensitivity: 'base'});

/**
 * Compare by name. The 2 entries must be in same directory.
 * @param {Entry} entry1 First entry.
 * @param {Entry} entry2 Second entry.
 * @return {number} Compare result.
 */
util.compareName = function(entry1, entry2) {
  return util.collator.compare(entry1.name, entry2.name);
};

/**
 * Compare by path.
 * @param {Entry} entry1 First entry.
 * @param {Entry} entry2 Second entry.
 * @return {number} Compare result.
 */
util.comparePath = function(entry1, entry2) {
  return util.collator.compare(entry1.fullPath, entry2.fullPath);
};

/**
 * Checks if the child entry is a descendant of another entry. If the entries
 * point to the same file or directory, then returns false.
 *
 * @param {DirectoryEntry|Object} ancestorEntry The ancestor directory entry.
 *     Can be a fake.
 * @param {Entry|Object} childEntry The child entry. Can be a fake.
 * @return {boolean} True if the child entry is contained in the ancestor path.
 */
util.isDescendantEntry = function(ancestorEntry, childEntry) {
  if (!ancestorEntry.isDirectory)
    return false;
  if (!util.isSameFileSystem(ancestorEntry.filesystem, childEntry.filesystem))
    return false;
  if (util.isSameEntry(ancestorEntry, childEntry))
    return false;
  if (util.isFakeEntry(ancestorEntry) || util.isFakeEntry(childEntry))
    return false;

  // Check if the ancestor's path with trailing slash is a prefix of child's
  // path.
  var ancestorPath = ancestorEntry.fullPath;
  if (ancestorPath.slice(-1) !== '/')
    ancestorPath += '/';
  return childEntry.fullPath.indexOf(ancestorPath) === 0;
};

/**
 * Visit the URL.
 *
 * If the browser is opening, the url is opened in a new tag, otherwise the url
 * is opened in a new window.
 *
 * @param {string} url URL to visit.
 */
util.visitURL = function(url) {
  window.open(url);
};

/**
 * Returns normalized current locale, or default locale - 'en'.
 * @return {string} Current locale
 */
util.getCurrentLocaleOrDefault = function() {
  // chrome.i18n.getMessage('@@ui_locale') can't be used in packed app.
  // Instead, we pass it from C++-side with strings.
  return str('UI_LOCALE') || 'en';
};

/**
 * Converts array of entries to an array of corresponding URLs.
 * @param {Array.<Entry>} entries Input array of entries.
 * @return {Array.<string>} Output array of URLs.
 */
util.entriesToURLs = function(entries) {
  return entries.map(function(entry) {
    return entry.toURL();
  });
};

/**
 * Converts array of URLs to an array of corresponding Entries.
 *
 * @param {Array.<string>} urls Input array of URLs.
 * @param {function(Array.<Entry>, Array.<URL>)=} opt_callback Completion
 *     callback with array of success Entries and failure URLs.
 * @return {Promise} Promise fulfilled with the object that has entries property
 *     and failureUrls property. The promise is never rejected.
 */
util.URLsToEntries = function(urls, opt_callback) {
  var promises = urls.map(function(url) {
    return new Promise(webkitResolveLocalFileSystemURL.bind(null, url)).
        then(function(entry) {
          return {entry: entry};
        }, function(failureUrl) {
          // Not an error. Possibly, the file is not accessible anymore.
          console.warn('Failed to resolve the file with url: ' + url + '.');
          return {failureUrl: url};
        });
  });
  var resultPromise = Promise.all(promises).then(function(results) {
    var entries = [];
    var failureUrls = [];
    for (var i = 0; i < results.length; i++) {
      if ('entry' in results[i])
        entries.push(results[i].entry);
      if ('failureUrl' in results[i]) {
        failureUrls.push(results[i].failureUrl);
      }
    }
    return {
      entries: entries,
      failureUrls: failureUrls
    };
  });

  // Invoke the callback. If opt_callback is specified, resultPromise is still
  // returned and fulfilled with a result.
  if (opt_callback) {
    resultPromise.then(function(result) {
      opt_callback(result.entries, result.failureUrls);
    }).catch(function(error) {
      console.error(
          'util.URLsToEntries is failed.',
          error.stack ? error.stack : error);
    });
  }

  return resultPromise;
};

/**
 * Returns whether the window is teleported or not.
 * @param {DOMWindow} window Window.
 * @return {Promise.<boolean>} Whether the window is teleported or not.
 */
util.isTeleported = function(window) {
  return new Promise(function(onFulfilled) {
    window.chrome.fileManagerPrivate.getProfiles(
        function(profiles, currentId, displayedId) {
          onFulfilled(currentId !== displayedId);
        });
  });
};

/**
 * Sets up and shows the alert to inform a user the task is opened in the
 * desktop of the running profile.
 *
 * TODO(hirono): Move the function from the util namespace.
 * @param {cr.ui.AlertDialog} alertDialog Alert dialog to be shown.
 * @param {Array.<Entry>} entries List of opened entries.
 */
util.showOpenInOtherDesktopAlert = function(alertDialog, entries) {
  if (!entries.length)
    return;
  chrome.fileManagerPrivate.getProfiles(
      function(profiles, currentId, displayedId) {
        // Find strings.
        var displayName;
        for (var i = 0; i < profiles.length; i++) {
          if (profiles[i].profileId === currentId) {
            displayName = profiles[i].displayName;
            break;
          }
        }
        if (!displayName) {
          console.warn('Display name is not found.');
          return;
        }

        var title = entries.size > 1 ?
            entries[0].name + '\u2026' /* ellipsis */ : entries[0].name;
        var message = strf(entries.size > 1 ?
                           'OPEN_IN_OTHER_DESKTOP_MESSAGE_PLURAL' :
                           'OPEN_IN_OTHER_DESKTOP_MESSAGE',
                           displayName,
                           currentId);

        // Show the dialog.
        alertDialog.showWithTitle(title, message);
      }.bind(this));
};

/**
 * Runs chrome.test.sendMessage in test environment. Does nothing if running
 * in production environment.
 *
 * @param {string} message Test message to send.
 */
util.testSendMessage = function(message) {
  var test = chrome.test || window.top.chrome.test;
  if (test)
    test.sendMessage(message);
};

/**
 * Returns the localized name for the root type. If not available, then returns
 * null.
 *
 * @param {VolumeManagerCommon.RootType} rootType The root type.
 * @return {?string} The localized name, or null if not available.
 */
util.getRootTypeLabel = function(rootType) {
  var str = function(id) {
    return loadTimeData.getString(id);
  };

  switch (rootType) {
    case VolumeManagerCommon.RootType.DOWNLOADS:
      return str('DOWNLOADS_DIRECTORY_LABEL');
    case VolumeManagerCommon.RootType.DRIVE:
      return str('DRIVE_MY_DRIVE_LABEL');
    case VolumeManagerCommon.RootType.DRIVE_OFFLINE:
      return str('DRIVE_OFFLINE_COLLECTION_LABEL');
    case VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME:
      return str('DRIVE_SHARED_WITH_ME_COLLECTION_LABEL');
    case VolumeManagerCommon.RootType.DRIVE_RECENT:
      return str('DRIVE_RECENT_COLLECTION_LABEL');
  }

  // Translation not found.
  return null;
};

/**
 * Extracts the extension of the path.
 *
 * Examples:
 * util.splitExtension('abc.ext') -> ['abc', '.ext']
 * util.splitExtension('a/b/abc.ext') -> ['a/b/abc', '.ext']
 * util.splitExtension('a/b') -> ['a/b', '']
 * util.splitExtension('.cshrc') -> ['', '.cshrc']
 * util.splitExtension('a/b.backup/hoge') -> ['a/b.backup/hoge', '']
 *
 * @param {string} path Path to be extracted.
 * @return {Array.<string>} Filename and extension of the given path.
 */
util.splitExtension = function(path) {
  var dotPosition = path.lastIndexOf('.');
  if (dotPosition <= path.lastIndexOf('/'))
    dotPosition = -1;

  var filename = dotPosition != -1 ? path.substr(0, dotPosition) : path;
  var extension = dotPosition != -1 ? path.substr(dotPosition) : '';
  return [filename, extension];
};

/**
 * Returns the localized name of the entry.
 *
 * @param {VolumeManager} volumeManager The volume manager.
 * @param {Entry} entry The entry to be retrieve the name of.
 * @return {?string} The localized name.
 */
util.getEntryLabel = function(volumeManager, entry) {
  var locationInfo = volumeManager.getLocationInfo(entry);

  if (locationInfo && locationInfo.isRootEntry) {
    switch (locationInfo.rootType) {
      case VolumeManagerCommon.RootType.DOWNLOADS:
        return str('DOWNLOADS_DIRECTORY_LABEL');
      case VolumeManagerCommon.RootType.DRIVE:
        return str('DRIVE_MY_DRIVE_LABEL');
      case VolumeManagerCommon.RootType.DRIVE_OFFLINE:
        return str('DRIVE_OFFLINE_COLLECTION_LABEL');
      case VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME:
        return str('DRIVE_SHARED_WITH_ME_COLLECTION_LABEL');
      case VolumeManagerCommon.RootType.DRIVE_RECENT:
        return str('DRIVE_RECENT_COLLECTION_LABEL');
      case VolumeManagerCommon.RootType.DRIVE_OTHER:
      case VolumeManagerCommon.RootType.DOWNLOADS:
      case VolumeManagerCommon.RootType.ARCHIVE:
      case VolumeManagerCommon.RootType.REMOVABLE:
      case VolumeManagerCommon.RootType.MTP:
      case VolumeManagerCommon.RootType.PROVIDED:
        return locationInfo.volumeInfo.label;
      default:
        console.error('Unsupported root type: ' + locationInfo.rootType);
        return locationInfo.volumeInfo.label;
    }
  }

  return entry.name;
};

/**
 * Checks if the specified set of allowed effects contains the given effect.
 * See: http://www.w3.org/TR/html5/editing.html#the-datatransfer-interface
 *
 * @param {string} effectAllowed The string denoting the set of allowed effects.
 * @param {string} dropEffect The effect to be checked.
 * @return {boolean} True if |dropEffect| is included in |effectAllowed|.
 */
util.isDropEffectAllowed = function(effectAllowed, dropEffect) {
  return effectAllowed === 'all' ||
      effectAllowed.toLowerCase().indexOf(dropEffect) !== -1;
};

/**
 * Verifies the user entered name for file or folder to be created or
 * renamed to. Name restrictions must correspond to File API restrictions
 * (see DOMFilePath::isValidPath). Curernt WebKit implementation is
 * out of date (spec is
 * http://dev.w3.org/2009/dap/file-system/file-dir-sys.html, 8.3) and going to
 * be fixed. Shows message box if the name is invalid.
 *
 * It also verifies if the name length is in the limit of the filesystem.
 *
 * @param {DirectoryEntry} parentEntry The URL of the parent directory entry.
 * @param {string} name New file or folder name.
 * @param {boolean} filterHiddenOn Whether to report the hidden file name error
 *     or not.
 * @return {Promise} Promise fulfilled on success, or rejected with the error
 *     message.
 */
util.validateFileName = function(parentEntry, name, filterHiddenOn) {
  var testResult = /[\/\\\<\>\:\?\*\"\|]/.exec(name);
  var msg;
  if (testResult)
    return Promise.reject(strf('ERROR_INVALID_CHARACTER', testResult[0]));
  else if (/^\s*$/i.test(name))
    return Promise.reject(str('ERROR_WHITESPACE_NAME'));
  else if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(name))
    return Promise.reject(str('ERROR_RESERVED_NAME'));
  else if (filterHiddenOn && /\.crdownload$/i.test(name))
    return Promise.reject(str('ERROR_RESERVED_NAME'));
  else if (filterHiddenOn && name[0] == '.')
    return Promise.reject(str('ERROR_HIDDEN_NAME'));

  return new Promise(function(fulfill, reject) {
    chrome.fileManagerPrivate.validatePathNameLength(
        parentEntry.toURL(),
        name,
        function(valid) {
          if (valid)
            fulfill();
          else
            reject(str('ERROR_LONG_NAME'));
        });
  });
};


text:
package org.elasticsearch.hadoop.serialization.bulk;

import java.util.List;

import org.elasticsearch.hadoop.cfg.ConfigurationOptions;
import org.elasticsearch.hadoop.cfg.Settings;
import org.elasticsearch.hadoop.serialization.bulk.MetadataExtractor.Metadata;
import org.elasticsearch.hadoop.serialization.field.FieldExtractor;
import org.elasticsearch.hadoop.util.Assert;
import org.elasticsearch.hadoop.util.StringUtils;

class UpdateBulkFactory extends AbstractBulkFactory {

    private final int RETRY_ON_FAILURE;
    private final String RETRY_HEADER;
    private final String SCRIPT;
    private final String SCRIPT_LANG;

    private final boolean HAS_SCRIPT, HAS_LANG, HAS_PARAMS;
    private final boolean UPSERT;

    public UpdateBulkFactory(Settings settings, MetadataExtractor metaExtractor) {
        this(settings, false, metaExtractor);
    }

    public UpdateBulkFactory(Settings settings, boolean upsert, MetadataExtractor metaExtractor) {
        super(settings, metaExtractor);

        UPSERT = upsert;
        RETRY_ON_FAILURE = settings.getUpdateRetryOnConflict();
        RETRY_HEADER = "\"_retry_on_conflict\":" + RETRY_ON_FAILURE + "";

        HAS_SCRIPT = StringUtils.hasText(settings.getUpdateScript());
        HAS_LANG = StringUtils.hasText(settings.getUpdateScriptLang());
        HAS_PARAMS = StringUtils.hasText(settings.getUpdateScriptParams());

        SCRIPT_LANG = "\"lang\":\"" + settings.getUpdateScriptLang() + "\",";
        SCRIPT = "\"script\":\"" + settings.getUpdateScript() + "\"";
    }

    @Override
    protected String getOperation() {
        return ConfigurationOptions.ES_OPERATION_UPDATE;
    }

    @Override
    protected void otherHeader(List<Object> list, boolean commaMightBeNeeded) {
        if (RETRY_ON_FAILURE > 0) {
            if (commaMightBeNeeded) {
                list.add(",");
            }
            list.add(RETRY_HEADER);
        }
    }

    @Override
    protected void writeObjectHeader(List<Object> list) {
        super.writeObjectHeader(list);

        Object paramExtractor = getExtractorOrDynamicValue(Metadata.PARAMS, getParamExtractor());

        if (paramExtractor != null) {
            list.add("{\"params\":");
            list.add(paramExtractor);
            list.add(",");
        }
        else {
            list.add("{");
        }

        if (HAS_SCRIPT) {
            if (HAS_LANG) {
                list.add(SCRIPT_LANG);
            }
            list.add(SCRIPT);
            if (UPSERT) {
                list.add(",\"upsert\":");
            }
        }
        else {
            if (UPSERT) {
                list.add("\"doc_as_upsert\":true,");
            }
            list.add("\"doc\":");
        }
    }

    @Override
    protected void writeObjectEnd(List<Object> after) {
        after.add("}");
        super.writeObjectEnd(after);
    }

    @Override
    protected boolean id(List<Object> list, boolean commaMightBeNeeded) {
        boolean added = super.id(list, commaMightBeNeeded);
        Assert.isTrue(added, String.format("Operation [%s] requires an id but none was given/found", getOperation()));
        return added;
    }
}


text:
package event

import (
	netv1 "k8s.io/api/networking/v1"

	"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/apis/networking.gke.io/v1"
)

type Fake struct {
	BackendErrorCnt        int
	CreateCnt              int
	DeleteCnt              int
	MissingCertificateCnt  int
	TooManyCertificatesCnt int
}

var _ Interface = (*Fake)(nil)

func (f *Fake) BackendError(mcrt v1.ManagedCertificate, err error) {
	f.BackendErrorCnt++
}

func (f *Fake) Create(mcrt v1.ManagedCertificate, sslCertificateName string) {
	f.CreateCnt++
}

func (f *Fake) Delete(mcrt v1.ManagedCertificate, sslCertificateName string) {
	f.DeleteCnt++
}

func (f *Fake) MissingCertificate(ingress netv1.Ingress, mcrtName string) {
	f.MissingCertificateCnt++
}

func (f *Fake) TooManyCertificates(mcrt v1.ManagedCertificate, err error) {
	f.TooManyCertificatesCnt++
}


text:
import {EntityMetadata} from "../../metadata/EntityMetadata";
import {EntityMetadataNotFound} from "../error/EntityMetadataNotFound";

/**
 * Array for the entity metadatas.
 */
export class EntityMetadataCollection extends Array<EntityMetadata> {

    // -------------------------------------------------------------------------
    // Public Methods
    // -------------------------------------------------------------------------

    hasTarget(target: Function|string) {
        return !!this.find(metadata => metadata.target === target || (typeof target === "string" && metadata.targetName === target));
    }

    findByTarget(target: Function|string): EntityMetadata {
        const metadata = this.find(metadata => metadata.target === target || (typeof target === "string" && metadata.targetName === target));
        if (!metadata)
            throw new EntityMetadataNotFound(target);

        return metadata;
    }

    findByName(name: string) {
        const metadata = this.find(metadata => metadata.name === name);
        if (!metadata)
            throw new EntityMetadataNotFound(name);

        return metadata;
    }

    filter(callbackfn: (value: EntityMetadata, index?: number, array?: Array<EntityMetadata>) => any, thisArg?: any): EntityMetadataCollection {
        thisArg = thisArg || void 0;
        return this.reduce(function(out: EntityMetadataCollection, val: EntityMetadata, index: number, array: Array<EntityMetadata>) {
            if (callbackfn.call(thisArg, val, index, array)) {
                out.push(val);
            }
            return out;
        }, new EntityMetadataCollection());
    }

}


text:
include(tools4tests)

if(WITH_${COMPONENT}_TESTING)

  # We don't use COMPILE_WITH since we don't want to link cppunit with the
  # kernel library
  find_package(CppUnit REQUIRED)
  set(TEST_LIBS ${TEST_LIBS} ${CPPUNIT_LIBRARIES})
  set(TEST_INCLUDE_DIR ${TEST_INCLUDE_DIR} ${CPPUNIT_INCLUDE_DIR})

  # the main test driver
  SET(TEST_MAIN src/contactDetection/basicBroadphase/test/TestMain.cpp)

  BEGIN_TEST(src/contactDetection/basicBroadphase/test)
  NEW_TEST(testMultiBody MultiBodyTest.cpp)
  END_TEST()

  IF(WITH_OCC)
    BEGIN_TEST(src/occ/test)
    NEW_TEST(testOcc OccTest.cpp)
    END_TEST()
  ENDIF()

  IF(WITH_MECHANISMS)
    MESSAGE("   ")
    MESSAGE("-------------------------------------- ************************ ")

    get_subdirectories(dirlist ${CMAKE_SOURCE_DIR}/examples/Mechanics/Mechanisms/)
    foreach(_dir ${dirlist})
      MESSAGE("${_dir}")
      set(bin_dir ${CMAKE_BINARY_DIR}/mechanics/swig/mechanics/mechanisms/test/${_dir})
      MESSAGE("mkdir ${bin_dir} ")
      file(MAKE_DIRECTORY ${bin_dir})
      file(GLOB EXAMPLES_FILES ${CMAKE_SOURCE_DIR}/examples/Mechanics/Mechanisms/${_dir}/bodydef.py
	${CMAKE_SOURCE_DIR}/examples/Mechanics/Mechanisms/${_dir}/mbtbLocalOptions.py)
      foreach(_F ${EXAMPLES_FILES})
	#MESSAGE("${_F}")
	configure_file(${_F} ${bin_dir})
	file(READ ${_F} RESOURCES_FILE)
	string(REGEX REPLACE
	  "with3D=1"
	  "with3D=0 # remove X output for test#"
	  RESOURCES_FILE_MODIFIED ${RESOURCES_FILE})
	#MESSAGE(${RESOURCES_FILE_MODIFIED})
	get_filename_component(_F_NAME ${_F} NAME)
	file(WRITE ${bin_dir}/${_F_NAME} ${RESOURCES_FILE_MODIFIED})
      endforeach()
      get_subdirectories(subdirlist ${CMAKE_SOURCE_DIR}/examples/Mechanics/Mechanisms/${_dir})

      foreach(_subdir ${subdirlist})
	if(NOT _subdir MATCHES siconos)
	  MESSAGE("subdir ${_subdir}")
	  file(GLOB EXAMPLES_SUBDIR_FILES
	    ${CMAKE_SOURCE_DIR}/examples/Mechanics/Mechanisms/${_dir}/${_subdir}/*.*)
	  file(MAKE_DIRECTORY ${bin_dir}/${_subdir})
	  foreach(_F ${EXAMPLES_SUBDIR_FILES})
	    MESSAGE("${_F}")
	    configure_file(${_F} ${bin_dir}/${_subdir})
	  endforeach()
	endif()
      endforeach(_subdir)

      set(command_name "python ${CMAKE_BINARY_DIR}/scripts/siconos -P ${CMAKE_BINARY_DIR}/scripts/siconos-mechanisms.py .")
      MESSAGE("${command_name}")
      add_test(mechanisms_${_dir} ${CMAKE_COMMAND} -E chdir ${bin_dir} python ${CMAKE_BINARY_DIR}/scripts/siconos -P ${CMAKE_BINARY_DIR}/scripts/siconos-mechanisms.py . )
    endforeach(_dir)

  ENDIF()

endif()


text:
class CreateTeams < ActiveRecord::Migration
  def self.up
    create_table :teams do |t|
      t.string :name
      t.string :password_digest
      t.datetime :updated_at
      t.datetime :created_at
    end
  end

  def self.down
    drop_table :teams
  end
end


text:
How to setup the advanced template in YII2
==========================================

## Step1: Init configuration ##

Open a terminal and go to the YII project folder, then run

    php init

on Linux/Mac or following command on Windows

    init.bat

Choose the development enviornment and finish the steps.

## Step2: Configure the database ##

### Configure the database using phpmyadmin in XAMPP ###

XAMPP is a popular PHP development enviornment and can run on Linux/Mac/Windows. It provides a easy
to install package containing Apache + MariaDB + PHP + Perl. Visit the home page at
https://www.apachefriends.org/index.html for downloads.

To visit phpmyadmin after installation, start the Apache and MySQL server in XAMPP control panel,
and open http://localhost/phpmyadmin/ at the webbrowser. The default root password for MySQL connection
is empty. You can change the password in the phpmyadmin.

### Configure the database using mysql ###

mysql is a command line tool for making connection to the MySQL server and execute MySQL commands. Below
gives basic mysql commands for creating a new database:

Connect to the MySQL server

    mysql -h localhost -P 3306 -u root

Show available database

    MySQL> show databases;

Create new database

    MySQL> create database smartdoor

### Configure database settings in YII2 ###

After creating database, configure the settings in common/config/main-local.php:

    <?php
    return [
        'components' => [
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host=localhost;dbname=smartdoor',
                'username' => 'root',
                'password' => '',
                'charset' => 'utf8',
            ],
            'mailer' => [
                'class' => 'yii\swiftmailer\Mailer',
                'viewPath' => '@common/mail',
                // send all mails to a file by default. You have to set
                // 'useFileTransport' to false and configure a transport
                // for the mailer to send real emails.
                'useFileTransport' => true,
            ],
        ],
    ];

## Step3: Run Database Migration ##

Run following command to create new country table and populate its data

    php yii migrate

on Linux/Mac or following command on Windows

    yii.bat migrate


text:
package org.xmlbeam.tutorial.e15_plist;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Test;
import org.xmlbeam.XBProjector;
import org.xmlbeam.config.DefaultXMLFactoriesConfig;
import org.xmlbeam.externalizer.ExternalizerAdapter;
import org.xmlbeam.tutorial.TutorialTestCase;

//START SNIPPET: Tutorial15

/* START SNIPPET: TutorialDescription
~~
 In this tutorial we address quite a few challenges in accessing the data in plist files.
 XML plists (XML Property Lists) files are key/value based data storages frequently used by OS X
 applications. The challenge is that the data is not stored in the key element, but besides.
 A key element is followed by an additional element holding the data. The name of the data containing element
 depends on the type of data. So we need some real XPath magic to cover this :)
 The second challenge is that we don't like to have XPath expressions specified for all data in the file.
 Instead we like to derive the key value of the expression from the method name.
 Last but not least we show how to switch the DTD validation of, in case your not on an OS X system.
END SNIPPET: TutorialDescription */

@SuppressWarnings({"serial","javadoc"})
//START SNIPPET: TestPlistAccess
public class TestPlistAccess extends TutorialTestCase {

    /**
     * Every plist file has a DTD referenced which might be unavailable if you are on a non MacOs system.
     * So we tweak the XBProjector configuration to ignore the DTD.
     */
    private final class NonValidatingXMLFactoriesConfig extends DefaultXMLFactoriesConfig {
        @Override
        public DocumentBuilderFactory createDocumentBuilderFactory()  {
            try {
            final DocumentBuilderFactory factory = super.createDocumentBuilderFactory();
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            return factory;
            }  catch (final ParserConfigurationException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * The projection in this tutorial does not define any XPath expression to the data.
     * Instead we like to derive the XPath from the method name. Although this could be done
     * in a single XPath expression, we split it up for two cases for readability:
     * - Selecting all children of the following element of the key element, if an array is expected
     * and
     * - Selecting the first following element of the key element, in all other cases.
     */
    public class PListExternalizer extends ExternalizerAdapter {

        @Override
        public String resolveXPath(final String annotationValue, final Method method, final Object[] args) {
            final String keyValue = method.getName().substring(3);
            if (method.getReturnType().isArray()) {
                return  "/plist/dict/key[.=\""+keyValue+"\"]/following-sibling::*[1]/child::*";
            }
           return  "/plist/dict/key[.=\""+keyValue+"\"]/following-sibling::*[1]";
        }

    }

    @Test
    public void testReadPList() throws IOException {
        final XBProjector projector = new XBProjector(new NonValidatingXMLFactoriesConfig());
        projector.config().setExternalizer(new PListExternalizer());
        final PList plist = projector.io().fromURLAnnotation(PList.class);
        System.out.println(plist.getAuthor()+" ("+plist.getBirthdate()+")");
        for (final String line:plist.getLines()) {
            System.out.println(line);
        }
    }
}
//END SNIPPET: TestPlistAccess
//END SNIPPET: Tutorial15


text:
<?xml version="1.0" encoding="utf-8"?>
<lfm status="ok">
  <results for="Believe">
    <opensearch:Query role="request" searchTerms="Believe" startPage="1" />
    <opensearch:totalResults>3926</opensearch:totalResults>
    <opensearch:startIndex>0</opensearch:startIndex>
    <opensearch:itemsPerPage>50</opensearch:itemsPerPage>
    <albummatches>
      <album>
        <name>Believe</name>
        <artist>Disturbed</artist>
        <id>1418894</id>
        <url>http://www.last.fm/music/Disturbed/Believe</url>
        <image size="small">http://userserve-ak.last.fm/serve/34s/53553281.png</image>
        <image size="medium">http://userserve-ak.last.fm/serve/64s/53553281.png</image>
        <image size="large">http://userserve-ak.last.fm/serve/126/53553281.png</image>
        <image size="extralarge">http://userserve-ak.last.fm/serve/300x300/53553281.png</image>
        <streamable>0</streamable>
        <mbid>ed32813a-cd20-4bb3-b3fd-bca6161deb17</mbid>
      </album>
    </albummatches>
  </results>
</lfm>


text:
enum Layer {
  kLayerHidden,
  kLayerBot,
  kLayerProjectiles,
  kLayerMid,
  kLayerMidElevated,
  kLayerTop,
  kLayerUI,
  kLayerCursor,
  kLayers
};

class InstancesManager {
 public:
  InstancesManager();

  void AddInstance(Instance *instance, Layer layer);
  void MarkToRemoveAndDelete(Instance *instance);

  void Draw(sf::RenderTarget *target);
  void Step(sf::Time elapsed);

  void KeyPressed(sf::Event::KeyEvent event);
  void KeyReleased(sf::Event::KeyEvent event);

  void MousePressed(sf::Event::MouseButtonEvent event);
  void MouseReleased(sf::Event::MouseButtonEvent event);
  void MouseMoved(sf::Event::MouseMoveEvent event);

  void EventTriggered(GameEvent event);

  void RemovePass();

 private:
  std::vector<std::vector<Instance*> > layers_;
  std::vector<Instance*> markedDelete_;
};

#endif  // BASE_INSTANCES_MANAGER_H_


text:
go-hc128
========
go-hc128 is a pure Go implementation of [HC-128](http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf), a stream cipher in the [eSTREAM](https://en.wikipedia.org/wiki/ESTREAM) portfolio.

[![Build Status](https://secure.travis-ci.org/tomfitzhenry/go-hc128.png)](http://travis-ci.org/tomfitzhenry/go-hc128)

How to install
--------------
`$ go get github.com/tomfitzhenry/go-hc128`

Documentation
-------------
[pkgdoc: github.com/tomfitzhenry/go-hc128](http://go.pkgdoc.org/github.com/tomfitzhenry/go-hc128)


text:
import { SyncStatus, SyncResource, IUserDataSyncService, UserDataSyncError, ISyncResourceHandle, ISyncTask, IManualSyncTask, IUserDataManifest, ISyncResourcePreview, IResourcePreview } from 'vs/platform/userDataSync/common/userDataSync';
import { ISharedProcessService } from 'vs/platform/ipc/electron-browser/sharedProcessService';
import { Disposable } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { IChannel } from 'vs/base/parts/ipc/common/ipc';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { CancellationToken } from 'vs/base/common/cancellation';
import { URI } from 'vs/base/common/uri';

export class UserDataSyncService extends Disposable implements IUserDataSyncService {

	declare readonly _serviceBrand: undefined;

	private readonly channel: IChannel;

	private _status: SyncStatus = SyncStatus.Uninitialized;
	get status(): SyncStatus { return this._status; }
	private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>());
	readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event;

	get onDidChangeLocal(): Event<SyncResource> { return this.channel.listen<SyncResource>('onDidChangeLocal'); }

	private _conflicts: [SyncResource, IResourcePreview[]][] = [];
	get conflicts(): [SyncResource, IResourcePreview[]][] { return this._conflicts; }
	private _onDidChangeConflicts: Emitter<[SyncResource, IResourcePreview[]][]> = this._register(new Emitter<[SyncResource, IResourcePreview[]][]>());
	readonly onDidChangeConflicts: Event<[SyncResource, IResourcePreview[]][]> = this._onDidChangeConflicts.event;

	private _lastSyncTime: number | undefined = undefined;
	get lastSyncTime(): number | undefined { return this._lastSyncTime; }
	private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>());
	readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event;

	private _onSyncErrors: Emitter<[SyncResource, UserDataSyncError][]> = this._register(new Emitter<[SyncResource, UserDataSyncError][]>());
	readonly onSyncErrors: Event<[SyncResource, UserDataSyncError][]> = this._onSyncErrors.event;

	constructor(
		@ISharedProcessService private readonly sharedProcessService: ISharedProcessService
	) {
		super();
		const userDataSyncChannel = sharedProcessService.getChannel('userDataSync');
		this.channel = {
			call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
				return userDataSyncChannel.call(command, arg, cancellationToken)
					.then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); });
			},
			listen<T>(event: string, arg?: any): Event<T> {
				return userDataSyncChannel.listen(event, arg);
			}
		};
		this.channel.call<[SyncStatus, [SyncResource, IResourcePreview[]][], number | undefined]>('_getInitialData').then(([status, conflicts, lastSyncTime]) => {
			this.updateStatus(status);
			this.updateConflicts(conflicts);
			if (lastSyncTime) {
				this.updateLastSyncTime(lastSyncTime);
			}
			this._register(this.channel.listen<SyncStatus>('onDidChangeStatus')(status => this.updateStatus(status)));
			this._register(this.channel.listen<number>('onDidChangeLastSyncTime')(lastSyncTime => this.updateLastSyncTime(lastSyncTime)));
		});
		this._register(this.channel.listen<[SyncResource, IResourcePreview[]][]>('onDidChangeConflicts')(conflicts => this.updateConflicts(conflicts)));
		this._register(this.channel.listen<[SyncResource, Error][]>('onSyncErrors')(errors => this._onSyncErrors.fire(errors.map(([source, error]) => ([source, UserDataSyncError.toUserDataSyncError(error)])))));
	}

	pull(): Promise<void> {
		return this.channel.call('pull');
	}

	createSyncTask(): Promise<ISyncTask> {
		throw new Error('not supported');
	}

	async createManualSyncTask(): Promise<IManualSyncTask> {
		const { id, manifest } = await this.channel.call<{ id: string, manifest: IUserDataManifest | null }>('createManualSyncTask');
		return new ManualSyncTask(id, manifest, this.sharedProcessService);
	}

	replace(uri: URI): Promise<void> {
		return this.channel.call('replace', [uri]);
	}

	reset(): Promise<void> {
		return this.channel.call('reset');
	}

	resetRemote(): Promise<void> {
		return this.channel.call('resetRemote');
	}

	resetLocal(): Promise<void> {
		return this.channel.call('resetLocal');
	}

	hasPreviouslySynced(): Promise<boolean> {
		return this.channel.call('hasPreviouslySynced');
	}

	hasLocalData(): Promise<boolean> {
		return this.channel.call('hasLocalData');
	}

	accept(syncResource: SyncResource, resource: URI, content: string | null, apply: boolean): Promise<void> {
		return this.channel.call('accept', [syncResource, resource, content, apply]);
	}

	resolveContent(resource: URI): Promise<string | null> {
		return this.channel.call('resolveContent', [resource]);
	}

	async getLocalSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
		const handles = await this.channel.call<ISyncResourceHandle[]>('getLocalSyncResourceHandles', [resource]);
		return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
	}

	async getRemoteSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> {
		const handles = await this.channel.call<ISyncResourceHandle[]>('getRemoteSyncResourceHandles', [resource]);
		return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) }));
	}

	async getAssociatedResources(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI, comparableResource?: URI }[]> {
		const result = await this.channel.call<{ resource: URI, comparableResource?: URI }[]>('getAssociatedResources', [resource, syncResourceHandle]);
		return result.map(({ resource, comparableResource }) => ({ resource: URI.revive(resource), comparableResource: URI.revive(comparableResource) }));
	}

	async getMachineId(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<string | undefined> {
		return this.channel.call<string | undefined>('getMachineId', [resource, syncResourceHandle]);
	}

	private async updateStatus(status: SyncStatus): Promise<void> {
		this._status = status;
		this._onDidChangeStatus.fire(status);
	}

	private async updateConflicts(conflicts: [SyncResource, IResourcePreview[]][]): Promise<void> {
		// Revive URIs
		this._conflicts = conflicts.map(([syncResource, conflicts]) =>
			([
				syncResource,
				conflicts.map(r =>
					({
						...r,
						localResource: URI.revive(r.localResource),
						remoteResource: URI.revive(r.remoteResource),
						previewResource: URI.revive(r.previewResource),
					}))
			]));
		this._onDidChangeConflicts.fire(this._conflicts);
	}

	private updateLastSyncTime(lastSyncTime: number): void {
		if (this._lastSyncTime !== lastSyncTime) {
			this._lastSyncTime = lastSyncTime;
			this._onDidChangeLastSyncTime.fire(lastSyncTime);
		}
	}
}

class ManualSyncTask implements IManualSyncTask {

	private readonly channel: IChannel;

	get onSynchronizeResources(): Event<[SyncResource, URI[]][]> { return this.channel.listen<[SyncResource, URI[]][]>('onSynchronizeResources'); }

	constructor(
		readonly id: string,
		readonly manifest: IUserDataManifest | null,
		sharedProcessService: ISharedProcessService,
	) {
		const manualSyncTaskChannel = sharedProcessService.getChannel(`manualSyncTask-${id}`);
		this.channel = {
			call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> {
				return manualSyncTaskChannel.call(command, arg, cancellationToken)
					.then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); });
			},
			listen<T>(event: string, arg?: any): Event<T> {
				return manualSyncTaskChannel.listen(event, arg);
			}
		};
	}

	async preview(): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('preview');
		return this.deserializePreviews(previews);
	}

	async accept(resource: URI, content: string | null): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('accept', [resource, content]);
		return this.deserializePreviews(previews);
	}

	async merge(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('merge', [resource]);
		return this.deserializePreviews(previews);
	}

	async discard(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discard', [resource]);
		return this.deserializePreviews(previews);
	}

	async apply(): Promise<[SyncResource, ISyncResourcePreview][]> {
		const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('apply');
		return this.deserializePreviews(previews);
	}

	pull(): Promise<void> {
		return this.channel.call('pull');
	}

	push(): Promise<void> {
		return this.channel.call('push');
	}

	stop(): Promise<void> {
		return this.channel.call('stop');
	}

	dispose(): void {
		this.channel.call('dispose');
	}

	private deserializePreviews(previews: [SyncResource, ISyncResourcePreview][]): [SyncResource, ISyncResourcePreview][] {
		return previews.map(([syncResource, preview]) =>
			([
				syncResource,
				{
					isLastSyncFromCurrentMachine: preview.isLastSyncFromCurrentMachine,
					resourcePreviews: preview.resourcePreviews.map(r => ({
						...r,
						localResource: URI.revive(r.localResource),
						remoteResource: URI.revive(r.remoteResource),
						previewResource: URI.revive(r.previewResource),
						acceptedResource: URI.revive(r.acceptedResource),
					}))
				}
			]));
	}
}

registerSingleton(IUserDataSyncService, UserDataSyncService);


text:
class DocbookXsl < Formula
  desc "XML vocabulary to create presentation-neutral documents"
  homepage "https://github.com/docbook/xslt10-stylesheets"
  url "https://github.com/docbook/xslt10-stylesheets/releases/download/release%2F1.79.2/docbook-xsl-nons-1.79.2.tar.bz2"
  sha256 "ee8b9eca0b7a8f89075832a2da7534bce8c5478fc8fc2676f512d5d87d832102"
  # Except as otherwise noted, for example, under some of the /contrib/
  # directories, the DocBook XSLT 1.0 Stylesheets use The MIT License.
  license "MIT"
  revision 1

  livecheck do
    url :homepage
    regex(%r{^(?:release/)?(\d+(?:\.\d+)+)$}i)
  end

  bottle do
    cellar :any_skip_relocation
    sha256 "65a5442556a88a865ef377cb73df0b3edf9ab2240e6f4bb2d71a71eabc74fa26" => :catalina
    sha256 "65a5442556a88a865ef377cb73df0b3edf9ab2240e6f4bb2d71a71eabc74fa26" => :mojave
    sha256 "65a5442556a88a865ef377cb73df0b3edf9ab2240e6f4bb2d71a71eabc74fa26" => :high_sierra
    sha256 "6b52c47bc47c4a19699fb52277f477d27bfb519d9b7e01d94ad6c566cf27f873" => :x86_64_linux
  end

  depends_on "docbook"

  resource "ns" do
    url "https://github.com/docbook/xslt10-stylesheets/releases/download/release%2F1.79.2/docbook-xsl-1.79.2.tar.bz2"
    sha256 "316524ea444e53208a2fb90eeb676af755da96e1417835ba5f5eb719c81fa371"
  end

  resource "doc" do
    url "https://github.com/docbook/xslt10-stylesheets/releases/download/release%2F1.79.2/docbook-xsl-doc-1.79.2.tar.bz2"
    sha256 "9bc38a3015717279a3a0620efb2d4bcace430077241ae2b0da609ba67d8340bc"
  end

  # see http://www.linuxfromscratch.org/blfs/view/9.1/pst/docbook-xsl.html for this patch
  patch do
    url "http://www.linuxfromscratch.org/patches/blfs/9.1/docbook-xsl-nons-1.79.2-stack_fix-1.patch"
    sha256 "a92c39715c54949ba9369add1809527b8f155b7e2a2b2e30cb4b39ee715f2e30"
  end

  def install
    ENV["XML_CATALOG_FILES"] = "#{etc}/xml/catalog"
    doc_files = %w[AUTHORS BUGS COPYING NEWS README RELEASE-NOTES.txt TODO VERSION VERSION.xsl]
    xsl_files = %w[assembly catalog.xml common docsrc eclipse epub epub3 extensions
                   fo highlighting html htmlhelp images javahelp lib log manpages
                   params profiling roundtrip slides template tests tools webhelp
                   website xhtml xhtml-1_1 xhtml5]
    touch "log"
    (prefix/"docbook-xsl").install xsl_files + doc_files
    resource("ns").stage do
      touch "log"
      (prefix/"docbook-xsl-ns").install xsl_files + doc_files
    end
    resource("doc").stage do
      doc.install "doc" => "reference"
    end

    bin.write_exec_script "#{prefix}/docbook-xsl/epub/bin/dbtoepub"
  end

  def xmlcatalog
    OS.mac? ? "xmlcatalog" : "#{Formula["libxml2"].opt_bin}/xmlcatalog"
  end

  def post_install
    etc_catalog = etc/"xml/catalog"
    ENV["XML_CATALOG_FILES"] = etc_catalog

    [
      ["xsl",    "xsl-nons"],
      ["xsl-ns", "xsl"],
    ].each do |nms|
      old_name = nms[0]
      new_name = nms[1]
      loc = "file://#{opt_prefix}/docbook-#{old_name}"

      # add/replace catalog entries
      cat_loc = "#{loc}/catalog.xml"
      system xmlcatalog, "--noout", "--del", cat_loc, etc_catalog
      system xmlcatalog, "--noout", "--add", "nextCatalog", "", cat_loc, etc_catalog

      # add rewrites for the new and old catalog URLs
      [
        "https://cdn.docbook.org/release/#{new_name}",
        "http://docbook.sourceforge.net/release/#{old_name}",
      ].each do |url_prefix|
        [version.to_s, "current"].each do |ver|
          system xmlcatalog, "--noout", "--del", "#{url_prefix}/#{ver}", etc_catalog
          ["rewriteSystem", "rewriteURI"].each do |k|
            system xmlcatalog, "--noout", "--add", k, "#{url_prefix}/#{ver}", loc, etc_catalog
          end
        end
      end
    end
  end

  test do
    system xmlcatalog, "#{etc}/xml/catalog", "https://cdn.docbook.org/release/xsl-nons/current/"
    system xmlcatalog, "#{etc}/xml/catalog", "https://cdn.docbook.org/release/xsl-nons/#{version}/"
    system xmlcatalog, "#{etc}/xml/catalog", "https://cdn.docbook.org/release/xsl/current/"
    system xmlcatalog, "#{etc}/xml/catalog", "https://cdn.docbook.org/release/xsl/#{version}/"
    system xmlcatalog, "#{etc}/xml/catalog", "http://docbook.sourceforge.net/release/xsl/current/"
    system xmlcatalog, "#{etc}/xml/catalog", "http://docbook.sourceforge.net/release/xsl/#{version}/"
    system xmlcatalog, "#{etc}/xml/catalog", "http://docbook.sourceforge.net/release/xsl-ns/current/"
    system xmlcatalog, "#{etc}/xml/catalog", "http://docbook.sourceforge.net/release/xsl-ns/#{version}/"
  end
end


text:
let haStr = "Hazzzzah";
let haRegex = /change/; // Change this line
let result = haRegex.test(haStr);


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class DropdownLanguageUpdater : MonoBehaviour
{

#pragma warning disable 0649
    [SerializeField]
    private UnityEvent onLanguageChanged;
#pragma warning restore 0649

    string currentLanguage;

	void Start()
	{
        currentLanguage = TextHelper.getLoadedLanguageID();
	}

	void Update()
	{
		if (currentLanguage != TextHelper.getLoadedLanguageID())
        {
            onLanguageChanged.Invoke();
            currentLanguage = TextHelper.getLoadedLanguageID();
        }
	}
}


text:
/**
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the latest version of the GNU Lesser General
 * Public License as published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program (LICENSE.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.jamwiki.parser.jflex;

import org.jamwiki.parser.ParserException;
import org.jamwiki.utils.WikiLogger;

/**
 * Process wiki bold and italic syntax (''italic'', '''bold''', '''''bold italic''''').
 */
public class WikiBoldItalicTag implements JFlexParserTag {

	private static final WikiLogger logger = WikiLogger.getLogger(WikiBoldItalicTag.class.getName());

	/**
	 * Parse a call to a Mediawiki noinclude tag of the form
	 * "<noinclude>text</noinclude>" and return the resulting output.
	 */
	public String parse(JFlexLexer lexer, String raw, Object... args) {
		if (logger.isTraceEnabled()) {
			logger.trace("bold / italic: " + raw + " (" + lexer.yystate() + ")");
		}
		if (args.length == 0) {
			throw new IllegalArgumentException("Must pass heading depth to WikiHeadingTag.parse");
		}
		try {
			this.processBoldItalic(lexer, (String)args[0]);
		} catch (ParserException e) {
			logger.info("Failure while parsing: " + raw, e);
			return raw;
		}
		return "";
	}

	/**
	 * Handle parsing of bold, italic, and bolditalic tags.
	 *
	 * @param tagType The tag type being parsed - either "i", "b", or null
	 *  if a bolditalic tag is being parsed.
	 */
	private void processBoldItalic(JFlexLexer lexer, String tagType) throws ParserException {
		if (tagType == null) {
			// bold-italic
			if (((JAMWikiLexer)lexer).peekTag().getTagType().equals("i")) {
				// italic tag already opened
				this.processBoldItalic(lexer, "i");
				this.processBoldItalic(lexer, "b");
			} else {
				// standard bold-italic processing
				this.processBoldItalic(lexer, "b");
				this.processBoldItalic(lexer, "i");
			}
			return;
		}
		// bold or italic
		if (((JAMWikiLexer)lexer).peekTag().getTagType().equals(tagType)) {
			// tag was open, close it
			((JAMWikiLexer)lexer).popTag(tagType);
			return;
		}
		// TODO - make this more generic and implement it globally
		if (tagType.equals("b") && ((JAMWikiLexer)lexer).peekTag().getTagType().equals("i")) {
			// since Mediawiki syntax unfortunately chose to use the same character
			// for bold and italic ('' and '''), see if the syntax is of the form
			// '''''bold''' then italic'', in which case the current stack contains
			// "b" followed by "i" when it should be the reverse.
			JFlexTagItem grandparent = ((JAMWikiLexer)lexer).peekTag(2);
			if (grandparent != null && grandparent.getTagType().equals("b")) {
				// swap the tag types and close the current tag
				grandparent.changeTagType("i");
				((JAMWikiLexer)lexer).peekTag().changeTagType("b");
				((JAMWikiLexer)lexer).popTag(tagType);
				return;
			}
		}
		// push the new tag onto the stack
		((JAMWikiLexer)lexer).pushTag(tagType, null);
	}
}


text:
<?php

namespace Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness;

/**
 * Class MovieTheater
 *
 * @author      AppBels <app.bels@gmail.com>
 * @name        MovieTheater
 * @namespace   Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness
 * @package     Org\Schema
 * @see         https://schema.org/MovieTheater
 * Date         03/04/2017
 */
class MovieTheater extends \Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness
{

	/**
	 * The number of screens in the movie theater.
	 * @access	public
	 * @var		int
	 */
	public $screenCount;

	/**
	 * MovieTheater constructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness::__construct()
	 */
	public function __construct ()
	{
		parent::__construct();
	}

	/**
	 * MovieTheater toString.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness::__toString()
	 *
	 * @return  string
	 */
	public function __toString ()
	{
		return parent::__toString();
	}

	/**
	 * MovieTheater destructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness\EntertainmentBusiness::__destruct()
	 */
	public function __destruct ()
	{
		parent::__destruct();
	}

}

?>


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

<TITLE>
WS.WSImpl (Play! API)
</TITLE>

<META NAME="date" CONTENT="2010-11-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

play.libs

Interface WS.WSImpl

All Known Implementing Classes:
WSAsync, WSUrlFetch

Enclosing class:
WS

public static interface WS.WSImpl

Method Summary

 WS.WSRequest
newRequest(java.lang.String url)

 void
stop()

Method Detail

newRequest

WS.WSRequest newRequest(java.lang.String url)

stop

void stop()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Guillaume Bort & zenexity - Distributed under Apache 2 licence, without any warrantly


text:
spike/
======

A place for code that doesn't belong in the library,
but you aren't quite ready to throw away either.


text:
<!DOCTYPE html>
<html lang="en">
  <head>
    <base href="http://mcastillo_macbook.dev.symphono.com/MortarJS/"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>MortarJs</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Jamsine Runner">
    <meta name="author" content="Miguel Castillo">

    <link rel="shortcut icon" type="image/png" href="tests/lib/jasmine-2.0.0/jasmine_favicon.png">
    <link rel="stylesheet" type="text/css" href="tests/lib/jasmine-2.0.0/jasmine.css">

    <script src="tests/lib/requirejs/require.js"></script>
    <script>
      // Configure requirejs all the tests are going to get their resources from
      require.config({
        "paths": {
          "underscore": "tests/lib/underscore/underscore",
          "jquery": "tests/lib/jquery/dist/jquery",
          "rjasmine": "tests/lib/rjasmine/dist/rjasmine-debug"
        },
        "shim": {
          "rjasmine": ["jquery", "underscore"],
          "underscore": {
            "exports": "_"
          }
        }
      });
    </script>
  </head>

  <body>
    <script>
      // Load up rjasmine
      require(["rjasmine"], function (RJasmine) {
        // Create instance of jasmine
        var rjasmine = new RJasmine({
          reporters: {
            console: true,
            html: true
          }
        });

        // Make api global and jasmine itself so that reporters can have an easy
        // way to register themeselves
        RJasmine.extend(window, rjasmine._api);
        window.jasmine = RJasmine.jasmine;

        rjasmine.ready(function() {
          require([
            "tests/specs/promise",
            "tests/specs/extender",
            "tests/specs/view",
            "tests/specs/tmpl",
            "tests/specs/model",
            "tests/specs/module",
            "tests/specs/url",
            "tests/specs/utils"
          ], rjasmine.execute);
        });
      });
    </script>
  </body>
</html>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Bowling Game - Coding Examplar">
    <meta name="author" content="Michael J. Burgess <micahel@mjburgess.co.uk>">

    <title>Bowling</title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>
            Bowling

Home

About

A Bowling Game

by Michael J. Burgess (michael@mjburgess.co.uk)


text:
package com.eldhelm.samsung.iap.function;

import java.util.ArrayList;

import android.os.Bundle;

import com.adobe.fre.FREArray;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;

import com.adobe.fre.FREObject;
import com.eldhelm.samsung.iap.InAppExtensionContext;
import com.eldhelm.samsung.iap.data.FREIapItem;

import com.sec.android.iap.IAPConnector;

public class GetItemListFunction implements FREFunction {

	@Override
	public FREObject call(FREContext arg0, FREObject[] arg1) {
		InAppExtensionContext frecontext = (InAppExtensionContext) arg0;
		IAPConnector mIAPConnector = frecontext.mIAPConnector;

		FREArray itemList = null;
		try {
			itemList = FREArray.newArray(FREIapItem.CLASS_NAME, 0, false);
		} catch (Exception e) {
			frecontext.sendException(e);
		}

		String _itemGroupId = null;
		int _startNum = 0;
		int _endNum = 0;
		String _itemType = null;

		try {
			_itemGroupId = arg1[0].getAsString();
			_startNum = arg1[1].getAsInt();
			_endNum = arg1[2].getAsInt();
			_itemType = arg1[3].getAsString();
		} catch (Exception e) {
			frecontext.sendException(e);
		}

		try {
			int mode = InAppExtensionContext.mMode;
			String packageName = frecontext.getActivity().getPackageName();

			frecontext.sendWarning("Calling getItemList:" + mode + ";"
					+ packageName + ";" + _itemGroupId + ";" + _startNum + ";"
					+ _endNum + ";" + _itemType);

			Bundle bundle = mIAPConnector.getItemList(mode, packageName,
					_itemGroupId, _startNum, _endNum, _itemType);

			if (null != bundle) {
				int statusCode = bundle.getInt("STATUS_CODE");

				if (statusCode == 0) {
					ArrayList<String> arrayList = bundle
							.getStringArrayList("RESULT_LIST");

					int i = 0;
					for (String itemString : arrayList) {
						itemList.setObjectAt(i++, new FREIapItem(itemString));
					}
				} else if (statusCode == -1001) {
					frecontext.updatePakcage(bundle);
				} else {
					frecontext.sendError("getItemList " + statusCode);
				}

			} else {
				frecontext.sendError("getItemList bundle is null");
			}

		} catch (Exception e) {
			frecontext.sendException(e);
		}

		return itemList;
	}

}


text:
namespace SlimMessageBus.Host.FluentValidation;

using global::FluentValidation;
using SlimMessageBus;
using SlimMessageBus.Host.Interceptor;

public class HandlerValidationInterceptor<T, R> : AbstractValidationInterceptor<T>, IRequestHandlerInterceptor<T, R>
{
    public HandlerValidationInterceptor(IEnumerable<IValidator<T>> validators, IValidationErrorsHandler errorsHandler = null)
        : base(validators, errorsHandler)
    {
    }

    public async Task<R> OnHandle(T message, Func<Task<R>> next, IConsumerContext context)
    {
        await OnValidate(message, context.CancellationToken).ConfigureAwait(false);
        return await next().ConfigureAwait(false);
    }
}


text:
<?php
namespace Edu\EleraningBundle\Form\Type;
use Symfony\Component\Form\FormBuilderInterface;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder
            ->add('fname',null,array("label"=>"نام"))
            ->add('lname',null,array("label"=>"نام خانوادگی"))
            ->add('phone',null,array("label"=>"تلفن"))
            ->add('melicode',null,array("label"=>"کدملی"))
            ->add('university',null,array("label"=>"دانشگاه",'property' => 'name','required'=>true))
        ;
    }

    public function getName()
    {
        return 'edu_user_registration';
    }
}


text:
ContentDownloader::ContentDownloader(QObject *parent)
    : QObject(parent),
      m_maximumWorkers(3),
      m_networkManager(parent)
{
    qRegisterMetaType<std::string>();
    qRegisterMetaType<Tangram::UrlCallback>();
    connect(this, SIGNAL(addTask(std::string,Tangram::UrlCallback)), this, SLOT(queueTask(std::string,Tangram::UrlCallback)));
    connect(this, SIGNAL(cancelTask(std::string)), this, SLOT(onTaskCanceled(std::string)));
    connect(this, SIGNAL(finishTasks()), this, SLOT(onTasksFinished()));
}

void ContentDownloader::queueTask(const std::string &url, const Tangram::UrlCallback &callback)
{
    std::shared_ptr<DownloadTask> task(new DownloadTask{url, callback});
    m_taskQueue.enqueue(task);
    processQueue();
}

void ContentDownloader::processQueue()
{
    while (!m_taskQueue.isEmpty() && m_replies.count() < m_maximumWorkers) {
        auto task = m_taskQueue.dequeue();
        QNetworkRequest request(QUrl(QString::fromStdString(task->url)));
        QNetworkReply *reply = m_networkManager.get(request);
        connect(reply, SIGNAL(finished()), this, SLOT(processReply()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(processError(QNetworkReply::NetworkError)));
        m_replies.insert(reply, task);
    }
}

void ContentDownloader::processError(QNetworkReply::NetworkError error)
{
    if (error != QNetworkReply::OperationCanceledError)
        qDebug() << Q_FUNC_INFO << error;
    auto *reply = qobject_cast<QNetworkReply *>(sender());
    m_replies.remove(reply);
    reply->deleteLater();
}

void ContentDownloader::onTaskCanceled(const std::string &url)
{
    for (int i = 0; i < m_taskQueue.count(); ++i) {
        if (m_taskQueue.at(i)->url == url) {
            m_taskQueue.removeAt(i);
            return;
        }
    }

    for (auto *reply : m_replies.keys()) {
        auto task = m_replies.value(reply);
        if (task->url == url) {
            m_replies.remove(reply);
            reply->abort();
            reply->deleteLater();
            return;
        }
    }
}

void ContentDownloader::onTasksFinished()
{
    m_taskQueue.clear();
    for (auto *reply : m_replies.keys()) {
        reply->abort();
        reply->deleteLater();
    }

    m_replies.clear();
}

void ContentDownloader::setMaximumWorkers(int maximumWorkers)
{
    m_maximumWorkers = maximumWorkers;
}

int ContentDownloader::maximumWorkers()
{
    return m_maximumWorkers;
}

void ContentDownloader::processReply()
{
    auto *reply = qobject_cast<QNetworkReply *>(sender());

    if (m_replies.contains(reply)) {
        auto task = m_replies.value(reply);
        m_replies.remove(reply);

        QByteArray bytes = reply->readAll();
        std::vector<char> content(bytes.begin(), bytes.end());
        task->callback(std::move(content));
    }

    if (reply)
        reply->deleteLater();
    processQueue();
}


text:
namespace FreeImageAPI
{
	/// <summary>
	/// Dithering algorithms.
	/// Constants used in FreeImage_Dither.
	/// </summary>
	public enum FREE_IMAGE_DITHER
	{
		/// <summary>
		/// Floyd and Steinberg error diffusion
		/// </summary>
		FID_FS = 0,
		/// <summary>
		/// Bayer ordered dispersed dot dithering (order 2 dithering matrix)
		/// </summary>
		FID_BAYER4x4 = 1,
		/// <summary>
		/// Bayer ordered dispersed dot dithering (order 3 dithering matrix)
		/// </summary>
		FID_BAYER8x8 = 2,
		/// <summary>
		/// Ordered clustered dot dithering (order 3 - 6x6 matrix)
		/// </summary>
		FID_CLUSTER6x6 = 3,
		/// <summary>
		/// Ordered clustered dot dithering (order 4 - 8x8 matrix)
		/// </summary>
		FID_CLUSTER8x8 = 4,
		/// <summary>
		/// Ordered clustered dot dithering (order 8 - 16x16 matrix)
		/// </summary>
		FID_CLUSTER16x16 = 5,
		/// <summary>
		/// Bayer ordered dispersed dot dithering (order 4 dithering matrix)
		/// </summary>
		FID_BAYER16x16 = 6
	}
}


text:
package org.docksidestage.sqlite.dbflute.readonly.cbean.nss;

import org.docksidestage.sqlite.dbflute.readonly.cbean.cq.RoyMemberWithdrawalCQ;

/**
 * The nest select set-upper of MEMBER_WITHDRAWAL.
 * @author DBFlute(AutoGenerator)
 */
public class RoyMemberWithdrawalNss {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected final RoyMemberWithdrawalCQ _query;
    public RoyMemberWithdrawalNss(RoyMemberWithdrawalCQ query) { _query = query; }
    public boolean hasConditionQuery() { return _query != null; }

    // ===================================================================================
    //                                                                     Nested Relation
    //                                                                     ===============
    /**
     * With nested relation columns to select clause.

     * MEMBER by my MEMBER_ID, named 'member'.
     * @return The set-upper of more nested relation. {...with[nested-relation].with[more-nested-relation]} (NotNull)
     */
    public RoyMemberNss withMember() {
        _query.xdoNss(() -> _query.queryMember());
        return new RoyMemberNss(_query.queryMember());
    }
    /**
     * With nested relation columns to select clause.

     * WITHDRAWAL_REASON by my WITHDRAWAL_REASON_CODE, named 'withdrawalReason'.
     */
    public void withWithdrawalReason() {
        _query.xdoNss(() -> _query.queryWithdrawalReason());
    }
}


text:
namespace text_file_loader
{
	void write(const service_ptr_t<file> & p_file,abort_callback & p_abort,const char * p_string,bool is_utf8);
	void read(const service_ptr_t<file> & p_file,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8);

	void write(const char * p_path,abort_callback & p_abort,const char * p_string,bool is_utf8);
	void read(const char * p_path,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8);

};