text:
/**
 * @fileoverview Date input field.
 * @author pkendall64@gmail.com (Paul Kendall)
 */
'use strict';

goog.provide('Blockly.FieldDate');

goog.require('Blockly.Field');
goog.require('goog.date');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.ui.DatePicker');
goog.require('goog.style');
goog.require('goog.i18n.DateTimeSymbols');
goog.require('goog.i18n.DateTimeSymbols_he');

/**
 * Class for a date input field.
 * @param {string} date The initial date.
 * @param {Function} opt_changeHandler A function that is executed when a new
 *     date is selected.  Its sole argument is the new date value.  Its
 *     return value becomes the selected date, unless it is undefined, in
 *     which case the new date stands, or it is null, in which case the change
 *     is aborted.
 * @extends {Blockly.Field}
 * @constructor
 */
Blockly.FieldDate = function(date, opt_changeHandler) {
  if (!date) {
    date = new goog.date.Date().toIsoString(true);
  }
  Blockly.FieldDate.superClass_.constructor.call(this, date);
  this.setValue(date);
  this.setChangeHandler(opt_changeHandler);
};
goog.inherits(Blockly.FieldDate, Blockly.Field);

/**
 * Clone this FieldDate.
 * @return {!Blockly.FieldDate} The result of calling the constructor again
 *   with the current values of the arguments used during construction.
 */
Blockly.FieldDate.prototype.clone = function() {
  return new Blockly.FieldDate(this.getValue(), this.changeHandler_);
};

/**
 * Mouse cursor style when over the hotspot that initiates the editor.
 */
Blockly.FieldDate.prototype.CURSOR = 'text';

/**
 * Close the colour picker if this input is being deleted.
 */
Blockly.FieldDate.prototype.dispose = function() {
  Blockly.WidgetDiv.hideIfOwner(this);
  Blockly.FieldDate.superClass_.dispose.call(this);
};

/**
 * Return the current date.
 * @return {string} Current date.
 */
Blockly.FieldDate.prototype.getValue = function() {
  return this.date_;
};

/**
 * Set the date.
 * @param {string} date The new date.
 */
Blockly.FieldDate.prototype.setValue = function(date) {
  if (this.sourceBlock_ && this.changeHandler_) {
    var validated = this.changeHandler_(date);
    // If the new date is invalid, validation returns null.
    // In this case we still want to display the illegal result.
    if (validated !== null && validated !== undefined) {
      date = validated;
    }
  }
  this.date_ = date;
  Blockly.Field.prototype.setText.call(this, date);
};

/**
 * Create a date picker under the date field.
 * @private
 */
Blockly.FieldDate.prototype.showEditor_ = function() {
  Blockly.WidgetDiv.show(this, this.sourceBlock_.RTL,
      Blockly.FieldDate.widgetDispose_);
  // Create the date picker using Closure.
  Blockly.FieldDate.loadLanguage_();
  var picker = new goog.ui.DatePicker();
  picker.setAllowNone(false);
  picker.setShowWeekNum(false);

  // Position the picker to line up with the field.
  // Record windowSize and scrollOffset before adding the picker.
  var windowSize = goog.dom.getViewportSize();
  var scrollOffset = goog.style.getViewportPageOffset(document);
  var xy = this.getAbsoluteXY_();
  var borderBBox = this.borderRect_.getBBox();
  var div = Blockly.WidgetDiv.DIV;
  picker.render(div);
  picker.setDate(goog.date.fromIsoString(this.getValue()));
  // Record pickerSize after adding the date picker.
  var pickerSize = goog.style.getSize(picker.getElement());

  // Flip the picker vertically if off the bottom.
  if (xy.y + pickerSize.height + borderBBox.height >=
      windowSize.height + scrollOffset.y) {
    xy.y -= pickerSize.height - 1;
  } else {
    xy.y += borderBBox.height - 1;
  }
  if (this.sourceBlock_.RTL) {
    xy.x += borderBBox.width;
    xy.x -= pickerSize.width;
    // Don't go offscreen left.
    if (xy.x < scrollOffset.x) {
      xy.x = scrollOffset.x;
    }
  } else {
    // Don't go offscreen right.
    if (xy.x > windowSize.width + scrollOffset.x - pickerSize.width) {
      xy.x = windowSize.width + scrollOffset.x - pickerSize.width;
    }
  }
  Blockly.WidgetDiv.position(xy.x, xy.y, windowSize, scrollOffset,
                             this.sourceBlock_.RTL);

  // Configure event handler.
  var thisField = this;
  Blockly.FieldDate.changeEventKey_ = goog.events.listen(picker,
      goog.ui.DatePicker.Events.CHANGE,
      function(event) {
        var date = event.date ? event.date.toIsoString(true) : '';
        Blockly.WidgetDiv.hide();
        if (thisField.sourceBlock_ && thisField.changeHandler_) {
          // Call any change handler, and allow it to override.
          var override = thisField.changeHandler_(date);
          if (override !== undefined) {
            date = override;
          }
        }
        thisField.setValue(date);
      });
};

/**
 * Hide the date picker.
 * @private
 */
Blockly.FieldDate.widgetDispose_ = function() {
  if (Blockly.FieldDate.changeEventKey_) {
    goog.events.unlistenByKey(Blockly.FieldDate.changeEventKey_);
  }
};

/**
 * Load the best language pack by scanning the Blockly.Msg object for a
 * language that matches the available languages in Closure.
 * @private
 */
Blockly.FieldDate.loadLanguage_ = function() {
  var reg = /^DateTimeSymbols_(.+)$/;
  for (var prop in goog.i18n) {
    var m = prop.match(reg);
    if (m) {
      var lang = m[1].toLowerCase().replace('_', '.');  // E.g. 'pt.br'
      if (goog.getObjectByName(lang, Blockly.Msg)) {
        goog.i18n.DateTimeSymbols = goog.i18n[prop];
      }
    }
  }
};


text:
package com.wxxr.nirvana.workbench.config;

import com.wxxr.nirvana.platform.IExtension;
import com.wxxr.nirvana.platform.IExtensionDelta;
import com.wxxr.nirvana.platform.IExtensionPoint;
import com.wxxr.nirvana.platform.IPlatform;
import com.wxxr.nirvana.platform.IPluginDescriptor;
import com.wxxr.nirvana.platform.IRegistryChangeEvent;
import com.wxxr.nirvana.platform.IRegistryChangeListener;
import com.wxxr.nirvana.platform.PlatformLocator;

/**
 * @author fudapeng
 *
 */
public abstract class BaseExtensionPointManager implements
		IRegistryChangeListener {

	protected String namespace;
	protected String extensionPointId;

	public BaseExtensionPointManager(String namespace, String extensionPointId) {
		if ((namespace == null) || (extensionPointId == null)) {
			throw new IllegalArgumentException();
		}
		this.namespace = namespace;
		this.extensionPointId = extensionPointId;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.wxxr.web.platform.core.IRegistryChangeListener#registryChanged(com
	 * .wxxr.web.platform.core.IRegistryChangeEvent)
	 */
	public void registryChanged(IRegistryChangeEvent event) {
		if (event == null) {
			return;
		}
		IExtensionDelta[] deltas = event.getExtensionDeltas(namespace,
				extensionPointId);
		IExtension ext = null;
		for (int i = 0; i < deltas.length; i++) {
			IExtensionDelta delta = deltas[i];
			if (delta != null) {
				switch (delta.getKind()) {
				case IExtensionDelta.ADDED:
					ext = delta.getExtension();
					processExtensionAdded(ext);
					break;
				case IExtensionDelta.REMOVED:
					ext = delta.getExtension();
					processExtensionRemoved(ext);
				}
			}
		}
	}

	public void start() {
		IPlatform platform = getUIPlatform();
		IExtensionPoint point = platform.getExtensionRegistry()
				.getExtensionPoint(namespace, extensionPointId);
		IExtension[] extensions = point.getExtensions();
		for (int i = 0; i < extensions.length; i++) {
			IExtension ext = extensions[i];
			if (ext != null) {
				processExtensionAdded(ext);
			}
		}
		getUIPlatform().getExtensionRegistry().addRegistryChangeListener(this,
				namespace);
	}

	public void stop() {
		getUIPlatform().getExtensionRegistry().removeRegistryChangeListener(
				this);
	}

	protected IPlatform getUIPlatform() {
		return PlatformLocator.getPlatform();
	}

	protected abstract void processExtensionRemoved(IExtension ext);

	protected abstract void processExtensionAdded(IExtension ext);

	protected Object createPluginObject(String clazz, IPluginDescriptor plugin)
			throws Exception {
		return PlatformLocator.getPlatform().createPluginObject(plugin, clazz,
				null);
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Treton.Core.Resources
{
	public interface IResourceLoaders
	{
		void Add(uint type, ILoader loader);
		void Remove(uint type);
		ILoader Get(uint type);
	}

	public class ResourceLoaders : IResourceLoaders
	{
		private readonly Dictionary<uint, ILoader> _loaders = new Dictionary<uint, ILoader>();

		public void Add(uint type, ILoader loader)
		{
			_loaders.Add(type, loader);
		}

		public void Remove(uint type)
		{
			_loaders.Remove(type);
		}

		public ILoader Get(uint type)
		{
			return _loaders[type];
		}
	}
}


text:
@interface XYQMovieTool ()
@property (nonatomic,strong) MPMoviePlayerController *moviePlayer;//视频播放控制器
@property (nonatomic,strong) MPMoviePlayerViewController *moviePlayerViewController;//播放器视图控制器
@end

@implementation XYQMovieTool

#pragma mark - 单例
+ (XYQMovieTool *)sharedManager
{
    static XYQMovieTool *Instance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        Instance = [[self alloc] init];
    });
    return Instance;
}

#pragma mark - 注册通知
-(void)addNotifitionByPush{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerThumbnailRequestFinished:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayer];
}
-(void)addNotifitionByPresent{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.moviePlayerViewController.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.moviePlayerViewController.moviePlayer];
    [notificationCenter addObserver:self selector:@selector(mediaPlayerThumbnailRequestFinished:) name:MPMoviePlayerThumbnailImageRequestDidFinishNotification object:self.moviePlayerViewController.moviePlayer];
}

#pragma mark - push播放本地视频
+(void)pushPlayMovieWithLocalURL:(NSString *)localURL viewController:(UIViewController *)containViewController{

    //实例化
    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];

    //保证每次点击都重新创建视频播放控制器视图,避免再次点击时由于不播放的问题
    movieTool.moviePlayer = nil;

    //地址
    NSURL *url = [NSURL fileURLWithPath:localURL];

    //播放器
    movieTool.moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
    movieTool.moviePlayer.view.frame = containViewController.view.bounds;
    movieTool.moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [containViewController.view addSubview:movieTool.moviePlayer.view];

    //注册通知
    [movieTool addNotifitionByPush];

    //开始播放
    [movieTool.moviePlayer prepareToPlay];
    [movieTool.moviePlayer play];
}

#pragma mark - push播放网络视频
+(void)pushPlayMovieWithNetURL:(NSString *)netWorkURL viewController:(UIViewController *)containViewController{

    //实例化
    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];

    //保证每次点击都重新创建视频播放控制器视图,避免再次点击时由于不播放的问题
    movieTool.moviePlayer = nil;

    //地址
    netWorkURL = [netWorkURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:netWorkURL];

    //播放器
    movieTool.moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
    movieTool.moviePlayer.view.frame = containViewController.view.bounds;
    movieTool.moviePlayer.view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [containViewController.view addSubview:movieTool.moviePlayer.view];

    //注册通知
    [movieTool addNotifitionByPush];

    //开始播放
    [movieTool.moviePlayer prepareToPlay];
    [movieTool.moviePlayer play];
}

#pragma mark - present播放本地视频
+(void)presentPlayMovieWithLocalURL:(NSString *)localURL viewController:(UIViewController *)containViewController{

    //实例化
    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];

    //保证每次点击都重新创建视频播放控制器视图,避免再次点击时由于不播放的问题
    movieTool.moviePlayerViewController = nil;

    //地址
    NSURL *url = [NSURL fileURLWithPath:localURL];

    //播放器
    movieTool.moviePlayerViewController = [[MPMoviePlayerViewController alloc]initWithContentURL:url];

    //注册通知
    [movieTool addNotifitionByPresent];

    //开始播放
    [containViewController presentMoviePlayerViewControllerAnimated:movieTool.moviePlayerViewController];
    [movieTool.moviePlayerViewController.moviePlayer prepareToPlay];
    [movieTool.moviePlayerViewController.moviePlayer play];
}

#pragma mark - present播放网络视频
+(void)presentPlayMovieWithNetURL:(NSString *)netWorkURL viewController:(UIViewController *)containViewController{

    //实例化
    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];

    //保证每次点击都重新创建视频播放控制器视图,避免再次点击时由于不播放的问题
    movieTool.moviePlayerViewController = nil;

    //地址
    netWorkURL = [netWorkURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:netWorkURL];

    //播放器
    movieTool.moviePlayerViewController = [[MPMoviePlayerViewController alloc]initWithContentURL:url];

    //注册通知
    [movieTool addNotifitionByPresent];

    //开始播放
    [containViewController presentMoviePlayerViewControllerAnimated:movieTool.moviePlayerViewController];
    [movieTool.moviePlayerViewController.moviePlayer prepareToPlay];
    [movieTool.moviePlayerViewController.moviePlayer play];
}

#pragma mark - 获取视频截图
+(void)thumbnailImageRequestWithTimes:(NSArray *)timesArr{

    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];
    if (movieTool.moviePlayer) {
       [movieTool.moviePlayer requestThumbnailImagesAtTimes:timesArr timeOption:MPMovieTimeOptionNearestKeyFrame];
    }
    if (movieTool.moviePlayerViewController) {
        [movieTool.moviePlayerViewController.moviePlayer requestThumbnailImagesAtTimes:timesArr timeOption:MPMovieTimeOptionNearestKeyFrame];
    }
}

#pragma mark - 取消播放并移除所有通知监控
+(void)cancelPlay{

    XYQMovieTool *movieTool = [XYQMovieTool sharedManager];
    if (movieTool.moviePlayer) {
        [movieTool.moviePlayer stop];
        movieTool.moviePlayer = nil;
    }
    if (movieTool.moviePlayerViewController) {
        [movieTool.moviePlayerViewController.moviePlayer stop];
        [movieTool.moviePlayerViewController dismissMoviePlayerViewControllerAnimated];
        movieTool.moviePlayerViewController = nil;
    }

    //移除所有通知监控
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    movieTool = nil;
}

#pragma mark - 播放状态改变,注意播放完成时的状态是暂停
-(void)mediaPlayerPlaybackStateChange:(NSNotification *)notification{
    if (self.moviePlayer) {
        switch (self.moviePlayer.playbackState) {
            case MPMoviePlaybackStatePlaying:
                NSLog(@"moviePlayer:正在播放...");
                break;
            case MPMoviePlaybackStatePaused:
                NSLog(@"moviePlayer:暂停播放...");
                break;
            case MPMoviePlaybackStateStopped:
                NSLog(@"moviePlayer:停止播放...");
                break;
            default:
                NSLog(@"moviePlayer:播放状态:%ld",(long)self.moviePlayer.playbackState);
                break;
        }
    }
    if (self.moviePlayerViewController) {
        switch (self.moviePlayerViewController.moviePlayer.playbackState) {
            case MPMoviePlaybackStatePlaying:
                NSLog(@"moviePlayerViewController:正在播放...");
                break;
            case MPMoviePlaybackStatePaused:
                NSLog(@"moviePlayerViewController:暂停播放...");
                break;
            case MPMoviePlaybackStateStopped:
                NSLog(@"moviePlayerViewController:停止播放...");
                break;
            default:
                NSLog(@"moviePlayerViewController:播放状态:%ld",(long)self.moviePlayerViewController.moviePlayer.playbackState);
                break;
        }
    }
}

#pragma mark - 播放完成
-(void)mediaPlayerPlaybackFinished:(NSNotification *)notification{
    if (self.moviePlayer) {
       NSLog(@"moviePlayer:播放完成----%ld",(long)self.moviePlayer.playbackState);
    }
    if (self.moviePlayerViewController) {
        NSLog(@"moviePlayerViewController:播放完成----%ld",(long)self.moviePlayerViewController.moviePlayer.playbackState);
    }
}

#pragma mark - 缩略图请求完成,此方法每次截图成功都会调用一次
-(void)mediaPlayerThumbnailRequestFinished:(NSNotification *)notification{
    NSLog(@"视频截图完成...");

    UIImage *image=notification.userInfo[MPMoviePlayerThumbnailImageKey];

    //保存图片到相册(此处第一次调用会请求用户获得访问相册权限)
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}

#pragma mark - dealloc
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

#pragma clang diagnostic pop


text:
package quasar.physical.marklogic.xcc

import slamdata.Predef._
import quasar.effect.Capture

import com.marklogic.xcc._
import scalaz._, Scalaz._

object contentsource {
  def defaultSession[F[_]: Bind: Capture: CSourceReader]: F[Session] =
    newSession[F](None)

  def newSession[F[_]: Bind: Capture: CSourceReader](
    defaultRequestOptions: Option[RequestOptions]
  ): F[Session] =
    CSourceReader[F].ask >>= (cs => Capture[F].capture {
      val session = cs.newSession
      defaultRequestOptions foreach session.setDefaultRequestOptions
      session
    })
}


text:
module CZMQ
  module FFI

    # working with multipart messages
    class Zmsg
      class DestroyedError < RuntimeError; end

      # Boilerplate for self pointer, initializer, and finalizer
      class << self
        alias :__new :new
      end
      def initialize ptr, finalize=true
        @ptr = ptr
        if @ptr.null?
          @ptr = nil # Remove null pointers so we don't have to test for them.
        elsif finalize
          @finalizer = self.class.send :create_finalizer_for, @ptr
          ObjectSpace.define_finalizer self, @finalizer
        end
      end
      def self.create_finalizer_for ptr
        Proc.new do
          ptr_ptr = ::FFI::MemoryPointer.new :pointer
          ptr_ptr.write_pointer ptr
          ::CZMQ::FFI.zmsg_destroy ptr_ptr
        end
      end
      def null?
        !@ptr or ptr.null?
      end
      # Return internal pointer
      def __ptr
        raise DestroyedError unless @ptr
        @ptr
      end
      # Nullify internal pointer and return pointer pointer
      def __ptr_give_ref
        raise DestroyedError unless @ptr
        ptr_ptr = ::FFI::MemoryPointer.new :pointer
        ptr_ptr.write_pointer @ptr
        ObjectSpace.undefine_finalizer self if @finalizer
        @finalizer = nil
        @ptr = nil
        ptr_ptr
      end

      # Create a new empty message object
      def self.new
        ptr = ::CZMQ::FFI.zmsg_new

        __new ptr
      end

      # Destroy a message object and all frames it contains
      def destroy
        return unless @ptr
        self_p = __ptr_give_ref
        result = ::CZMQ::FFI.zmsg_destroy self_p
        result
      end

      # Receive message from socket, returns zmsg_t object or NULL if the recv
      # was interrupted. Does a blocking recv. If you want to not block then use
      # the zloop class or zmsg_recv_nowait or zmq_poll to check for socket input
      # before receiving.
      def self.recv source
        result = ::CZMQ::FFI.zmsg_recv source
        result = Zmsg.__new result, true
        result
      end

      # Send message to destination socket, and destroy the message after sending
      # it successfully. If the message has no frames, sends nothing but destroys
      # the message anyhow. Nullifies the caller's reference to the message (as
      # it is a destructor).
      def self.send self_p, dest
        self_p = self_p.__ptr_give_ref
        result = ::CZMQ::FFI.zmsg_send self_p, dest
        result
      end

      # Send message to destination socket as part of a multipart sequence, and
      # destroy the message after sending it successfully. Note that after a
      # zmsg_sendm, you must call zmsg_send or another method that sends a final
      # message part. If the message has no frames, sends nothing but destroys
      # the message anyhow. Nullifies the caller's reference to the message (as
      # it is a destructor).
      def self.sendm self_p, dest
        self_p = self_p.__ptr_give_ref
        result = ::CZMQ::FFI.zmsg_sendm self_p, dest
        result
      end

      # Return size of message, i.e. number of frames (0 or more).
      def size
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_size @ptr
        result
      end

      # Return total size of all frames in message.
      def content_size
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_content_size @ptr
        result
      end

      # Push frame to the front of the message, i.e. before all other frames.
      # Message takes ownership of frame, will destroy it when message is sent.
      # Returns 0 on success, -1 on error. Deprecates zmsg_push, which did not
      # nullify the caller's frame reference.
      def prepend frame_p
        raise DestroyedError unless @ptr
        frame_p = frame_p.__ptr_give_ref
        result = ::CZMQ::FFI.zmsg_prepend @ptr, frame_p
        result
      end

      # Add frame to the end of the message, i.e. after all other frames.
      # Message takes ownership of frame, will destroy it when message is sent.
      # Returns 0 on success. Deprecates zmsg_add, which did not nullify the
      # caller's frame reference.
      def append frame_p
        raise DestroyedError unless @ptr
        frame_p = frame_p.__ptr_give_ref
        result = ::CZMQ::FFI.zmsg_append @ptr, frame_p
        result
      end

      # Remove first frame from message, if any. Returns frame, or NULL.
      def pop
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_pop @ptr
        result = Zframe.__new result, true
        result
      end

      # Push block of memory to front of message, as a new frame.
      # Returns 0 on success, -1 on error.
      def pushmem src, size
        raise DestroyedError unless @ptr
        size = Integer(size)
        result = ::CZMQ::FFI.zmsg_pushmem @ptr, src, size
        result
      end

      # Add block of memory to the end of the message, as a new frame.
      # Returns 0 on success, -1 on error.
      def addmem src, size
        raise DestroyedError unless @ptr
        size = Integer(size)
        result = ::CZMQ::FFI.zmsg_addmem @ptr, src, size
        result
      end

      # Push string as new frame to front of message.
      # Returns 0 on success, -1 on error.
      def pushstr string
        raise DestroyedError unless @ptr
        string = String(string)
        result = ::CZMQ::FFI.zmsg_pushstr @ptr, string
        result
      end

      # Push string as new frame to end of message.
      # Returns 0 on success, -1 on error.
      def addstr string
        raise DestroyedError unless @ptr
        string = String(string)
        result = ::CZMQ::FFI.zmsg_addstr @ptr, string
        result
      end

      # Push formatted string as new frame to front of message.
      # Returns 0 on success, -1 on error.
      def pushstrf format, result
        raise DestroyedError unless @ptr
        format = String(format)
        result = ::CZMQ::FFI.zmsg_pushstrf @ptr, format, result
        result
      end

      # Push formatted string as new frame to end of message.
      # Returns 0 on success, -1 on error.
      def addstrf format, result
        raise DestroyedError unless @ptr
        format = String(format)
        result = ::CZMQ::FFI.zmsg_addstrf @ptr, format, result
        result
      end

      # Pop frame off front of message, return as fresh string. If there were
      # no more frames in the message, returns NULL.
      def popstr
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_popstr @ptr
        result
      end

      # Push encoded message as a new frame. Message takes ownership of
      # submessage, so the original is destroyed in this call. Returns 0 on
      # success, -1 on error.
      def addmsg msg_p
        raise DestroyedError unless @ptr
        msg_p = msg_p.__ptr_give_ref
        result = ::CZMQ::FFI.zmsg_addmsg @ptr, msg_p
        result
      end

      # Remove first submessage from message, if any. Returns zmsg_t, or NULL if
      # decoding was not succesfull.
      def popmsg
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_popmsg @ptr
        result = Zmsg.__new result, true
        result
      end

      # Remove specified frame from list, if present. Does not destroy frame.
      def remove frame
        raise DestroyedError unless @ptr
        frame = frame.__ptr if frame
        result = ::CZMQ::FFI.zmsg_remove @ptr, frame
        result
      end

      # Set cursor to first frame in message. Returns frame, or NULL, if the
      # message is empty. Use this to navigate the frames as a list.
      def first
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_first @ptr
        result = Zframe.__new result, false
        result
      end

      # Return the next frame. If there are no more frames, returns NULL. To move
      # to the first frame call zmsg_first(). Advances the cursor.
      def next
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_next @ptr
        result = Zframe.__new result, false
        result
      end

      # Return the last frame. If there are no frames, returns NULL.
      def last
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_last @ptr
        result = Zframe.__new result, false
        result
      end

      # Save message to an open file, return 0 if OK, else -1. The message is
      # saved as a series of frames, each with length and data. Note that the
      # file is NOT guaranteed to be portable between operating systems, not
      # versions of CZMQ. The file format is at present undocumented and liable
      # to arbitrary change.
      def save file
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_save @ptr, file
        result
      end

      # Load/append an open file into message, create new message if
      # null message provided. Returns NULL if the message could not
      # be loaded.
      def self.load self, file
        self = self.__ptr if self
        result = ::CZMQ::FFI.zmsg_load self, file
        result = Zmsg.__new result, true
        result
      end

      # Serialize multipart message to a single buffer. Use this method to send
      # structured messages across transports that do not support multipart data.
      # Allocates and returns a new buffer containing the serialized message.
      # To decode a serialized message buffer, use zmsg_decode ().
      def encode buffer
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_encode @ptr, buffer
        result
      end

      # Decodes a serialized message buffer created by zmsg_encode () and returns
      # a new zmsg_t object. Returns NULL if the buffer was badly formatted or
      # there was insufficient memory to work.
      def self.decode buffer, buffer_size
        buffer_size = Integer(buffer_size)
        result = ::CZMQ::FFI.zmsg_decode buffer, buffer_size
        result = Zmsg.__new result, true
        result
      end

      # Create copy of message, as new message object. Returns a fresh zmsg_t
      # object. If message is null, or memory was exhausted, returns null.
      def dup
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_dup @ptr
        result = Zmsg.__new result, true
        result
      end

      # Send message to zsys log sink (may be stdout, or system facility as
      # configured by zsys_set_logstream).
      def print
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_print @ptr
        result
      end

      # Return true if the two messages have the same number of frames and each
      # frame in the first message is identical to the corresponding frame in the
      # other message. As with zframe_eq, return false if either message is NULL.
      def eq other
        raise DestroyedError unless @ptr
        other = other.__ptr if other
        result = ::CZMQ::FFI.zmsg_eq @ptr, other
        result
      end

      # Generate a signal message encoding the given status. A signal is a short
      # message carrying a 1-byte success/failure code (by convention, 0 means
      # OK). Signals are encoded to be distinguishable from "normal" messages.
      def self.new_signal status
        result = ::CZMQ::FFI.zmsg_new_signal status
        result = Zmsg.__new result, true
        result
      end

      # Return signal value, 0 or greater, if message is a signal, -1 if not.
      def signal
        raise DestroyedError unless @ptr
        result = ::CZMQ::FFI.zmsg_signal @ptr
        result
      end

      # Probe the supplied object, and report if it looks like a zmsg_t.
      def self.is self
        result = ::CZMQ::FFI.zmsg_is self
        result
      end

      # Self test of this class
      def self.test verbose
        verbose = !(0==verbose||!verbose) # boolean
        result = ::CZMQ::FFI.zmsg_test verbose
        result
      end
    end

  end
end

################################################################################
#  THIS FILE IS 100% GENERATED BY ZPROJECT; DO NOT EDIT EXCEPT EXPERIMENTALLY  #
#  Please refer to the README for information about making permanent changes.  #
################################################################################


text:
package gov.nih.nci.evs.restapi.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.codec.binary.Base64;
import org.json.*;

/**
 * @author EVS Team
 * @version 1.0
 *
 * Modification history:
 *     Initial implementation kim.ong@ngc.com
 *
 */

public class OWLSPARQLUtilsExt {

	public static String verifyServiceUrl(String serviceUrl) {
		if (serviceUrl.indexOf("?query=?query=") != -1) {
			serviceUrl = serviceUrl.replace("?query=?query=", "?query=");
		} else if (serviceUrl.indexOf("?") == -1) {
			serviceUrl = serviceUrl + "?query=";
		}
		return serviceUrl;
	}

	public static HashMap getNameVersion2EndpointNamedGraphMap(String[] sparql_endpoints) {
		HashMap hmap = new HashMap();
		for (int i=0; i<sparql_endpoints.length; i++) {
			String sparql_endpoint = sparql_endpoints[i];
			sparql_endpoint = verifyServiceUrl(sparql_endpoint);
			//OWLSPARQLUtils owlSPARQLUtils = new OWLSPARQLUtils(sparql_endpoint + "?query=");
			OWLSPARQLUtils owlSPARQLUtils = new OWLSPARQLUtils(sparql_endpoint);
			HashMap sub_hmap = null;
			try {
				sub_hmap = owlSPARQLUtils.getNameVersion2NamedGraphMap();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (sub_hmap != null) {
				Iterator it = sub_hmap.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next(); //NameVersion
					Vector values = (Vector) sub_hmap.get(key);//namedgraphs
					if (values != null) {
						for (int k=0; k<values.size(); k++) {
							String namedgraph = (String) values.elementAt(k);
							Vector w = new Vector();
							if (hmap.containsKey(key)) {
								w = (Vector) hmap.get(key);
							}
							if (!w.contains(sparql_endpoint + "|" + namedgraph)) {
								w.add(sparql_endpoint + "|" + namedgraph);
							}
							hmap.put(key, w);
						}
					}
				}
			} else {
				System.out.println("owlSPARQLUtils.getNameVersion2NamedGraphMap() returns NULL???");
			}
		}
		return hmap;
	}

	public static String getLatestVersion(HashMap nameVersion2EndpointNamedGraphMap, String codingSchemeName) {
		if (nameVersion2EndpointNamedGraphMap == null) return null;
		Vector v = new Vector();
		Iterator it = nameVersion2EndpointNamedGraphMap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			if (key.startsWith(codingSchemeName + "|")) {
				v.add(key);
			}
		}
		if (v.size() > 0) {
			v = new SortUtils().quickSort(v);
		}

		if (v.size() >= 1) {
			String key = (String) v.elementAt(v.size()-1);
			Vector values = (Vector) nameVersion2EndpointNamedGraphMap.get(key);
			String value = null;
			if (values != null) {
				value = (String) values.elementAt(0);
			}
			Vector u = StringUtils.parseData(key, '|');
			//return key + "|" + value;
			return (String) u.elementAt(1);
	    } else {
			return null;
		}
	}

	public static Vector getSupportedCodingSchemesAndVersions(HashMap nameVersion2EndpointNamedGraphMap) {
		if (nameVersion2EndpointNamedGraphMap == null) return null;
		Vector v = new Vector();
		Iterator it = nameVersion2EndpointNamedGraphMap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			if (!v.contains(key)) {
				v.add(key);
			}
		}
		v = new SortUtils().quickSort(v);
        return v;
	}

	public static Vector getSupportedCodingSchemes(HashMap nameVersion2EndpointNamedGraphMap) {
		if (nameVersion2EndpointNamedGraphMap == null) return null;
		Vector v = new Vector();
		Iterator it =
		nameVersion2EndpointNamedGraphMap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			Vector u = StringUtils.parseData(key, '|');
			String codingScheme = (String) u.elementAt(0);
			if (!v.contains(codingScheme)) {
				v.add(codingScheme);
			}
		}
		v = new SortUtils().quickSort(v);
        return v;
	}

	public static String getPrefix(Vector prefix_vec, String codingSchemeName) {
		StringBuffer buf = new StringBuffer();
		for (int i=0; i<prefix_vec.size(); i++) {
			String t = (String) prefix_vec.elementAt(i);
			t = t.replaceAll("<", "<");
			t = t.replaceAll(">", ">");
			Vector u = StringUtils.parseData(t, '|');
			String key = (String) u.elementAt(0);
			if (key.compareTo("COMMON") == 0 || key.compareTo(codingSchemeName) == 0) {
				String value = (String) u.elementAt(1);
				buf.append(value).append("\n");
			}
		}
		return buf.toString();
	}

    public static HashMap getCodingSchemeNameVersion2OWLSPARQLUtilsMap(String[] sparql_endpoints) {
		return getCodingSchemeNameVersion2OWLSPARQLUtilsMap(sparql_endpoints, null);
	}

    public static HashMap getCodingSchemeNameVersion2OWLSPARQLUtilsMap(String[] sparql_endpoints, Vector prefix_vec) {
		HashMap OWLSPARQLUtilsMap = new HashMap();
		for (int i=0; i<sparql_endpoints.length; i++) {
			String sparql_endpoint = sparql_endpoints[i];
			System.out.println("SPARQL endpoint: " + sparql_endpoint);
			OWLSPARQLUtils owlSPARQLUtils = new OWLSPARQLUtils(sparql_endpoint);
			HashMap sub_hmap = null;
			try {
			    sub_hmap = owlSPARQLUtils.getNameVersion2NamedGraphMap();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (sub_hmap == null) {
				System.out.println("sub_hmap == null???");
			} else {
				Iterator it = sub_hmap.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
				    try {
						Vector u = StringUtils.parseData(key, '|');
						//NCI_Thesaurus|17.05e --> https://sparql-evs-stage.nci.nih.gov/sparql?query=|http://NCIt_Flattened
						String codingScheme = (String) u.elementAt(0);
						System.out.println("\tcodingScheme: " + codingScheme);
						String version = (String) u.elementAt(1);
						System.out.println("\tversion: " + version);
						Vector named_graphs = (Vector) sub_hmap.get(key);
						for (int k=0; k<named_graphs.size(); k++) {
							String named_graph = (String) named_graphs.elementAt(k);
							OWLSPARQLUtils sparql_util = new OWLSPARQLUtils(sparql_endpoint);
							sparql_util.set_named_graph(named_graph);
							String prefixes = null;
							if (prefix_vec != null) {
								prefixes = getPrefix(prefix_vec, codingScheme);
							} else {
								String uri = PrefixUtils.codingScheme2URI(codingScheme);
								prefixes = PrefixUtils.getPrefixes(uri);
							}
							sparql_util.set_prefixes(prefixes);
							String csnameversion = codingScheme + "|" + version;
							OWLSPARQLUtilsMap.put(csnameversion, sparql_util);

						}
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}
		}
		return OWLSPARQLUtilsMap;
	}

	public static void main(String[] args) {
		String[] sparql_endpoints = new String[1];
		sparql_endpoints[0] = args[0];//"https://sparql-evs-dev.nci.nih.gov/sparql";
		HashMap nameVersion2EndpointNamedGraphMap = OWLSPARQLUtilsExt.getNameVersion2EndpointNamedGraphMap(sparql_endpoints);
		Iterator it = nameVersion2EndpointNamedGraphMap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			System.out.println("key: " + key);
			Vector values = (Vector) nameVersion2EndpointNamedGraphMap.get(key);
			for (int k=0; k<values.size(); k++) {
				String value = (String) values.elementAt(k);
				System.out.println("\tEndpointNamedGraph: " + value);
			}
		}
		String codingSchemeName = "NCI_Thesaurus";
		String version = OWLSPARQLUtilsExt.getLatestVersion(nameVersion2EndpointNamedGraphMap, codingSchemeName);
		System.out.println("\nVocabulary: " + codingSchemeName);
		System.out.println("Latest version: " + version);

		Vector w = OWLSPARQLUtilsExt.getSupportedCodingSchemes(nameVersion2EndpointNamedGraphMap);
		for (int k=0; k<w.size(); k++) {
			String value = (String) w.elementAt(k);
			System.out.println("SupportedCodingSchemes: " + value);
		}

		w = OWLSPARQLUtilsExt.getSupportedCodingSchemesAndVersions(nameVersion2EndpointNamedGraphMap);
		for (int k=0; k<w.size(); k++) {
			String value = (String) w.elementAt(k);
			System.out.println("SupportedCodingSchemesAndVersion: " + value);
		}

		HashMap codingSchemeNameVersion2OWLSPARQLUtilsMap = OWLSPARQLUtilsExt.getCodingSchemeNameVersion2OWLSPARQLUtilsMap(sparql_endpoints);
		Iterator it2 = codingSchemeNameVersion2OWLSPARQLUtilsMap.keySet().iterator();
		while (it2.hasNext()) {
			String key = (String) it2.next();
			System.out.println("\tcodingSchemeNameVersion2OWLSPARQLUtilsMap key: " + key);
			OWLSPARQLUtils owlSPARQLUtils = (OWLSPARQLUtils) codingSchemeNameVersion2OWLSPARQLUtilsMap.get(key);
            String named_graph = owlSPARQLUtils.get_named_graph();
			System.out.println("\tOWLSPARQLUtils named_graph: " + named_graph);
			Vector w2 = owlSPARQLUtils.getTripleCount(named_graph);
			StringUtils.dumpVector("count", w2);
		}
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.compute.models;

import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingById;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsListingByResourceGroup;
import com.azure.resourcemanager.resources.fluentcore.collection.SupportsCreating;
import com.azure.resourcemanager.resources.fluentcore.collection.SupportsDeletingById;

/** Entry point to disk encryption set management API. */
public interface DiskEncryptionSets
    extends SupportsCreating<DiskEncryptionSet.DefinitionStages.Blank>,
        SupportsListingByResourceGroup<DiskEncryptionSet>,
        SupportsGettingByResourceGroup<DiskEncryptionSet>,
        SupportsGettingById<DiskEncryptionSet>,
        SupportsDeletingByResourceGroup,
        SupportsDeletingById {
}


text:
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { Schema as ApplicationOptions } from '../application/schema';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as AppShellOptions } from './schema';

describe('App Shell Schematic', () => {
  const schematicRunner = new SchematicTestRunner(
    '@schematics/angular',
    require.resolve('../collection.json'),
  );
  const defaultOptions: AppShellOptions = {
    project: 'bar',
  };

  const workspaceOptions: WorkspaceOptions = {
    name: 'workspace',
    newProjectRoot: 'projects',
    version: '6.0.0',
  };

  const appOptions: ApplicationOptions = {
    name: 'bar',
    inlineStyle: false,
    inlineTemplate: false,
    routing: true,
    skipTests: false,
    skipPackageJson: false,
  };
  let appTree: UnitTestTree;

  beforeEach(async () => {
    appTree = await schematicRunner.runSchematicAsync('workspace', workspaceOptions).toPromise();
    appTree = await schematicRunner
      .runSchematicAsync('application', appOptions, appTree)
      .toPromise();
  });

  it('should ensure the client app has a router-outlet', async () => {
    appTree = await schematicRunner.runSchematicAsync('workspace', workspaceOptions).toPromise();
    appTree = await schematicRunner
      .runSchematicAsync('application', { ...appOptions, routing: false }, appTree)
      .toPromise();
    await expectAsync(
      schematicRunner.runSchematicAsync('app-shell', defaultOptions, appTree).toPromise(),
    ).toBeRejected();
  });

  it('should add a universal app', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.server.module.ts';
    expect(tree.exists(filePath)).toEqual(true);
  });

  it('should add app shell configuration', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/angular.json';
    const content = tree.readContent(filePath);
    const workspace = JSON.parse(content);
    const target = workspace.projects.bar.architect['app-shell'];
    expect(target.options.route).toEqual('shell');
    expect(target.configurations.development.browserTarget).toEqual('bar:build:development');
    expect(target.configurations.development.serverTarget).toEqual('bar:server:development');
    expect(target.configurations.production.browserTarget).toEqual('bar:build:production');
    expect(target.configurations.production.serverTarget).toEqual('bar:server:production');
  });

  it('should add router module to client app module', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(/import { RouterModule } from '@angular\/router';/);
  });

  it('should not fail when AppModule have imported RouterModule already', async () => {
    const updateRecorder = appTree.beginUpdate('/projects/bar/src/app/app.module.ts');
    updateRecorder.insertLeft(0, "import { RouterModule } from '@angular/router';");
    appTree.commitUpdate(updateRecorder);

    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(/import { RouterModule } from '@angular\/router';/);
  });

  describe('Add router-outlet', () => {
    function makeInlineTemplate(tree: UnitTestTree, template?: string): void {
      template =
        template ||
        `
      <p>
        App works!
      </p>`;
      const newText = `
        import { Component, OnInit } from '@angular/core';

        @Component({
          selector: ''
          template: \`
            ${template}
          \`,
          styleUrls: ['./app.component.css']
        })
        export class AppComponent implements OnInit {

          constructor() { }

          ngOnInit() {
          }

        }

      `;
      tree.overwrite('/projects/bar/src/app/app.component.ts', newText);
      tree.delete('/projects/bar/src/app/app.component.html');
    }

    it('should not re-add the router outlet (external template)', async () => {
      const htmlPath = '/projects/bar/src/app/app.component.html';
      appTree.overwrite(htmlPath, '<router-outlet></router-outlet>');
      const tree = await schematicRunner
        .runSchematicAsync('app-shell', defaultOptions, appTree)
        .toPromise();

      const content = tree.readContent(htmlPath);
      const matches = content.match(/<router-outlet><\/router-outlet>/g);
      const numMatches = matches ? matches.length : 0;
      expect(numMatches).toEqual(1);
    });

    it('should not re-add the router outlet (inline template)', async () => {
      makeInlineTemplate(appTree, '<router-outlet></router-outlet>');
      const tree = await schematicRunner
        .runSchematicAsync('app-shell', defaultOptions, appTree)
        .toPromise();
      const content = tree.readContent('/projects/bar/src/app/app.component.ts');
      const matches = content.match(/<router-outlet><\/router-outlet>/g);
      const numMatches = matches ? matches.length : 0;
      expect(numMatches).toEqual(1);
    });
  });

  it('should add router imports to server module', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.server.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(/import { Routes, RouterModule } from '@angular\/router';/);
  });

  it('should work after adding nguniversal', async () => {
    let tree = await schematicRunner
      .runSchematicAsync('universal', defaultOptions, appTree)
      .toPromise();

    // change main tsconfig to mimic ng add for nguniveral
    const workspace = JSON.parse(appTree.readContent('/angular.json'));
    workspace.projects.bar.architect.server.options.main = 'server.ts';
    appTree.overwrite('angular.json', JSON.stringify(workspace, undefined, 2));

    tree = await schematicRunner.runSchematicAsync('app-shell', defaultOptions, tree).toPromise();
    const filePath = '/projects/bar/src/app/app.server.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(/import { Routes, RouterModule } from '@angular\/router';/);
  });

  it('should define a server route', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.server.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(/const routes: Routes = \[/);
  });

  it('should import RouterModule with forRoot', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    const filePath = '/projects/bar/src/app/app.server.module.ts';
    const content = tree.readContent(filePath);
    expect(content).toMatch(
      /const routes: Routes = \[ { path: 'shell', component: AppShellComponent }\];/,
    );
    expect(content).toMatch(/ServerModule,\r?\n\s*RouterModule\.forRoot\(routes\),/);
  });

  it('should create the shell component', async () => {
    const tree = await schematicRunner
      .runSchematicAsync('app-shell', defaultOptions, appTree)
      .toPromise();
    expect(tree.exists('/projects/bar/src/app/app-shell/app-shell.component.ts')).toBe(true);
    const content = tree.readContent('/projects/bar/src/app/app.server.module.ts');
    expect(content).toMatch(/app-shell\.component/);
  });
});


text:
import { Component, Input } from '@angular/core';
import { Item } from '../../item.model';

@Component({
  selector: 'item',
  templateUrl: 'item.html'
})
export class ItemComponent {
  @Input() item: Item;

  constructor() { }

  get name(){
    return this.item.name;
  }
  get description(){
    return this.item.description;
  }

  get totalQuantity(){
    return this.item.totalQuantity;
  }

  get weight(){
    return this.item.weight;
  }
}


text:
package net.orfjackal.dimdwarf.aop.conf;

import net.orfjackal.dimdwarf.aop.*;
import org.objectweb.asm.ClassVisitor;

public class AopTransformationChain extends AbstractTransformationChain {

    private final AopApi api;

    public AopTransformationChain(AopApi api) {
        this.api = api;
    }

    protected ClassVisitor getAdapters(ClassVisitor cv) {
        // the adapter declared last is processed first
        cv = new AddEqualsAndHashCodeMethodsForEntities(api, cv);
        cv = new AddMarkerInterfaceForEntities(api, cv);
        return cv;
    }
}


text:
'use strict';

angular.module('copayApp.controllers').controller('UnsupportedController',
  function($scope, $location) {
    if (localStorage && localStorage.length > 0) {
      $location.path('/');
    }
  }
);


text:
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
// This file is part of ModelBlocks. Copyright 2009, ModelBlocks developers. //
//                                                                           //
//    ModelBlocks is free software: you can redistribute it and/or modify    //
//    it under the terms of the GNU General Public License as published by   //
//    the Free Software Foundation, either version 3 of the License, or      //
//    (at your option) any later version.                                    //
//                                                                           //
//    ModelBlocks 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 General Public License for more details.                           //
//                                                                           //
//    You should have received a copy of the GNU General Public License      //
//    along with ModelBlocks.  If not, see <http://www.gnu.org/licenses/>.   //
//                                                                           //
//    ModelBlocks developers designate this particular file as subject to    //
//    the "Moses" exception as provided by ModelBlocks developers in         //
//    the LICENSE file that accompanies this code.                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#ifndef _NL_MIXTURE__
#define _NL_MIXTURE__

#include "nl-randvar.h"
#include "nl-list.h"

////////////////////////////////////////////////////////////////////////////////
//
//  Mixture Model
//
////////////////////////////////////////////////////////////////////////////////

template <template <class MY> class M,class Y,class C>
class Mixture2DModel : public Generic1DModel<Y,Prob> {
 private:
  // Static data members...
  static bool bModeled;
  // Data members...
  CPT1DModel<C,Prob>  mC;
  SimpleHash<C,M<Y> > mY_giv_C;
 public:
  Mixture2DModel ( )                 : mC()  { }
  Mixture2DModel ( const string& s ) : mC(s) { }
  // Specification methods...
  CPT1DModel<C,Prob>& setMixingModel ( ) { return mC; }
  Prob& setComponentProb  ( const C& c ) { return mC.setProb(c);       }
  M<Y>& setComponentModel ( const C& c ) { return mY_giv_C.set(c); }
  // Extraction methods...
  Prob        getComponentProb  ( const C& c ) { return mC.getProb(c);       }
  const M<Y>& getComponentModel ( const C& c ) { return mY_giv_C.get(c); }
  Prob getProb ( const Y& y ) const { Prob pr=0.0;
                                      C c; for ( bool b=c.setFirst(); b; b=c.setNext() )
                                             pr += ( mC.getProb(c) * mY_giv_C.get(c).getProb(y) );
                                      return pr; }
  // Input / output methods...
  bool readFields  ( char* as[], int numF )               { return ( mC.readFields(as,numF) || mY_giv_C.set(C(as[1])).readFields(as+1,numF-1) ); }
  void writeFields ( FILE* pf, string sPref )       const { mC.writeFields(pf,sPref);   C c; for ( bool b=c.setFirst(); b; b=c.setNext() )
                                                                                mY_giv_C.get(c).writeFields(pf,sPref+" "+c.getString()); }
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

template <template <class MY> class M,class Y,class X,class C>
class Mixture3DModel : public Generic2DModel<Y,X,Prob> {
 private:
  // Static data members...
  static bool bModeled;
  // Data members...
  CPT2DModel<C,X,Prob>             mC_giv_X;
  SimpleHash<Joint2DRV<X,C>,M<Y> > mY_giv_X_C;
 public:
  Mixture3DModel ( )                 : mC_giv_X()  { }
  Mixture3DModel ( const string& s ) : mC_giv_X(s) { }
  // Specification methods...
  Prob& setComponentProb  ( const X& x, const C& c ) { return mC_giv_X.setProb(c,x); }
  M<Y>& setComponentModel ( const X& x, const C& c ) { return mY_giv_X_C.set(Joint2DRV<X,C>(x,c)); }
  // Extraction methods...
  Prob getProb ( const Y& y, const X& x ) const { Prob pr=0.0;
                                                  C c; for ( bool b=c.setFirst(); b; b=c.setNext() )
                                                         pr += ( mC_giv_X.getProb(c,x) * mY_giv_X_C.get(Joint2DRV<X,C>(x,c)).getProb(y) );
                                                  return pr; }
  // Input / output methods...
  bool readFields  ( char* as[], int numF )     { return ( mC_giv_X.readFields(as,numF) || mY_giv_X_C.set(Joint2DRV<X,C>(X(as[1]),C(as[2]))).readFields(as+2,numF-2) ); }
  void writeFields ( FILE* pf, string sPref ) const { mC_giv_X.writeFields(pf,sPref);
                                                            X x; for ( bool bx=x.setFirst(); bx; bx=x.setNext() ) {
                                                                   C c; for ( bool b=c.setFirst(); b; b=c.setNext() ) {
                                                                          mY_giv_X_C.get(Joint2DRV<X,C>(x,c)).writeFields(pf,sPref+" "+c.getString()); } } }
};

////////////////////////////////////////////////////////////////////////////////
//
//  Trainable Mixture Model
//
////////////////////////////////////////////////////////////////////////////////

template <template <class MY> class M,class Y,class C>
class TrainableMixture2DModel : public Mixture2DModel<M,Y,C> {
// private:
//  LogPDFVal logpdfPrevDataAvg;
 public:
//  // Constructor / destructor methods...
//  TrainableMixture2DModel ( ) : logpdfPrevDataAvg(log(0.0)) { }
  // Specification methods...
  void updateFields ( const List<Joint2DRV<Y,Prob> >&, const PDFVal, bool& );
  void train        ( List<Joint2DRV<Y,Prob> >&, const int, const PDFVal );
};

////////////////////////////////////////
template <template <class MY> class M,class Y,class C>
void TrainableMixture2DModel<M,Y,C>::updateFields ( const List<Joint2DRV<Y,Prob> >& lyp, const PDFVal WEIGHT_LIMIT, bool& bShouldStop ) {
  LogPDFVal logpdfData = 0.0;
  CPT1DModel<C,Prob>                             mprPseudoEmpC;        // pseudo-empirical prob marginal
  SimpleHash<C,List<pair<const Y*,Prob> > >      alypPseudoEmpY_giv_C; // pseudo-empirical prob conditional

  //// E step: create pseudo-annotated (expectation) corpus by re-distributing empirical probabilities over C, according to model parameters...

  C c;
  for ( bool b=c.setFirst(); b; b=c.setNext() )
    setComponentModel(c).precomputeVarianceTerms();

  // For each Y...
  for ( const ListedObject<Joint2DRV<Y,Prob> >* pyp=lyp.getFirst(); pyp; pyp=lyp.getNext(pyp) ) {
    const Y&    y      = pyp->getSub1();  // data value
    const Prob& prEmpY = pyp->getSub2();  // empirical prob

    CPT1DModel<C,PDFVal> mpdfEstCY;      // model-estimated pdf
    PDFVal               pdfEstY = 0.0;  // model-estimated pdf marginal

    // For each C, compute model-estimated pdfs...
    C c; for ( bool b=c.setFirst(); b; b=c.setNext() ) {
      PDFVal pdfEstCY       = getComponentProb(c) * getComponentModel(c).getProb(y);
//      fprintf(stderr," ???%g %d %g\n",(double)pdfEstCY,(int)c,getComponentModel(c).getProb(y)); ////y.write(stderr); fprintf(stderr,"\n");
      mpdfEstCY.setProb(c)  = pdfEstCY;
      pdfEstY              += pdfEstCY;      // marginalize out C     (marginal estimated pdf of each y)
    }

    // Update total...
    logpdfData += log(pdfEstY); // product of each datum (joint estimated pdf of training corpus)
    //fprintf(stderr,"..%g %g\n",pdfEstY,logpdfData);

    // For each C, compute psuedo-empirical probs (model-estimated * empirical)...
    for ( bool b=c.setFirst(); b; b=c.setNext() ) {
      Prob prEstC_giv_Y                            = mpdfEstCY.getProb(c) / pdfEstY;   // so these are normalized distribs over C
      Prob prPseudoEmpCY                           = prEmpY * prEstC_giv_Y;
      alypPseudoEmpY_giv_C.set(c).add()            = pair<const Y*,Prob> ( &pyp->getSub1(), prPseudoEmpCY );
      mprPseudoEmpC.setProb(c)                    += prPseudoEmpCY;      // marginalize out Y
    }
  }
  // Renormalize sub-lists...
  for ( bool b=c.setFirst(); b; b=c.setNext() )
    for ( ListedObject<pair<const Y*,Prob> >* pyp=alypPseudoEmpY_giv_C.set(c).setFirst(); pyp; pyp=alypPseudoEmpY_giv_C.set(c).setNext(pyp) )
      pyp->second /= mprPseudoEmpC.getProb(c);

  //// M step: update model parameters using MLE (relative frequency estimation) on pseudo-annotated corpus...

  for ( bool b=c.setFirst(); b; b=c.setNext() ) {
    // If any change exceeds thresh, continue...
    if ( bShouldStop && ( getComponentProb(c)-mprPseudoEmpC.getProb(c) >  WEIGHT_LIMIT ||
                          getComponentProb(c)-mprPseudoEmpC.getProb(c) < -WEIGHT_LIMIT ) ) bShouldStop = false;
    // Update probs...
    setComponentProb(c)            = mprPseudoEmpC.getProb(c);
    setComponentModel(c).setFields ( alypPseudoEmpY_giv_C.get(c) );
    //////getComponentModel(c).writeFields(stderr,c.getString());
  }

  //////Mixture2DModel<M,Y,C>::writeFields(stderr,"");
  fprintf(stderr,"  log pdf data: %g\n",(double)logpdfData);
//  // Quit if total prob doesn't improve enough...
//  fprintf(stderr,"  log avg pdf: %g - %g < %g ORLY? %d\n",
//          (double)logpdfDataAvg,(double)logpdfPrevDataAvg,(double)WEIGHT_LIMIT,
//          ((logpdfDataAvg - logpdfPrevDataAvg) < WEIGHT_LIMIT)  );
//  bShouldStop = ( (logpdfDataAvg - logpdfPrevDataAvg) < WEIGHT_LIMIT );
//  logpdfPrevDataAvg = logpdfDataAvg;
}

////////////////////////////////////////
template <template <class MY> class M,class Y,class C>
void TrainableMixture2DModel<M,Y,C>::train ( List<Joint2DRV<Y,Prob> >& lyp, const int EPOCH_LIMIT, const PDFVal WEIGHT_LIMIT ) {

  // Normalize model...
  Mixture2DModel<M,Y,C>::setMixingModel().normalize();  // OUGHT NOT TO BE NECESSARY!!!

  // Normalize input...
  PDFVal pdfNorm = 0.0;
  for ( const ListedObject<Joint2DRV<Y,Prob> >* pyp=lyp.getFirst(); pyp; pyp=lyp.getNext(pyp) ) pdfNorm += pyp->getSub2();
  for ( ListedObject<Joint2DRV<Y,Prob> >*       pyp=lyp.setFirst(); pyp; pyp=lyp.setNext(pyp) ) pyp->setSub2() /= pdfNorm;

  // Iterate over each epoch...
  bool bShouldStop = true;
  for ( int epoch=0; epoch<EPOCH_LIMIT; epoch++ ) {
    fprintf(stderr,"---------- EPOCH %d/%d ----------\n",epoch,EPOCH_LIMIT);
    clock_t start = clock();
    updateFields ( lyp, WEIGHT_LIMIT, bShouldStop ) ;
    clock_t end = clock();
    fprintf ( stderr, "epoch time: %d ticks or %f seconds\n", end-start, ((double)end - start)/CLOCKS_PER_SEC ) ;
    if (bShouldStop) break;
  }
}

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////

template <template <class MY> class M,class Y,class X,class C>
class TrainableMixture3DModel : public Generic2DModel<Y,X,C> {
 private:
  string sId;
  SimpleHash<X,List<Joint2DRV<Y,Prob> > >       alyp;
  SimpleHash<X,TrainableMixture2DModel<M,Y,C> > am;
 public:
  // Constructor / destructor methods...
  TrainableMixture3DModel ( string s ) : sId(s) { }
  // Specification methods...
  void train ( const int, const PDFVal );
  void train ( const List<Joint3DRV<X,Y,Prob> >&, const int, const PDFVal );
  // Extraction methods...
  Prob getProb ( const Y& y, const X& x ) const { return am.get(x).getProb(y); }
  // Input / output methods...
  bool readData    ( char* as[], int );
  bool readFields  ( char* as[], int numF ) { return ( am.set(X(as[1])).readFields(as+1,numF-1) ); }
  void writeFields ( FILE*, string sPref );
};

////////////////////////////////////////
template <template <class MY> class M,class Y,class X,class C>
void TrainableMixture3DModel<M,Y,X,C>::train ( const int EPOCH_LIMIT, const PDFVal WEIGHT_LIMIT ) {
  // Update each subphone from list...
  int ctr = 0;
  X x; for ( bool b=x.setFirst(); b; b=x.setNext() ) {
    if (OUTPUT_NOISY) fprintf(stderr,"==================== SUBMODEL %s (number %d) %d data pts ====================\n",
                              x.getString().c_str(),ctr++,alyp.get(x).getCard());
    am.set(x).train ( alyp.set(x), EPOCH_LIMIT, WEIGHT_LIMIT );
  }
}

////////////////////////////////////////
template <template <class MY> class M,class Y,class X,class C>
void TrainableMixture3DModel<M,Y,X,C>::train ( const List<Joint3DRV<X,Y,Prob> >& lxyp, const int EPOCH_LIMIT, const PDFVal WEIGHT_LIMIT ) {
  // Chop list into phone-specific sub-lists...
  ListedObject<Joint3DRV<X,Y,Prob> >* pxyp;
  for ( pxyp=lxyp.getFirst(); pxyp; pxyp=lxyp.getNext(pxyp) )
    alyp.set(pxyp->getSub1()).add() = Joint2DRV<Y,Prob> ( pxyp->getSub2(), pxyp->getSub3() );
  // Update each subphone from list...
  train(EPOCH_LIMIT,WEIGHT_LIMIT);
}

////////////////////////////////////////
template <template <class MY> class M,class Y,class X,class C>
bool TrainableMixture3DModel<M,Y,X,C>::readData ( char* as[], int numFields ) {
  if ( /*as[0]!=sId+"dat" ||*/ numFields!=3 ) return false;
  alyp.set(X(as[1])).add() = Joint2DRV<Y,Prob>(Y(as[2]),Prob(1.0));
  return true;
}

////////////////////////////////////////
template <template <class MY> class M,class Y,class X,class C>
void TrainableMixture3DModel<M,Y,X,C>::writeFields  ( FILE* pf, string sPref ) {
  X x; for ( bool b=x.setFirst(); b; b=x.setNext() ) {
    am.get(x).writeFields(pf,sPref+" "+x.getString());
  }
}

#endif /*_NL_MIXTURE__*/


text:
function foo(p) { return p.catch(x => x); }

const a = Promise.resolve(1);

%PrepareFunctionForOptimization(foo);
foo(a);
foo(a);
%OptimizeFunctionOnNextCall(foo);
foo(a);

let custom_then_called = false;
a.then = function() { custom_then_called = true; }
foo(a);
assertTrue(custom_then_called);


text:
---
uid: SolidEdgeFrameworkSupport.DimensionStyle.PrimaryLinearToleranceUnits
summary:
remarks:
---


text:
import os, sys
from django.conf import settings

def pytest_configure():
    sys.path.append(os.path.dirname(__file__))

    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')


text:
<?php namespace Exchange\EWSType; use Exchange\EWSType;
/**
 * Contains EWSType_GetPhoneCallInformationType.
 */

/**
 * Represents a request to get telephone call information.
 *
 * @package php-ews\Types
 *
 * @todo Extend EWSType_BaseRequestType.
 */
class EWSType_GetPhoneCallInformationType extends EWSType
{
    /**
     * Specifies the identifier of a phone call.
     *
     * @since Exchange 2010
     *
     * @var EWSType_PhoneCallIdType
     */
    public $PhoneCallId;
}


text:
package models

import play.api.libs.json.{Format, JsResult, JsString, JsValue}
import play.api.mvc.QueryStringBindable.Parsing

object ThingType extends Enumeration {
  type Type = Value
  val Primary, Secondary, Other = Value

  implicit val jsonFormat = new Format[Type] {
    override def reads(json: JsValue): JsResult[Type] =
      json.validate[String].map(ThingType.withName)

    override def writes(o: Type): JsValue = JsString(o.toString)
  }

  implicit val queryBinder = new Parsing[Type](
    parse = ThingType.withName,
    serialize = v => v.toString,
    error = (key: String, e: Exception) => "Cannot parse parameter %s as ThingType: %s".format(key, e.getMessage)
  )
}


text:
import configTemplate from './config.html!text';

import _ from 'lodash' ;

class WorldPingConfigCtrl {
  constructor($scope, $injector, $q, backendSrv, alertSrv) {
    this.$q = $q;
    this.backendSrv = backendSrv;
    this.alertSrv = alertSrv;
    this.validKey = false;
    this.quotas = {};
    this.appEditCtrl.setPreUpdateHook(this.preUpdate.bind(this));
    this.appEditCtrl.setPostUpdateHook(this.postUpdate.bind(this));
    this.org = null;

    if (this.appModel.jsonData === null) {
      this.appModel.jsonData = {};
    }
    if (!this.appModel.secureJsonData) {
      this.appModel.secureJsonData = {};
    }
    if (this.appModel.enabled) {
      this.validateKey();
    }
  }

  reset() {
    this.appModel.jsonData.apiKeySet=false;
    this.validKey = false;
    this.org = null;
  }

  validateKey() {
    var self = this;
    var p = this.backendSrv.get('api/plugin-proxy/raintank-worldping-app/api/v2/quotas');
    p.then((resp) => {
      if (resp.meta.code !== 200) {
        self.alertSrv.set("failed to get Quotas", resp.message, 'error', 10000);
        return self.$q.reject(resp.message);
      }
      self.validKey = true;
      self.quotas = resp.body;

      self.getOrgDetails();
    }, (resp) => {
      if (self.appModel.enabled) {
        self.alertSrv.set("failed to verify apiKey", resp.statusText, 'error', 10000);
        self.appModel.enabled = false;
        self.appModel.jsonData.apiKeySet = false;
        self.appModel.secureJsonData.apiKey = "";
        self.errorMsg = "invalid apiKey";
        self.validKey = false;
      }
    });
    return p;
  }

  getOrgDetails() {
    var self = this;
    var p = this.backendSrv.get('api/plugin-proxy/raintank-worldping-app/api/grafana-net/profile/org');
    p.then((resp) => {
      self.org = resp;

      const millionChecksPerMonth = Math.ceil(parseInt(self.org.checksPerMonth, 10) / 100000) / 10;
      if (millionChecksPerMonth > 1000) {
        self.org.strChecksPerMonth = Math.ceil(millionChecksPerMonth / 1000) + ' Billion';
      } else if (millionChecksPerMonth > 0) {
        self.org.strChecksPerMonth = millionChecksPerMonth + ' Million';
      } else {
        self.org.strChecksPerMonth = 'N/A';
      }
    }, (resp) => {
      self.alertSrv.set("failed to get Org Details", resp.statusText, 'error', 10000);
    });
    return p;
  }

  preUpdate() {
    var model = this.appModel;
    if (!model.enabled) {
      return this.$q.resolve();
    }

    if (!model.jsonData.apiKeySet && !model.secureJsonData.apiKey) {
      model.enabled = false;
      this.errorMsg = "apiKey not set";
      this.validKey = false;
      return this.$q.reject("apiKey not set.");
    }
    model.jsonData.apiKeySet = true;
    return this.initDatasource();
  }

  postUpdate() {
    if (!this.appModel.enabled) {
      return this.$q.resolve();
    }
    var self = this;
    return this.validateKey()
    .then(() => {
      return self.appEditCtrl.importDashboards().then(() => {
        return {
          url: "dashboard/db/worldping-home",
          message: "worldPing app installed!"
        };
      });
    });
  }

  configureDatasource() {
    this.appModel.jsonData.datasourceSet = false;
    this.initDatasource().then(() => {
      this.appModel.jsonData.datasourceSet = true;
    });
  }

  initDatasource() {
    var self = this;
    //check for existing datasource.
    var p = self.backendSrv.get('/api/datasources');
    p.then(function(results) {
      var foundGraphite = false;
      var foundElastic = false;
      _.forEach(results, function(ds) {
        if (foundGraphite && foundElastic) { return; }
        if (ds.name === "raintank") {
          foundGraphite = true;
        }
        if (ds.name === "raintankEvents") {
          foundElastic = true;
        }
      });
      var promises = [];
      if (!foundGraphite) {
        // create datasource.
        var graphite = {
          name: 'raintank',
          type: 'graphite',
          url: 'api/plugin-proxy/raintank-worldping-app/api/graphite',
          access: 'direct',
          jsonData: {}
        };
        promises.push(self.backendSrv.post('/api/datasources', graphite));
      }
      if (!foundElastic) {
        // create datasource.
        var elastic = {
          name: 'raintankEvents',
          type: 'elasticsearch',
          url: 'api/plugin-proxy/raintank-worldping-app/api/elasticsearch',
          access: 'direct',
          database: '[events-]YYYY-MM-DD',
          jsonData: {
            esVersion: 1,
            interval: "Daily",
            timeField: "timestamp"
          }
        };
        promises.push(self.backendSrv.post('/api/datasources', elastic));
      }
      return self.$q.all(promises);
    });
    return p;
  }
}

WorldPingConfigCtrl.template = configTemplate;

export {
  WorldPingConfigCtrl as ConfigCtrl
};


text:
'use strict';

describe('services', function () {
  describe('PeopleService', function () {
    beforeEach(module('collabjs.services'));

    var httpBackend;
    var service;
    var successCallback;
    var errorCallback;

    beforeEach(inject(function ($httpBackend, peopleService) {
      httpBackend = $httpBackend;
      service = peopleService;
      successCallback = jasmine.createSpy('success');
      errorCallback = jasmine.createSpy('error');
    }));

    afterEach(function () {
      httpBackend.verifyNoOutstandingExpectation();
      httpBackend.verifyNoOutstandingRequest();
    });

    it('should have account service registered', function () {
      expect(service).not.toEqual(null);
    });

    it('should have primary api', function () {
      expect(angular.isFunction(service.getPeople)).toBe(true);
      expect(angular.isFunction(service.getFollowing)).toBe(true);
      expect(angular.isFunction(service.getFollowers)).toBe(true);
      expect(angular.isFunction(service.canFollow)).toBe(true);
      expect(angular.isFunction(service.getCountryName)).toBe(true);
      expect(angular.isFunction(service.getFollowingUrl)).toBe(true);
      expect(angular.isFunction(service.getFollowersUrl)).toBe(true);
      expect(angular.isFunction(service.follow)).toBe(true);
      expect(angular.isFunction(service.unfollow)).toBe(true);
    });

    it('should retrieve people from server', function () {
      var url = '/api/people';
      httpBackend.expectGET(url).respond(200);

      service.getPeople().then(successCallback);
      httpBackend.flush();

      expect(successCallback).toHaveBeenCalled();
    });

    it('should retrieve following by account', function () {
      var url = '/api/u/johndoe/following';
      httpBackend.expectGET(url).respond(200);

      service.getFollowing('johndoe').then(successCallback);
      httpBackend.flush();

      expect(successCallback).toHaveBeenCalled();
    });

    it('should retrieve followers by account', function () {
      var url = '/api/u/johndoe/followers';
      httpBackend.expectGET(url).respond(url);

      service.getFollowers('johndoe').then(successCallback);
      httpBackend.flush();

      expect(successCallback).toHaveBeenCalled();
    });

    it('should allow following profile', function () {
      var profile = { isFollowed: false, isOwnProfile: false };
      expect(service.canFollow(profile)).toBe(true);
    });

    it('should not allow following profile', function () {
      var profile = { isFollowed: true, isOwnProfile: false };
      expect(service.canFollow(profile)).toBe(false);
    });

    it('should not allow following own profile', function () {
      var profile = { isFollowed: false, isOwnProfile: true };
      expect(service.canFollow(profile)).toBe(false);
    });

    it('should allow unfollowing profile', function () {
      var profile = { isFollowed: true, isOwnProfile: false };
      expect(service.canUnfollow(profile)).toBe(true);
    });

    it('should not allow unfollowing profile', function () {
      var profile = { isFollowed: false, isOwnProfile: false };
      expect(service.canUnfollow(profile)).toBe(false);
    });

    it('should not allow unfollowing own profile', function () {
      var profile = { isFollowed: true, isOwnProfile: true };
      expect(service.canUnfollow(profile)).toBe(false);
    });

    it('should get country name', function () {
      var profile = { location: 'ua' };
      expect(service.getCountryName(profile)).toBe('Ukraine');
    });

    it('should not get country name', function () {
      expect(service.getCountryName({})).toBe('');
      expect(service.getCountryName({location: ''})).toBe('');
    });

    it('should get following url', function () {
      var profile = { account: 'johndoe' };
      var expectedUrl = '/#/people/johndoe/following';
      expect(service.getFollowingUrl(profile)).toBe(expectedUrl);
    });

    it('should not get following url if profile is not defined', function () {
      expect(service.getFollowingUrl(null)).toBeNull();
    });

    it('should not get following url if profile account is missing', function () {
      var profile = {};
      expect(service.getFollowingUrl(profile)).toBeNull();
    });

    it('should get followers url', function () {
      var profile = { account: 'johndoe' };
      var expectedUrl = '/#/people/johndoe/followers';
      expect(service.getFollowersUrl(profile)).toBe(expectedUrl);
    });

    it('should not get followers url if profile is not defined', function () {
      expect(service.getFollowersUrl(null)).toBeNull();
    });

    it('should not get followers url if profile account is missing', function () {
      var profile = {};
      expect(service.getFollowersUrl(profile)).toBeNull();
    });

    it('should follow profile', function () {
      var profile = { account: 'johndoe', isFollowed: false };
      var url = '/api/u/johndoe/follow';
      httpBackend.expectPOST(url).respond(200);

      service.follow(profile);
      httpBackend.flush();

      expect(profile.isFollowed).toBe(true);
    });

    it('should unfollow profile', function () {
      var profile = { account: 'johndoe', isFollowed: true };
      var url = '/api/u/johndoe/unfollow';
      httpBackend.expectPOST(url).respond(200);

      service.unfollow(profile);
      httpBackend.flush();

      expect(profile.isFollowed).toBe(false);
    });

  });
});


text:
<footer class="footer">
  <a [href]="legalPage">Impressum, Datenschutz, Urheberrecht, Haftungsausschluss</a>
</footer>


text:
package io.arivera.oss.embedded.rabbitmq;

import io.arivera.oss.embedded.rabbitmq.util.ArchiveType;
import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem;

import java.io.Serializable;
import java.util.Comparator;
import java.util.List;

/**
 * A class that provides information about a specific distribution artifact version of RabbitMQ.
 */
public interface Version {

  VersionComparator VERSION_COMPARATOR = new VersionComparator();

  /**
   * @return a String formatted like {@code "3.6.5"}
   *
   * @see #getVersionAsString(CharSequence)
   */
  String getVersionAsString();

  /**
   * @return a String formatted like {@code "3_6_5"} if given {@code "_"} as separator.
   */
  String getVersionAsString(CharSequence separator);

  /**
   * @return correct Archive Type for the given OS.
   */
  ArchiveType getArchiveType(OperatingSystem operatingSystem);

  /**
   * @return folder name under which the compressed application is extracted to.
   */
  String getExtractionFolder();

  /**
   * @return minimum version required to run this RabbitMQ version. Example: {@code "R16B3"} or {code null}
   */
  String getMinimumErlangVersion();

  /**
   * @return an Array like [3,6,5] for version 3.6.5
   */
  List<Integer> getVersionComponents();

  class VersionComparator implements Comparator<Version>, Serializable {

    private static final long serialVersionUID = 1L;

    @Override
    public int compare(Version v1, Version v2) {
      for (int i = 0; i < v1.getVersionComponents().size(); i++) {
        int comp = v1.getVersionComponents().get(i).compareTo(v2.getVersionComponents().get(i));
        if (comp != 0) {
          return comp;
        }
      }
      return 0;
    }

  }

}


text:
package com.sivalabs.myapp;

import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.PrimaryKey;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.QueryOutcome;
import com.amazonaws.services.dynamodbv2.document.ScanOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;
import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DynamoDBSample {

    public static void main(String[] args) throws Exception {
        createTable();
        loadData();
        createNewItem();
        readItem();
        updateItem();
        updateItemConditionally();
        deleteItem();
        queryData();
        scanData();
        deleteTable();
    }

    static DynamoDB dynamoDB() {
        String dynamodbEndpoint = "http://localhost:4569";
        AwsClientBuilder.EndpointConfiguration endpointConfiguration =
                new AwsClientBuilder.EndpointConfiguration(dynamodbEndpoint, Regions.US_WEST_2.getName());
        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .build();

        return new DynamoDB(client);

    }

    public static void createTable() throws Exception {
        System.err.println("-------createTable----------");
        DynamoDB dynamoDB = dynamoDB();

        String tableName = "Movies";

        try {
            System.out.println("Attempting to create table; please wait...");
            Table table = dynamoDB.createTable(tableName,
                    Arrays.asList(new KeySchemaElement("year", KeyType.HASH), // Partition key
                            new KeySchemaElement("title", KeyType.RANGE)), // Sort key
                    Arrays.asList(new AttributeDefinition("year", ScalarAttributeType.N),
                            new AttributeDefinition("title", ScalarAttributeType.S)),
                    new ProvisionedThroughput(10L, 10L));
            table.waitForActive();
            System.out.println("Success.  Table status: " + table.getDescription().getTableStatus());

        } catch (Exception e) {
            System.err.println("Unable to create table: ");
            System.err.println(e.getMessage());
        }

    }

    public static void loadData() throws Exception {
        System.err.println("-------loadData----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");
        InputStream is = DynamoDBSample.class.getResourceAsStream("/moviedata.json");
        JsonParser parser = new JsonFactory().createParser(is);

        JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();

        ObjectNode currentNode;

        while (iter.hasNext()) {
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();

            try {
                table.putItem(new Item().withPrimaryKey("year", year, "title", title).withJSON("info",
                        currentNode.path("info").toString()));
                System.out.println("PutItem succeeded: " + year + " " + title);

            } catch (Exception e) {
                System.err.println("Unable to add movie: " + year + " " + title);
                System.err.println(e.getMessage());
                break;
            }
        }
        parser.close();
    }

    public static void createNewItem() throws Exception {
        System.err.println("-------createNewItem----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        final Map<String, Object> infoMap = new HashMap<String, Object>();
        infoMap.put("plot", "Nothing happens at all.");
        infoMap.put("rating", 0);

        try {
            System.out.println("Adding a new item...");
            PutItemOutcome outcome = table
                    .putItem(new Item().withPrimaryKey("year", year, "title", title).withMap("info", infoMap));

            System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult());

        } catch (Exception e) {
            System.err.println("Unable to add item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }

    public static void readItem() throws Exception {
        System.err.println("-------readItem----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        GetItemSpec spec = new GetItemSpec().withPrimaryKey("year", year, "title", title);

        try {
            System.out.println("Attempting to read the item...");
            Item outcome = table.getItem(spec);
            System.out.println("GetItem succeeded: " + outcome);

        } catch (Exception e) {
            System.err.println("Unable to read item: " + year + " " + title);
            System.err.println(e.getMessage());
        }

    }

    public static void updateItem() throws Exception {
        System.err.println("-------updateItem----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
                .withUpdateExpression("set info.rating = :r, info.plot=:p, info.actors=:a")
                .withValueMap(new ValueMap().withNumber(":r", 5.5).withString(":p", "Everything happens all at once.")
                        .withList(":a", Arrays.asList("Larry", "Moe", "Curly")))
                .withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Updating the item...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    public static void incrementAtomicCounter() throws Exception {
        System.err.println("-------incrementAtomicCounter----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("year", year, "title", title)
                .withUpdateExpression("set info.rating = info.rating + :val")
                .withValueMap(new ValueMap().withNumber(":val", 1)).withReturnValues(ReturnValue.UPDATED_NEW);

        try {
            System.out.println("Incrementing an atomic counter...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    public static void updateItemConditionally() throws Exception {
        System.err.println("-------updateItemConditionally----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withUpdateExpression("remove info.actors[0]")
                //.withConditionExpression("size(info.actors) > :num").withValueMap(new ValueMap().withNumber(":num", 3))
                .withConditionExpression("size(info.actors) >= :num").withValueMap(new ValueMap().withNumber(":num", 3))
                .withReturnValues(ReturnValue.UPDATED_NEW);

        // Conditional update (we expect this to fail)
        try {
            System.out.println("Attempting a conditional update...");
            UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());

        } catch (Exception e) {
            System.err.println("Unable to update item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    public static void deleteItem() throws Exception {
        System.err.println("-------deleteItem----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        int year = 2015;
        String title = "The Big New Movie";

        /*DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
                .withPrimaryKey(new PrimaryKey("year", year, "title", title)).withConditionExpression("info.rating <= :val")
                .withValueMap(new ValueMap().withNumber(":val", 5.0));

        // Conditional delete (we expect this to fail)
*/
        DeleteItemSpec deleteItemSpec = new DeleteItemSpec()
                .withPrimaryKey(new PrimaryKey("year", 2015, "title", "The Big New Movie"));

        try {
            System.out.println("Attempting a conditional delete...");
            table.deleteItem(deleteItemSpec);
            System.out.println("DeleteItem succeeded");
        } catch (Exception e) {
            System.err.println("Unable to delete item: " + year + " " + title);
            System.err.println(e.getMessage());
        }
    }

    public static void queryData() throws Exception {
        System.err.println("-------queryData----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        HashMap<String, String> nameMap = new HashMap<String, String>();
        nameMap.put("#yr", "year");

        HashMap<String, Object> valueMap = new HashMap<String, Object>();
        valueMap.put(":yyyy", 2013);

        QuerySpec querySpec = new QuerySpec().withKeyConditionExpression("#yr = :yyyy").withNameMap(nameMap)
                .withValueMap(valueMap);

        ItemCollection<QueryOutcome> items = null;
        Iterator<Item> iterator = null;
        Item item = null;

        try {
            System.out.println("Movies from 2013");
            items = table.query(querySpec);

            iterator = items.iterator();
            while (iterator.hasNext()) {
                item = iterator.next();
                System.out.println(item.getNumber("year") + ": " + item.getString("title"));
            }

        } catch (Exception e) {
            System.err.println("Unable to query movies from 2013");
            System.err.println(e.getMessage());
        }

        valueMap.put(":yyyy", 1992);
        valueMap.put(":letter1", "A");
        valueMap.put(":letter2", "L");

        querySpec.withProjectionExpression("#yr, title, info.genres, info.actors[0]")
                .withKeyConditionExpression("#yr = :yyyy and title between :letter1 and :letter2").withNameMap(nameMap)
                .withValueMap(valueMap);

        try {
            System.out.println("Movies from 1992 - titles A-L, with genres and lead actor");
            items = table.query(querySpec);

            iterator = items.iterator();
            while (iterator.hasNext()) {
                item = iterator.next();
                System.out.println(item.getNumber("year") + ": " + item.getString("title") + " " + item.getMap("info"));
            }

        } catch (Exception e) {
            System.err.println("Unable to query movies from 1992:");
            System.err.println(e.getMessage());
        }
    }

    public static void scanData() throws Exception {
        System.err.println("-------scanData----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        ScanSpec scanSpec = new ScanSpec().withProjectionExpression("#yr, title, info.rating")
                .withFilterExpression("#yr between :start_yr and :end_yr").withNameMap(new NameMap().with("#yr", "year"))
                .withValueMap(new ValueMap().withNumber(":start_yr", 2000).withNumber(":end_yr", 2016));

        try {
            ItemCollection<ScanOutcome> items = table.scan(scanSpec);

            Iterator<Item> iter = items.iterator();
            while (iter.hasNext()) {
                Item item = iter.next();
                System.err.println(item.toString());
            }

        } catch (Exception e) {
            System.err.println("Unable to scan the table:");
            System.err.println(e.getMessage());
        }
    }

    public static void deleteTable() throws Exception {
        System.err.println("-------deleteTable----------");
        DynamoDB dynamoDB = dynamoDB();

        Table table = dynamoDB.getTable("Movies");

        try {
            System.out.println("Attempting to delete table; please wait...");
            table.delete();
            table.waitForDelete();
            System.out.print("Success.");

        } catch (Exception e) {
            System.err.println("Unable to delete table: ");
            System.err.println(e.getMessage());
        }
    }
}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Console\Output;

use PhpCsFixer\FixerFileProcessedEvent;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Output writer to show the process of a FixCommand.
 *
 * @internal
 */
final class ProcessOutput implements ProcessOutputInterface
{
    /**
     * File statuses map.
     *
     * @var array
     */
    private static $eventStatusMap = [
        FixerFileProcessedEvent::STATUS_UNKNOWN => ['symbol' => '?', 'format' => '%s', 'description' => 'unknown'],
        FixerFileProcessedEvent::STATUS_INVALID => ['symbol' => 'I', 'format' => '<bg=red>%s</bg=red>', 'description' => 'invalid file syntax (file ignored)'],
        FixerFileProcessedEvent::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '<fg=cyan>%s</fg=cyan>', 'description' => 'skipped (cached or empty file)'],
        FixerFileProcessedEvent::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'],
        FixerFileProcessedEvent::STATUS_FIXED => ['symbol' => 'F', 'format' => '<fg=green>%s</fg=green>', 'description' => 'fixed'],
        FixerFileProcessedEvent::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '<bg=red>%s</bg=red>', 'description' => 'error'],
        FixerFileProcessedEvent::STATUS_LINT => ['symbol' => 'E', 'format' => '<bg=red>%s</bg=red>', 'description' => 'error'],
    ];

    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * @var int
     */
    private $files;

    /**
     * @var int
     */
    private $processedFiles = 0;

    /**
     * @var int
     */
    private $symbolsPerLine;

    /**
     * @param int $width
     * @param int $nbFiles
     */
    public function __construct(OutputInterface $output, EventDispatcherInterface $dispatcher, $width, $nbFiles)
    {
        $this->output = $output;
        $this->eventDispatcher = $dispatcher;
        $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, [$this, 'onFixerFileProcessed']);
        $this->files = $nbFiles;

        //   max number of characters per line
        // - total length x 2 (e.g. "  1 / 123" => 6 digits and padding spaces)
        // - 11               (extra spaces, parentheses and percentage characters, e.g. " x / x (100%)")
        $this->symbolsPerLine = max(1, $width - \strlen((string) $this->files) * 2 - 11);
    }

    public function __destruct()
    {
        $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, [$this, 'onFixerFileProcessed']);
    }

    public function onFixerFileProcessed(FixerFileProcessedEvent $event)
    {
        $status = self::$eventStatusMap[$event->getStatus()];
        $this->output->write($this->output->isDecorated() ? sprintf($status['format'], $status['symbol']) : $status['symbol']);

        ++$this->processedFiles;

        $symbolsOnCurrentLine = $this->processedFiles % $this->symbolsPerLine;
        $isLast = $this->processedFiles === $this->files;

        if (0 === $symbolsOnCurrentLine || $isLast) {
            $this->output->write(sprintf(
                '%s %'.\strlen((string) $this->files).'d / %d (%3d%%)',
                $isLast && 0 !== $symbolsOnCurrentLine ? str_repeat(' ', $this->symbolsPerLine - $symbolsOnCurrentLine) : '',
                $this->processedFiles,
                $this->files,
                round($this->processedFiles / $this->files * 100)
            ));

            if (!$isLast) {
                $this->output->writeln('');
            }
        }
    }

    public function printLegend()
    {
        $symbols = [];

        foreach (self::$eventStatusMap as $status) {
            $symbol = $status['symbol'];
            if ('' === $symbol || isset($symbols[$symbol])) {
                continue;
            }

            $symbols[$symbol] = sprintf('%s-%s', $this->output->isDecorated() ? sprintf($status['format'], $symbol) : $symbol, $status['description']);
        }

        $this->output->write(sprintf("\nLegend: %s\n", implode(', ', $symbols)));
    }
}