text:
using CoreGraphics;
using CoreAnimation;
using System;
using System.ComponentModel;
using Xamarin.Forms;
using FFImageLoading.Work;
using Foundation;
using FFImageLoading.Forms;
using FFImageLoading.Extensions;
using System.Threading.Tasks;
using FFImageLoading.Helpers;
using FFImageLoading.Forms.Args;
using FFImageLoading.Forms.Platform;
using System.Reflection;

#if __IOS__
using UIKit;
using PImage = UIKit.UIImage;
using PImageView = UIKit.UIImageView;
using Xamarin.Forms.Platform.iOS;

#elif __MACOS__
using AppKit;
using PImage = AppKit.NSImage;
using PImageView = FFImageLoading.Forms.Platform.CachedImageRenderer.FormsNSImageView;
using Xamarin.Forms.Platform.MacOS;
using System.IO;
#endif

namespace FFImageLoading.Forms.Platform
{
    /// <summary>
    /// CachedImage Implementation
    /// </summary>
    [Preserve(AllMembers = true)]
    public class CachedImageRenderer : ViewRenderer<CachedImage, PImageView>
    {
        [RenderWith(typeof(CachedImageRenderer))]
        internal class _CachedImageRenderer
        {
        }

        private bool _isDisposed;
		private IScheduledWork _currentTask;
        private ImageSourceBinding _lastImageSource;
        private readonly object _updateBitmapLock = new object();

        /// <summary>
        ///   Used for registration with dependency service
        /// </summary>
        public static new void Init()
        {
            CachedImage.IsRendererInitialized = true;

            // needed because of this STUPID linker issue: https://bugzilla.xamarin.com/show_bug.cgi?id=31076
#pragma warning disable 0219
            var ignore1 = typeof(CachedImageRenderer);
            var ignore2 = typeof(CachedImage);
#pragma warning restore 0219
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            ScaleHelper.InitAsync();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }

		/// <summary>
		/// Call this after Xamarin.Forms.Init to use FFImageLoading in all Xamarin.Forms views,
		/// including Xamarin.Forms.Image
		/// </summary>
		public static void InitImageSourceHandler()
		{
			Helpers.Dependency.Register(typeof(FileImageSource), typeof(FFImageLoadingImageSourceHandler));
			Helpers.Dependency.Register(typeof(StreamImageSource), typeof(FFImageLoadingImageSourceHandler));
			Helpers.Dependency.Register(typeof(UriImageSource), typeof(FFImageLoadingImageSourceHandler));
			Helpers.Dependency.Register(typeof(EmbeddedResourceImageSource), typeof(FFImageLoadingImageSourceHandler));
			Helpers.Dependency.Register(typeof(DataUrlImageSource), typeof(FFImageLoadingImageSourceHandler));

			try
			{
				var svgAssembly = Assembly.Load("FFImageLoading.Svg.Forms");
				if (svgAssembly != null)
				{
					var svgImageSourceType = svgAssembly.GetType("FFImageLoading.Svg.Forms.SvgImageSource");
					if (svgImageSourceType != null)
					{
						Helpers.Dependency.Register(svgImageSourceType, typeof(FFImageLoadingImageSourceHandler));
					}
				}
			}
			catch { }
		}

		protected override void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
                CancelIfNeeded();
            }

            base.Dispose(disposing);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<CachedImage> e)
        {
            base.OnElementChanged(e);

            if (Control == null && Element != null && !_isDisposed)
            {
#if __IOS__
                SetNativeControl(new PImageView(CGRect.Empty)
                {
                    ContentMode = UIViewContentMode.ScaleAspectFit,
                    ClipsToBounds = true
                });
#elif __MACOS__
                SetNativeControl(new PImageView());
#endif
            }

            if (e.OldElement != null)
            {
                e.OldElement.InternalReloadImage = null;
                e.OldElement.InternalCancel = null;
                e.OldElement.InternalGetImageAsJPG = null;
                e.OldElement.InternalGetImageAsPNG = null;
            }

            if (e.NewElement != null)
            {
				e.NewElement.InternalReloadImage = new Action(ReloadImage);
                e.NewElement.InternalCancel = new Action(CancelIfNeeded);
                e.NewElement.InternalGetImageAsJPG = new Func<GetImageAsJpgArgs, Task<byte[]>>(GetImageAsJpgAsync);
                e.NewElement.InternalGetImageAsPNG = new Func<GetImageAsPngArgs, Task<byte[]>>(GetImageAsPngAsync);

				SetOpacity();
				SetAspect();
                UpdateImage(Control, Element, e.OldElement);
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName == CachedImage.SourceProperty.PropertyName)
            {
                UpdateImage(Control, Element, null);
            }
            if (e.PropertyName == CachedImage.IsOpaqueProperty.PropertyName)
            {
                SetOpacity();
            }
            if (e.PropertyName == CachedImage.AspectProperty.PropertyName)
            {
                SetAspect();
            }
        }

        private void SetAspect()
        {
            if (Control == null || Control.Handle == IntPtr.Zero || Element == null || _isDisposed)
                return;
#if __IOS__
            Control.ContentMode = Element.Aspect.ToUIViewContentMode();
#elif __MACOS__
            switch (Element.Aspect)
            {
                case Aspect.AspectFill:
                    Control.Layer.ContentsGravity = CALayer.GravityResizeAspectFill;
                    break;
                case Aspect.Fill:
                    Control.Layer.ContentsGravity = CALayer.GravityResize;
                    break;
                case Aspect.AspectFit:
                default:
                    Control.Layer.ContentsGravity = CALayer.GravityResizeAspect;
                    break;
            }
#endif
        }

        private void SetOpacity()
        {
            if (Control == null || Control.Handle == IntPtr.Zero || Element == null || _isDisposed)
                return;
#if __IOS__
            Control.Opaque = Element.IsOpaque;
#elif __MACOS__
            Control.SetIsOpaque(Element.IsOpaque);
#endif
        }

        private void UpdateImage(PImageView imageView, CachedImage image, CachedImage previousImage)
        {
            lock (_updateBitmapLock)
            {
                CancelIfNeeded();

                if (image == null || imageView == null || imageView.Handle == IntPtr.Zero || _isDisposed)
                    return;

                var ffSource = ImageSourceBinding.GetImageSourceBinding(image.Source, image);
                if (ffSource == null)
                {
                    if (_lastImageSource == null)
                        return;

                    _lastImageSource = null;
                    imageView.Image = null;
                    return;
                }

                if (previousImage != null && !ffSource.Equals(_lastImageSource))
                {
                    _lastImageSource = null;
                    imageView.Image = null;
                }

                image.SetIsLoading(true);

                var placeholderSource = ImageSourceBinding.GetImageSourceBinding(image.LoadingPlaceholder, image);
                var errorPlaceholderSource = ImageSourceBinding.GetImageSourceBinding(image.ErrorPlaceholder, image);
                image.SetupOnBeforeImageLoading(out var imageLoader, ffSource, placeholderSource, errorPlaceholderSource);

                if (imageLoader != null)
                {
                    var finishAction = imageLoader.OnFinish;
                    var sucessAction = imageLoader.OnSuccess;

                    imageLoader.Finish((work) =>
                    {
                        finishAction?.Invoke(work);
                        ImageLoadingSizeChanged(image, false);
                    });

                    imageLoader.Success((imageInformation, loadingResult) =>
                    {
                        sucessAction?.Invoke(imageInformation, loadingResult);
                        _lastImageSource = ffSource;
                    });

                    imageLoader.LoadingPlaceholderSet(() => ImageLoadingSizeChanged(image, true));

                    if (!_isDisposed)
                        _currentTask = imageLoader.Into(imageView);
                }
            }
        }

		private async void ImageLoadingSizeChanged(CachedImage element, bool isLoading)
		{
			if (element == null || _isDisposed)
				return;

			await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
			{
				if (element == null || _isDisposed)
					return;

				((IVisualElementController)element).NativeSizeChanged();

				if (!isLoading)
					element.SetIsLoading(isLoading);
			}).ConfigureAwait(false);
		}

		private void ReloadImage()
        {
            UpdateImage(Control, Element, null);
        }

        private void CancelIfNeeded()
        {
            try
            {
                _currentTask?.Cancel();
            }
            catch { }
        }

        private Task<byte[]> GetImageAsJpgAsync(GetImageAsJpgArgs args)
        {
            return GetImageAsByteAsync(false, args.Quality, args.DesiredWidth, args.DesiredHeight);
        }

        private Task<byte[]> GetImageAsPngAsync(GetImageAsPngArgs args)
        {
            return GetImageAsByteAsync(true, 90, args.DesiredWidth, args.DesiredHeight);
        }

        private async Task<byte[]> GetImageAsByteAsync(bool usePNG, int quality, int desiredWidth, int desiredHeight)
        {
            PImage image = null;

            await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
            {
                if (Control != null)
                    image = Control.Image;
            }).ConfigureAwait(false);

            if (image == null)
                return null;

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                image = image.ResizeUIImage(desiredWidth, desiredHeight, InterpolationMode.Default);
            }

#if __IOS__

            var imageData = usePNG ? image.AsPNG() : image.AsJPEG((nfloat)quality / 100f);

            if (imageData == null || imageData.Length == 0)
                return null;

            var encoded = imageData.ToArray();
            imageData.TryDispose();
            return encoded;
#elif __MACOS__

            byte[] encoded;
            using (MemoryStream ms = new MemoryStream())
            using (var stream = usePNG ? image.AsPngStream() : image.AsJpegStream(quality))
            {
                stream.CopyTo(ms);
                encoded = ms.ToArray();
            }

            if (desiredWidth != 0 || desiredHeight != 0)
            {
                image.TryDispose();
            }

            return encoded;
#endif
        }

#if __MACOS__
        public class FormsNSImageView : NSImageView
        {
            bool _isOpaque;

            public FormsNSImageView()
            {
                //Layer = new FFCALayer();
                //WantsLayer = true;
            }

            public void SetIsOpaque(bool isOpaque)
            {
                _isOpaque = isOpaque;
            }

            //public override void DrawRect(CGRect dirtyRect)
            //{
            //    // TODO if it isn't disabled then this issue happens:
            //    // https://github.com/luberda-molinet/FFImageLoading/issues/922
            //    // base.DrawRect(dirtyRect);
            //}

            public override bool IsOpaque => _isOpaque;
        }
#endif
    }
}


text:
'use babel';

import Opal from '../lib/opal';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('Opal', () => {
  let workspaceElement, activationPromise;

  beforeEach(() => {
    workspaceElement = atom.views.getView(atom.workspace);
    activationPromise = atom.packages.activatePackage('opal');
  });

  describe('when the opal:toggle event is triggered', () => {
    it('hides and shows the modal panel', () => {
      // Before the activation event the view is not on the DOM, and no panel
      // has been created
      expect(workspaceElement.querySelector('.opal')).not.toExist();

      // This is an activation event, triggering it will cause the package to be
      // activated.
      atom.commands.dispatch(workspaceElement, 'opal:toggle');

      waitsForPromise(() => {
        return activationPromise;
      });

      runs(() => {
        expect(workspaceElement.querySelector('.opal')).toExist();

        let opalElement = workspaceElement.querySelector('.opal');
        expect(opalElement).toExist();

        let opalPanel = atom.workspace.panelForItem(opalElement);
        expect(opalPanel.isVisible()).toBe(true);
        atom.commands.dispatch(workspaceElement, 'opal:toggle');
        expect(opalPanel.isVisible()).toBe(false);
      });
    });

    it('hides and shows the view', () => {
      // This test shows you an integration test testing at the view level.

      // Attaching the workspaceElement to the DOM is required to allow the
      // `toBeVisible()` matchers to work. Anything testing visibility or focus
      // requires that the workspaceElement is on the DOM. Tests that attach the
      // workspaceElement to the DOM are generally slower than those off DOM.
      jasmine.attachToDOM(workspaceElement);

      expect(workspaceElement.querySelector('.opal')).not.toExist();

      // This is an activation event, triggering it causes the package to be
      // activated.
      atom.commands.dispatch(workspaceElement, 'opal:toggle');

      waitsForPromise(() => {
        return activationPromise;
      });

      runs(() => {
        // Now we can test for view visibility
        let opalElement = workspaceElement.querySelector('.opal');
        expect(opalElement).toBeVisible();
        atom.commands.dispatch(workspaceElement, 'opal:toggle');
        expect(opalElement).not.toBeVisible();
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package JUnit_Test;

import org.junit.*;

import Util.CifrarioCesare;

public class CodiceCesareTest {
	private CifrarioCesare cifrario;
	@Before
	public void init(){
		cifrario = new CifrarioCesare();
	}

	@Test
	public void firstTest(){
		assert(cifrario!=null);
	}
	@Test
	public void cifraEdecifra(){
		String s = "stringa di prova";
		assert (s.equals(cifrario.deCript(cifrario.cript(s))));
	}
}


text:
package com.ctrip.xpipe.redis.core.protocal.protocal;

import com.ctrip.xpipe.payload.ByteArrayOutputStreamPayload;
import com.ctrip.xpipe.payload.InOutPayloadFactory;
import com.ctrip.xpipe.redis.core.exception.RedisRuntimeException;
import com.ctrip.xpipe.redis.core.protocal.RedisClientProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wenchao.meng
 *
 * 2016年4月22日 下午6:05:05
 */
public class ArrayParser extends AbstractRedisClientProtocol<Object[]>{

	private static final Logger logger = LoggerFactory.getLogger(ArrayParser.class);

	public enum ARRAY_STATE{
		READ_SIZE,
		READ_CONTENT
	}

	private Object[] resultArray;
	private int  arraySize = 0;
	private int  currentIndex = 0;
	private RedisClientProtocol<?> currentParser  = null;
	private ARRAY_STATE arrayState = ARRAY_STATE.READ_SIZE;

	private InOutPayloadFactory inOutPayloadFactory;

	public ArrayParser() {

	}

	public ArrayParser(Object []payload){
		super(payload, true, true);
	}

	@Override
	public RedisClientProtocol<Object[]> read(ByteBuf byteBuf) {

		switch(arrayState){

			case READ_SIZE:

				String arrayNumString = readTilCRLFAsString(byteBuf);
				if(arrayNumString == null){
					return null;
				}

				if(arrayNumString.charAt(0) == ASTERISK_BYTE){
					arrayNumString = arrayNumString.substring(1);
				}
				arrayNumString = arrayNumString.trim();

				arraySize = Integer.valueOf(arrayNumString);
				resultArray = new Object[arraySize];
				arrayState = ARRAY_STATE.READ_CONTENT;
				currentIndex = 0;
				if(arraySize == 0){
					return new ArrayParser(resultArray);
				}
				if(arraySize < 0){
					return new ArrayParser(null);
				}
			case READ_CONTENT:

				for(int i=currentIndex; i < arraySize ; i++){

					while(true){
						if(currentParser == null){

							if(byteBuf.readableBytes() == 0){
								return null;
							}
							int readerIndex = byteBuf.readerIndex();
							int data = byteBuf.getByte(readerIndex);
							switch(data){
								case '\r':
								case '\n':
									byteBuf.readByte();
									break;
								case DOLLAR_BYTE:
									if(inOutPayloadFactory != null) {
										currentParser = new CommandBulkStringParser(inOutPayloadFactory.create());
									} else {
										currentParser = new CommandBulkStringParser(new ByteArrayOutputStreamPayload());
									}
									break;
								case COLON_BYTE:
									currentParser = new LongParser();
									break;
								case ASTERISK_BYTE:
									currentParser = new ArrayParser().setInOutPayloadFactory(inOutPayloadFactory);
									break;
								case MINUS_BYTE:
									currentParser = new RedisErrorParser();
									break;
								case PLUS_BYTE:
									currentParser = new SimpleStringParser();
									break;
								default:
									throw new RedisRuntimeException("unknown protocol type:" + (char)data);
							}
						}
						if(currentParser != null){
							break;
						}
					}
					RedisClientProtocol<?> result = currentParser.read(byteBuf);
					if(result == null){
						return null;
					}
					resultArray[currentIndex] = result.getPayload();
					currentParser = null;
					currentIndex++;
				}
				if(currentIndex == arraySize){
					return new ArrayParser(resultArray);
				}
				break;
			default:
				throw new IllegalStateException("unknown state:" + arrayState);
		}
		return null;
	}

	@Override
	protected ByteBuf getWriteByteBuf() {

		int length = payload.length;
		CompositeByteBuf result = new CompositeByteBuf(UnpooledByteBufAllocator.DEFAULT, false, payload.length + 1);
		String prefix = String.format("%c%d\r\n", ASTERISK_BYTE, length);
		result.addComponent(Unpooled.wrappedBuffer(prefix.getBytes()));
		for(Object o : payload){
			ByteBuf buff = ParserManager.parse(o);
			result.addComponent(buff);
		}
		result.setIndex(0, result.capacity());
		return result;
	}

	@Override
	protected Logger getLogger() {
		return logger;
	}

	@Override
	public boolean supportes(Class<?> clazz) {
		return clazz.isArray();
	}

	@Override
	public void reset() {
		super.reset();
		arrayState = ARRAY_STATE.READ_SIZE;
		resultArray = null;
		arraySize = 0;
		currentIndex = 0;
		currentParser  = null;
	}

	public ArrayParser setInOutPayloadFactory(InOutPayloadFactory inOutPayloadFactory) {
		this.inOutPayloadFactory = inOutPayloadFactory;
		return this;
	}
}


text:
<?php

declare(strict_types=1);

namespace Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21;

use Centreon\Domain\Contact\Contact;
use Centreon\Domain\MetaServiceConfiguration\MetaServiceConfigurationService;
use Centreon\Domain\MetaServiceConfiguration\UseCase\V2110\FindOneMetaServiceConfiguration;
use PHPUnit\Framework\TestCase;
use Tests\Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfigurationTest;

/**
 * @package Tests\Centreon\Domain\MetaServiceConfiguration\UseCase\V21
 */
class FindOneMetaServiceConfigurationTest extends TestCase
{
    /**
     * @var MetaServiceConfigurationService&\PHPUnit\Framework\MockObject\MockObject
     */
    private $metaServiceConfigurationService;
    /**
     * @var \Centreon\Domain\MetaServiceConfiguration\Model\MetaServiceConfiguration
     */
    private $metaServiceConfiguration;

    protected function setUp(): void
    {
        $this->metaServiceConfigurationService = $this->createMock(MetaServiceConfigurationService::class);
        $this->metaServiceConfiguration = MetaServiceConfigurationTest::createEntity();
    }

    /**
     * @return FindHostCategories
     */
    private function createMetaServiceConfigurationUseCase(): FindOneMetaServiceConfiguration
    {
        $contact = new Contact();
        $contact->setAdmin(true);

        return (new FindOneMetaServiceConfiguration($this->metaServiceConfigurationService, $contact));
    }

    /**
     * Test as admin user
     */
    public function testExecuteAsAdmin(): void
    {
        $this->metaServiceConfigurationService
            ->expects($this->once())
            ->method('findWithoutAcl')
            ->willReturn($this->metaServiceConfiguration);

        $contact = new Contact();
        $contact->setAdmin(true);
        $findMetaServiceConfigurations = new FindOneMetaServiceConfiguration(
            $this->metaServiceConfigurationService,
            $contact
        );
        $response = $findMetaServiceConfigurations->execute($this->metaServiceConfiguration->getId());
        $metaServiceConfigurationResponse = $response->getMetaServiceConfiguration();
        /**
         * Only testing the ID here and not everything as this part is already tested in other test case
         */
        $this->assertEquals($this->metaServiceConfiguration->getId(), $metaServiceConfigurationResponse['id']);
    }

    /**
     * Test as non admin user
     */
    public function testExecuteAsNonAdmin(): void
    {
        $this->metaServiceConfigurationService
            ->expects($this->once())
            ->method('findWithAcl')
            ->willReturn($this->metaServiceConfiguration);

        $contact = new Contact();
        $contact->setAdmin(false);
        $findMetaServiceConfigurations = new FindOneMetaServiceConfiguration(
            $this->metaServiceConfigurationService,
            $contact
        );
        $response = $findMetaServiceConfigurations->execute($this->metaServiceConfiguration->getId());
        $metaServiceConfigurationResponse = $response->getMetaServiceConfiguration();
        /**
         * Only testing the ID here and not everything as this part is already tested in other test case
         */
        $this->assertEquals($this->metaServiceConfiguration->getId(), $metaServiceConfigurationResponse['id']);
    }
}


text:
require 'gecoder/interface/binding_changes'
require 'gecoder/interface/enum_matrix'
require 'gecoder/interface/mixin'
require 'gecoder/interface/mixin'
require 'gecoder/interface/mixin'
require 'gecoder/interface/search'
require 'gecoder/interface/constraints'
require 'gecoder/interface/variables'
require 'gecoder/interface/enum_wrapper'
require 'gecoder/interface/branch'
require 'gecoder/interface/convenience'


text:
package blueprint

import (
	"context"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"github.com/pkg/errors"

	mdmsvc "github.com/micromdm/micromdm/mdm"
	"github.com/micromdm/micromdm/mdm/mdm"
	"github.com/micromdm/micromdm/platform/command"
	"github.com/micromdm/micromdm/platform/device"
	"github.com/micromdm/micromdm/platform/profile"
	"github.com/micromdm/micromdm/platform/pubsub"
	"github.com/micromdm/micromdm/platform/user"
)

type BlueprintWorkerStore interface {
	BlueprintsByApplyAt(ctx context.Context, action string) ([]Blueprint, error)
}

type UserStore interface {
	User(ctx context.Context, uuid string) (*user.User, error)
}

type ProfileStore interface {
	ProfileById(ctx context.Context, id string) (*profile.Profile, error)
}

func NewWorker(
	db BlueprintWorkerStore,
	userDB UserStore,
	profileDB ProfileStore,
	cmdsvc command.Service,
	sub pubsub.Subscriber,
	logger log.Logger,
) *Worker {
	return &Worker{
		db:        db,
		userDB:    userDB,
		profileDB: profileDB,
		ps:        sub,
		cmdsvc:    cmdsvc,
		logger:    logger,
	}
}

type Worker struct {
	db        BlueprintWorkerStore
	userDB    UserStore
	profileDB ProfileStore
	ps        pubsub.Subscriber
	cmdsvc    command.Service
	logger    log.Logger
}

func (w *Worker) Run(ctx context.Context) error {
	tokenUpdateEvents, err := w.ps.Subscribe(ctx, "applyAtEnroll", device.DeviceEnrolledTopic)
	if err != nil {
		return errors.Wrapf(err, "subscribing devices to %s topic", device.DeviceEnrolledTopic)
	}

	for {
		var err error
		select {
		case <-ctx.Done():
			return ctx.Err()
		case ev := <-tokenUpdateEvents:
			err = w.handleTokenUpdateEvent(ctx, ev.Message)
		}

		if err != nil {
			level.Info(w.logger).Log(
				"msg", "handle blueprint action",
				"err", err,
			)
			continue
		}

	}
}

// TODO: See notes from here:
// https://github.com/jessepeterson/micromdm/blob/8b068ac98d06954bb3e08b1557c193007932552b/blueprint/listener.go#L73-L103
// Also see discussion here for general direction:
// https://github.com/micromdm/micromdm/pull/149
// Finally see discussion here for high-level goals:
// https://github.com/micromdm/micromdm/issues/110
func (w *Worker) handleTokenUpdateEvent(ctx context.Context, message []byte) error {
	var ev mdmsvc.CheckinEvent
	if err := mdmsvc.UnmarshalCheckinEvent(message, &ev); err != nil {
		return errors.Wrap(err, "unmarshal checkin event")
	}
	if ev.Command.UserID != "" {
		level.Debug(w.logger).Log(
			"msg", "skipping user token update in blueprint worker.",
			"device_udid", ev.Command.UDID,
			"user_id", ev.Command.UserID,
		)
		// skip UserID token updates
		return nil
	}

	bps, err := w.db.BlueprintsByApplyAt(ctx, ApplyAtEnroll)
	if err != nil {
		return errors.Wrap(err, "get blueprints by ApplyAtEnroll")
	}

	// if there are no blueprints exit early. This will ensure that DeviceConfigured is not sent.
	if len(bps) == 0 {
		level.Debug(w.logger).Log(
			"msg", "no blueprints to apply",
			"device_udid", ev.Command.UDID,
		)
		return nil
	}

	for _, bp := range bps {
		level.Debug(w.logger).Log(
			"msg", "applying blueprint",
			"device_udid", ev.Command.UDID,
			"blueprint_name", bp.Name,
		)

		if err := w.applyToDevice(ctx, bp, ev.Command.UDID); err != nil {
			return errors.Wrapf(err, "apply blueprint to udid name=%s, udid=%s", bp.Name, ev.Command.UDID)
		}
	}

	if ev.Command.AwaitingConfiguration {
		level.Debug(w.logger).Log(
			"msg", "sending DeviceConfigured at the end of blueprint",
			"device_udid", ev.Command.UDID,
		)
		_, err := w.cmdsvc.NewCommand(ctx, &mdm.CommandRequest{
			Command: &mdm.Command{RequestType: "DeviceConfigured"},
			UDID:    ev.Command.UDID,
		})
		if err != nil {
			return errors.Wrap(err, "send DeviceConfigured")
		}
	}

	return nil

}

func (w *Worker) applyToDevice(ctx context.Context, bp Blueprint, udid string) error {
	var requests []*mdm.CommandRequest
	for _, uuid := range bp.UserUUID {
		level.Debug(w.logger).Log(
			"msg", "creating mdm command request from blueprint",
			"request_type", "AccountConfiguration",
			"blueprint_name", bp.Name,
			"user_uuid", uuid,
			"device_udid", udid,
		)

		usr, err := w.userDB.User(ctx, uuid)
		if err != nil {
			level.Info(w.logger).Log(
				"msg", "get user for AccountConfiguration request",
				"blueprint_name", bp.Name,
				"user_uuid", uuid,
				"device_udid", udid,
				"err", err,
			)
			continue
		}

		requests = append(requests, &mdm.CommandRequest{
			UDID: udid,
			Command: &mdm.Command{
				RequestType: "AccountConfiguration",
				AccountConfiguration: &mdm.AccountConfiguration{
					SkipPrimarySetupAccountCreation:     bp.SkipPrimarySetupAccountCreation,
					SetPrimarySetupAccountAsRegularUser: bp.SetPrimarySetupAccountAsRegularUser,
					AutoSetupAdminAccounts: []mdm.AdminAccount{
						{
							ShortName:    usr.UserShortname,
							FullName:     usr.UserLongname,
							PasswordHash: usr.PasswordHash,
							Hidden:       usr.Hidden,
						},
					},
				},
			},
		})
	}

	for _, appURL := range bp.ApplicationURLs {
		level.Debug(w.logger).Log(
			"msg", "creating mdm command request from blueprint",
			"request_type", "InstallApplication",
			"blueprint_name", bp.Name,
			"manifest_url", appURL,
			"device_udid", udid,
		)

		requests = append(requests, &mdm.CommandRequest{
			UDID: udid,
			Command: &mdm.Command{
				RequestType: "InstallApplication",
				InstallApplication: &mdm.InstallApplication{
					ManifestURL:     &appURL,
					ManagementFlags: intPtr(1),
				},
			},
		})
	}

	for _, pid := range bp.ProfileIdentifiers {
		level.Debug(w.logger).Log(
			"msg", "creating mdm command request from blueprint",
			"request_type", "InstallProfile",
			"blueprint_name", bp.Name,
			"profile_identifier", pid,
			"device_udid", udid,
		)
		foundProfile, err := w.profileDB.ProfileById(ctx, pid)
		if err != nil {
			level.Info(w.logger).Log(
				"msg", "retrieve profile from db",
				"blueprint_name", bp.Name,
				"profile_identifier", pid,
				"is_not_found_err", profile.IsNotFound(err),
				"err", err,
			)
			continue
		}

		requests = append(requests, &mdm.CommandRequest{
			UDID: udid,
			Command: &mdm.Command{
				RequestType: "InstallProfile",
				InstallProfile: &mdm.InstallProfile{
					Payload: foundProfile.Mobileconfig,
				},
			},
		})
	}

	for _, r := range requests {
		if _, err := w.cmdsvc.NewCommand(ctx, r); err != nil {
			return errors.Wrap(err, "create new command from blueprint")
		}
	}
	return nil
}

func intPtr(i int) *int {
	return &i
}


text:
'use strict';

var jsdom = require('jsdom'),
    Q     = require('q');

function formInput(html) {
  return Q.Promise(function (resolve, reject) {
    jsdom.env(
      html,
      function (errors, window) {
        var inputs,
            result = [],
            forms = window.document.getElementsByTagName('form');
        forms = Array.prototype.slice.call(forms);
        forms.forEach(function (form, index) {
          result.push({'formIndex': index, 'inputs': [], 'values': {}});
          inputs = form.getElementsByTagName('input');
          inputs = Array.prototype.slice.call(inputs);
          inputs.forEach(function (input) {
            if (input.value) {
              result[index]['values'][input.name] = input.value;
            }
            result[index]['inputs'].push(input.name);
          });
        });
        resolve(result);
      }
    );
  });
}
exports.formInput = formInput;


text:
<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
/**
 * Smarty {math} function plugin
 *
 * Type:     function

 * Name:     math

 * Purpose:  handle math computations in template

 * @link http://smarty.php.net/manual/en/language.function.math.php {math}
 *          (Smarty online manual)
 * @author   Monte Ohrt <monte at ohrt dot com>
 * @param array
 * @param Smarty
 * @return string
 */
function smarty_function_math($params, &$smarty) {
    // be sure equation parameter is present
    if (empty($params['equation'])) {
        $smarty->trigger_error("math: missing equation parameter");
        return;
    }
    // strip out backticks, not necessary for math
    $equation = str_replace('`', '', $params['equation']);
    // make sure parenthesis are balanced
    if (substr_count($equation, "(") != substr_count($equation, ")")) {
        $smarty->trigger_error("math: unbalanced parenthesis");
        return;
    }
    // match all vars in equation, make sure all are passed
    preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!", $equation, $match);
    $allowed_funcs = array('int', 'abs', 'ceil', 'cos', 'exp', 'floor', 'log', 'log10', 'max', 'min', 'pi', 'pow', 'rand', 'round', 'sin', 'sqrt', 'srand', 'tan');
    foreach ($match[1] as $curr_var) {
        if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) {
            $smarty->trigger_error("math: function call $curr_var not allowed");
            return;
        }
    }
    foreach ($params as $key => $val) {
        if ($key != "equation" && $key != "format" && $key != "assign") {
            // make sure value is not empty
            if (strlen($val) == 0) {
                $smarty->trigger_error("math: parameter $key is empty");
                return;
            }
            if (!is_numeric($val)) {
                $smarty->trigger_error("math: parameter $key: is not numeric");
                return;
            }
            $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
        }
    }
    eval("\$smarty_math_result = " . $equation . ";");
    if (empty($params['format'])) {
        if (empty($params['assign'])) {
            return $smarty_math_result;
        } else {
            $smarty->assign($params['assign'], $smarty_math_result);
        }
    } else {
        if (empty($params['assign'])) {
            printf($params['format'], $smarty_math_result);
        } else {
            $smarty->assign($params['assign'], sprintf($params['format'], $smarty_math_result));
        }
    }
}
/* vim: set expandtab: */
?>


text:
<?php

namespace Import\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Class CityRepository
 * @package Import\AppBundle\Entity
 */
class CityRepository extends EntityRepository {}


text:
/*
 * Do not modify this file. This file is generated from the elasticache-2015-02-02.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.ElastiCache.Model
{
    ///
    /// Container for the parameters to the CreateCacheSecurityGroup operation.
    /// The CreateCacheSecurityGroup action creates a new cache security group. Use
    /// a cache security group to control access to one or more cache clusters.
    ///
    ///
    /// <para>
    /// Cache security groups are only used when you are creating a cache cluster outside
    /// of an Amazon Virtual Private Cloud (VPC). If you are creating a cache cluster inside
    /// of a VPC, use a cache subnet group instead. For more information, see CreateCacheSubnetGroup.
    /// </para>
    ///
    public partial class CreateCacheSecurityGroupRequest : AmazonElastiCacheRequest
    {
        private string _cacheSecurityGroupName;
        private string _description;

        ///
        /// Empty constructor used to set  properties independently even when a simple constructor is available
        ///
        public CreateCacheSecurityGroupRequest() { }

        ///
        /// Instantiates CreateCacheSecurityGroupRequest with the parameterized properties
        ///
        /// <param name="cacheSecurityGroupName">A name for the cache security group. This value is stored as a lowercase string. Constraints: Must contain no more than 255 alphanumeric characters. Cannot be the word "Default". Example: mysecuritygroup</param>
        /// <param name="description">A description for the cache security group.</param>
        public CreateCacheSecurityGroupRequest(string cacheSecurityGroupName, string description)
        {
            _cacheSecurityGroupName = cacheSecurityGroupName;
            _description = description;
        }

        ///
        /// Gets and sets the property CacheSecurityGroupName.
        /// <para>
        /// A name for the cache security group. This value is stored as a lowercase string.
        /// </para>
        ///
        /// <para>
        /// Constraints: Must contain no more than 255 alphanumeric characters. Cannot be the
        /// word "Default".
        /// </para>
        ///
        /// <para>
        /// Example: mysecuritygroup
        /// </para>
        ///
        public string CacheSecurityGroupName
        {
            get { return this._cacheSecurityGroupName; }
            set { this._cacheSecurityGroupName = value; }
        }

        // Check to see if CacheSecurityGroupName property is set
        internal bool IsSetCacheSecurityGroupName()
        {
            return this._cacheSecurityGroupName != null;
        }

        ///
        /// Gets and sets the property Description.
        /// <para>
        /// A description for the cache security group.
        /// </para>
        ///
        public string Description
        {
            get { return this._description; }
            set { this._description = value; }
        }

        // Check to see if Description property is set
        internal bool IsSetDescription()
        {
            return this._description != null;
        }

    }
}


text:
echo user1 with correct password
curl -X POST --data "username=testdomain\\testuser01&password=password1" http://127.0.0.1:8000/rauth/
echo

echo
echo user1 with wrong password
curl -X POST --data "username=testdomain\\testuser01&password=wrong" http://127.0.0.1:8000/rauth/
echo

echo
echo user2 with correct password
curl -X POST --data "username=testdomain\\testuser02&password=password2" http://127.0.0.1:8000/rauth/
echo

echo
echo user2 with wrong password
curl -X POST --data "username=testdomain\\testuser02&password=wrong" http://127.0.0.1:8000/rauth/
echo

echo
echo user3 with correct password
curl -X POST --data "username=testdomain\\testuser03&password=password3" http://127.0.0.1:8000/rauth/
echo

echo
echo user3 with wrong password
curl -X POST --data "username=testdomain\\testuser03&password=wrong" http://127.0.0.1:8000/rauth/
echo

echo
echo


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/html/Album/vendor/zendframework/zendframework/library/Zend/EventManager/StaticEventManager.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/Album /

vendor /

zendframework /

zendframework /

library /

Zend /

EventManager /

StaticEventManager.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

33.33%

2 / 6

      CRAP

36.36%

4 / 11

      StaticEventManager

0.00%

0 / 1

33.33%

2 / 6

      19.63

36.36%

4 / 11

       __construct()

0.00%

0 / 1

      2

0.00%

0 / 1

       __clone()

0.00%

0 / 1

      2

0.00%

0 / 1

       getInstance()

0.00%

0 / 1

      6

0.00%

0 / 4

       setInstance(SharedEventManagerInterface $instance)

100.00%

1 / 1

      1

100.00%

2 / 2

       hasInstance()

0.00%

0 / 1

      2

0.00%

0 / 1

       resetInstance()

100.00%

1 / 1

      1

100.00%

2 / 2

1
	<?php

2

9

10
	namespace Zend\EventManager;

11

12

13
	/**

14
	 * Static version of EventManager

15
	 */

16
	class StaticEventManager extends SharedEventManager

17
	{

18
	    /**

19
	     * @var StaticEventManager

20
	     */

21
	    protected static $instance;

22

23
	    /**

24
	     * Singleton

25
	     */

26
	    protected function __construct()

27
	    {

28
	    }

29

30
	    /**

31
	     * Singleton

32
	     *

33
	     * @return void

34
	     */

35
	    private function __clone()

36
	    {

37
	    }

38

39
	    /**

40
	     * Retrieve instance

41
	     *

42
	     * @return StaticEventManager

43
	     */

44
	    public static function getInstance()

45
	    {

46
	        if (null === static::$instance) {

47
	            static::setInstance(new static());

48
	        }

49
	        return static::$instance;

50
	    }

51

52
	    /**

53
	     * Set the singleton to a specific SharedEventManagerInterface instance

54
	     *

55
	     * @param SharedEventManagerInterface $instance

56
	     * @return void

57
	     */

58
	    public static function setInstance(SharedEventManagerInterface $instance)

59
	    {

60
	        static::$instance = $instance;

61
	    }

62

63
	    /**

64
	     * Is a singleton instance defined?

65
	     *

66
	     * @return bool

67
	     */

68
	    public static function hasInstance()

69
	    {

70
	        return (static::$instance instanceof SharedEventManagerInterface);

71
	    }

72

73
	    /**

74
	     * Reset the singleton instance

75
	     *

76
	     * @return void

77
	     */

78
	    public static function resetInstance()

79
	    {

80
	        static::$instance = null;

81
	    }

82
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.6.0-1+deb.sury.org~trusty+1 and PHPUnit 3.7.28 at Tue Oct 7 22:36:47 AMT 2014.


text:
local plist					= require("cp.plist")

local mod = {}

mod.ARCHIVER_KEY 			= "$archiver"
mod.ARCHIVER_VALUE 			= "NSKeyedArchiver"

mod.OBJECTS_KEY 			= "$objects"
mod.TOP_KEY					= "$top"

mod.CFUID					= "CF$UID"

local function checkArchiver(archive)
	return archive[mod.ARCHIVER_KEY] == mod.ARCHIVER_VALUE
end

local function isReference(data)
	return type(data) == 'table' and data[mod.CFUID] ~= nil
end

local function getReferenceID(data)
	return data[mod.CFUID]
end

local function defrostClass(data, defrostFn)
	if data["$class"] then
		local classname = data["$class"]["$classname"]
		-- check if a defrost function was provided
		if type(defrostFn) == "function" then
			local result = defrostFn(data, classname)
			if result then
				return result
			end
		end
		-- if not handled then manage some of the basic types.
		if classname == "NSMutableDictionary" or classname == "NSDictionary" then
			local keys = data["NS.keys"]
			local values = data["NS.objects"]
			local dict = {}
			for i,k in ipairs(keys) do
				dict[k] = values[i]
			end
			return dict
		elseif classname == "NSMutableArray" or classname == "NSArray" then
			return data["NS.objects"]
		elseif classname == "NSMutableSet" or classname == "NSSet" then
			return data["NS.objects"]
		end
	end
	return data
end

--------------------------------------------------------------------------------
-- GETS THE SPECIFIED OBJECT, LOOKING UP THE REFERENCE OBJECT IF NECESSARY:
--------------------------------------------------------------------------------
local function get(data, objects, cache, defrostFn)
	local result = nil
	if isReference(data) then
		-- it's a reference
		local id = getReferenceID(data) + 1
		-- try getting from the cache first
		result = cache[id]
		if not result then
			-- and defrost the 'objects' record
			local object = objects[id]
			if type(object) == "table" then
				-- otherwise, we create a new cached object
				result = {}
				cache[id] = result
				for k,v in pairs(object) do
					result[k] = get(v, objects, cache, defrostFn)
				end
				result = defrostClass(result, defrostFn)
				cache[id] = result
			else
				result = object
				cache[id] = result
			end
		end
	elseif type(data) == "table" then
		result = {}
		for k,v in pairs(data) do
			result[k] = get(v, objects, cache, defrostFn)
		end
		result = defrostClass(result, defrostFn)
	else
		result = data
	end
	return result
end

--- cp.plist.archiver.unarchive(archive, defrostFn) -> table
--- Function
--- Unarchives a LUA table which was archived into a plist using the NSKeyedArchiver.
---
--- Parameters:
---  * `archive`		- the table containing the archive plist as a table
---  * `defrostFn`	- (optional) a function which will be passed an object with a '$class' entry
---
--- Returns:
---  * The unarchived plist table
---
--- Notes:
---  * A 'defrost' function can be provided, which will be called whenever a table with a '$class'
---    structure is present. It will receive the table and the classname and should either return a modified value
---    if the class was handled, or `nil` if it was unable to handle the class. Eg:
---
---    ```
---    local result = archiver.unarchive(archiveData, function(frozen, classname)
--- 	   if classname == "XXMyClass" then
--- 		   return MyClass:new(frozen.foo, frozen.bar)
--- 	   end
---		   return nil
---    end)
---    ```
function mod.unarchive(archive, defrostFn)
	if checkArchiver(archive) then
		local objects = archive[mod.OBJECTS_KEY]
		local cache = {}
		local top = archive[mod.TOP_KEY]
		if top then
			return get(top, objects, cache, defrostFn)
		end
	else
		return nil, string.format("The archive was not archived by %s", mod.ARCHIVER_VALUE)
	end
end

--- cp.plist.archiver.unarchiveFile(filename, defrostFn) -> table
--- Function
--- Unarchives a plist file which was archived into a plist using the NSKeyedArchiver.
---
--- Parameters:
---  * `base64data`	- the file containing the archive plist
---  * `defrostFn`	- (optional) a function which will be passed an object with a '$class' entry
---
--- Returns:
---  * The unarchived plist.
---
--- Notes:
---  * A 'defrost' function can be provided, which will be called whenever a table with a '$class'
---    structure is present. It will receive the table and the classname and should either return a modified value
---    if the class was handled, or `nil` if it was unable to handle the class. Eg:
---
---    ```
---    local result = archiver.unarchiveFile(filename, function(frozen, classname)
--- 	   if classname == "XXMyClass" then
--- 		   return MyClass:new(frozen.foo, frozen.bar)
--- 	   end
---		   return nil
---    end)
---    ```
function mod.unarchiveBase64(base64data, defrostFn)
	local archive, err = plist.base64ToTable(base64data)
	if archive then
		return mod.unarchive(archive, defrostFn)
	else
		return nil, err
	end
end

--- cp.plist.archiver.unarchiveFile(filename, defrostFn) -> table
--- Function
--- Unarchives a plist file which was archived into a plist using the NSKeyedArchiver.
---
--- Parameters:
---  * `filename`	- the file containing the archive plist
---  * `defrostFn`	- (optional) a function which will be passed an object with a '$class' entry
---
--- Returns:
---  * The unarchived plist.
---
--- Notes:
---  * A 'defrost' function can be provided, which will be called whenever a table with a '$class'
---    structure is present. It will receive the table and the classname and should either return a modified value
---    if the class was handled, or `nil` if it was unable to handle the class. Eg:
---
---    ```
---    local result = archiver.unarchiveFile(filename, function(frozen, classname)
--- 	   if classname == "XXMyClass" then
--- 		   return MyClass:new(frozen.foo, frozen.bar)
--- 	   end
---		   return nil
---    end)
---    ```
function mod.unarchiveFile(filename, defrostFn)
	local archive, err = plist.fileToTable(filename)
	if archive then
		return mod.unarchive(archive, defrostFn)
	else
		return nil, err
	end
end

return mod


text:
  <title>tabletable test page</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

Fancy Test Page


text:
package org.basex.query.func.store;

import org.basex.query.*;
import org.basex.query.value.*;

/**
 * Function implementation.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class StoreKeys extends StoreFn {
  @Override
  public Value value(final QueryContext qc) {
    return store(qc).keys();
  }
}


text:
'use strict';

var util = require('util');
var msRest = require('ms-rest');
var ServiceClient = msRest.ServiceClient;
var WebResource = msRest.WebResource;

var models = require('../models');

/**
 * @class
 * Polymorphism
 * __NOTE__: An instance of this class is automatically created for an
 * instance of the AutoRestComplexTestService.
 * Initializes a new instance of the Polymorphism class.
 * @constructor
 *
 * @param {AutoRestComplexTestService} client Reference to the service client.
 */
function Polymorphism(client) {
  this.client = client;
}

/**
 * Get complex types that are polymorphic
 * @param {object} [options]
 *
 * @param {object} [options.customHeaders] headers that will be added to
 * request
 *
 * @param {function} callback
 *
 * @returns {Stream} The Response stream
 */
Polymorphism.prototype.getValid = function (options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//complex/polymorphism/valid';
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  httpRequest.body = null;
  httpRequest.headers['Content-Length'] = 0;
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = httpRequest;
      error.response = response;
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        error.body = parsedErrorResponse;
        if (error.body !== null && error.body !== undefined) {
          error.body = client._models['ErrorModel'].deserialize(error.body);
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = new msRest.HttpOperationResponse();
    result.request = httpRequest;
    result.response = response;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      var parsedResponse;
      try {
        parsedResponse = JSON.parse(responseBody);
        result.body = parsedResponse;
        if (result.body !== null && result.body !== undefined) {
          if(result.body['dtype'] !== null && result.body['dtype'] !== undefined && client._models.discriminators[result.body['dtype']]) {
            result.body = client._models.discriminators[result.body['dtype']].deserialize(result.body);
          } else {
            throw new Error('No discriminator field "dtype" was found in response.');
          }
        }
      } catch (error) {
        var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody));
        deserializationError.request = httpRequest;
        deserializationError.response = response;
        return callback(deserializationError);
      }
    }

    return callback(null, result);
  });
};

/**
 * Put complex types that are polymorphic
 * @param {Fish} [complexBody] Please put a salmon that looks like this:
] {
]         'dtype':'Salmon',
]         'location':'alaska',
]         'iswild':true,
]         'species':'king',
]         'length':1.0,
]         'siblings':[
]           {
]             'dtype':'Shark',
]             'age':6,
]             'birthday': '2012-01-05T01:00:00Z',
]             'length':20.0,
]             'species':'predator',
]           },
]           {
]             'dtype':'Sawshark',
]             'age':105,
]             'birthday': '1900-01-05T01:00:00Z',
]             'length':10.0,
]             'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'),
]             'species':'dangerous',
]           }
]         ]
]       };
 *
 * @param {Number} [complexBody.length]
 *
 * @param {Array} [complexBody.siblings]
 *
 * @param {String} [complexBody.species]
 *
 * @param {object} [options]
 *
 * @param {object} [options.customHeaders] headers that will be added to
 * request
 *
 * @param {function} callback
 *
 * @returns {Stream} The Response stream
 */
Polymorphism.prototype.putValid = function (complexBody, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (complexBody === null || complexBody === undefined) {
      throw new Error('\'complexBody\' cannot be null');
    }
    if (complexBody !== null && complexBody !== undefined) {
      if(complexBody['dtype'] !== null && complexBody['dtype'] !== undefined && client._models.discriminators[complexBody['dtype']]) {
        client._models.discriminators[complexBody['dtype']].validate(complexBody);
      } else {
        throw new Error('No discriminator field "dtype" was found in parameter "complexBody".');
      }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//complex/polymorphism/valid';
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  requestContent = JSON.stringify(msRest.serializeObject(complexBody));
  httpRequest.body = requestContent;
  httpRequest.headers['Content-Length'] = Buffer.isBuffer(requestContent) ? requestContent.length : Buffer.byteLength(requestContent, 'UTF8');
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = httpRequest;
      error.response = response;
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        error.body = parsedErrorResponse;
        if (error.body !== null && error.body !== undefined) {
          error.body = client._models['ErrorModel'].deserialize(error.body);
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = new msRest.HttpOperationResponse();
    result.request = httpRequest;
    result.response = response;
    if (responseBody === '') responseBody = null;

    return callback(null, result);
  });
};

/**
 * Put complex types that are polymorphic, attempting to omit required
 * 'birthday' field - the request should not be allowed from the client
 * @param {Fish} [complexBody] Please attempt put a sawshark that looks like this, the client should not allow this data to be sent:
] {
]     "dtype": "sawshark",
]     "species": "snaggle toothed",
]     "length": 18.5,
]     "age": 2,
]     "birthday": "2013-06-01T01:00:00Z",
]     "location": "alaska",
]     "picture": base64(FF FF FF FF FE),
]     "siblings": [
]         {
]             "dtype": "shark",
]             "species": "predator",
]             "birthday": "2012-01-05T01:00:00Z",
]             "length": 20,
]             "age": 6
]         },
]         {
]             "dtype": "sawshark",
]             "species": "dangerous",
]             "picture": base64(FF FF FF FF FE),
]             "length": 10,
]             "age": 105
]         }
]     ]
] }
 *
 * @param {Number} [complexBody.length]
 *
 * @param {Array} [complexBody.siblings]
 *
 * @param {String} [complexBody.species]
 *
 * @param {object} [options]
 *
 * @param {object} [options.customHeaders] headers that will be added to
 * request
 *
 * @param {function} callback
 *
 * @returns {Stream} The Response stream
 */
Polymorphism.prototype.putValidMissingRequired = function (complexBody, options, callback) {
  var client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (complexBody === null || complexBody === undefined) {
      throw new Error('\'complexBody\' cannot be null');
    }
    if (complexBody !== null && complexBody !== undefined) {
      if(complexBody['dtype'] !== null && complexBody['dtype'] !== undefined && client._models.discriminators[complexBody['dtype']]) {
        client._models.discriminators[complexBody['dtype']].validate(complexBody);
      } else {
        throw new Error('No discriminator field "dtype" was found in parameter "complexBody".');
      }
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  var requestUrl = this.client.baseUri +
                   '//complex/polymorphism/missingrequired/invalid';
  // trim all duplicate forward slashes in the url
  var regex = /([^:]\/)\/+/gi;
  requestUrl = requestUrl.replace(regex, '$1');

  // Create HTTP transport objects
  var httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.headers = {};
  httpRequest.url = requestUrl;
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  // Serialize Request
  var requestContent = null;
  requestContent = JSON.stringify(msRest.serializeObject(complexBody));
  httpRequest.body = requestContent;
  httpRequest.headers['Content-Length'] = Buffer.isBuffer(requestContent) ? requestContent.length : Buffer.byteLength(requestContent, 'UTF8');
  if(options) {
    for(var headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  // Send Request
  return client.pipeline(httpRequest, function (err, response, responseBody) {
    if (err) {
      return callback(err);
    }
    var statusCode = response.statusCode;
    if (statusCode !== 200) {
      var error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = httpRequest;
      error.response = response;
      if (responseBody === '') responseBody = null;
      var parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        error.body = parsedErrorResponse;
        if (error.body !== null && error.body !== undefined) {
          error.body = client._models['ErrorModel'].deserialize(error.body);
        }
      } catch (defaultError) {
        error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    var result = new msRest.HttpOperationResponse();
    result.request = httpRequest;
    result.response = response;
    if (responseBody === '') responseBody = null;

    return callback(null, result);
  });
};

module.exports = Polymorphism;


text:
{{{
  "title": "Platform Specific: AF CLI Login Issues",
  "date": "1-22-2015",
  "author": "Chris Sterling",
  "attachments": [],
  "contentIsHTML": false
}}}

### IMPORTANT

This document is for users of AppFog v1. This document does not apply to the current AppFog service that is located in CenturyLink Cloud Control Portal.

### Documentation

If you can log into the web console, but you're running into issues with the af login command, try this:

$ rm ~/.af_token
$ af login


text:
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var request = require('request');
var flash = require('connect-flash');

exports.setup = function (User, config) {
    passport.use(new GoogleStrategy({
            clientID: "819851225510-qkuq5o6u2aid8mbr7g729bt0pvd0f13k.apps.googleusercontent.com",
            clientSecret:"Zr1P819rNcW1Up1ThvsWhjtC",
            callbackURL: "http://localhost:9000/auth/google/callback"
        },
        function(accessToken, refreshToken, profile, done) {

            if(profile._json.domain === "paradigmcreatives.com"){
                console.log(profile._json);
                User.findOne({
                    'google.id': profile.id
                }, function(err, user) {
                    if (!user) {
                        user = new User({
                            name: profile.displayName,
                            email: profile.emails[0].value,
                            role: 'user',
                            username: profile.username,
                            provider: 'google',
                            google: profile._json
                        });
                        user.save(function(err) {
                            if (err) done(err);
                            return done(err, user);
                        });
                    } else {
                        return done(err, user);
                    }
                });
            }
            else {
                console.log("fail");
                return done(null, false, { message: 'Invalid host Domain.' });
            }
        }
    ));
};


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;

namespace Microsoft.WindowsAzure.MobileServices
{
    /// <summary>
    /// Provides serialization and deserialization for a
    /// <see cref="MobileServiceClient"/>.
    /// </summary>
    internal class MobileServiceSerializer
    {
        /// <summary>
        /// The version system property as a string
        /// </summary>
        internal static readonly string VersionSystemPropertyString = MobileServiceSystemProperties.Version.ToString().ToLowerInvariant();

        /// <summary>
        /// The version system property as a string
        /// </summary>
        internal static readonly string UpdatedAtSystemPropertyString = MobileServiceSystemProperties.UpdatedAt.ToString().ToLowerInvariant();

        /// <summary>
        /// The version system property as a string
        /// </summary>
        internal static readonly string CreatedAtSystemPropertyString = MobileServiceSystemProperties.CreatedAt.ToString().ToLowerInvariant();

        /// <summary>
        /// The deleted system property as a string
        /// </summary>
        internal static readonly string DeletedSystemPropertyString = MobileServiceSystemProperties.Deleted.ToString().ToLowerInvariant();

        /// <summary>
        /// A regex for validating string ids
        /// </summary>
        private static Regex stringIdValidationRegex = new Regex(@"([\u0000-\u001F]|[\u007F-\u009F]|[""\+\?\\\/\`]|^\.{1,2}$)");

        /// <summary>
        /// The long type.
        /// </summary>
        private static Type longType = typeof(long);

        /// <summary>
        /// The int type.
        /// </summary>
        private static Type intType = typeof(int);

        /// <summary>
        /// The max length of valid string ids.
        /// </summary>
        internal const int MaxStringIdLength = 255;

        /// <summary>
        /// The JSON serializer settings to use with the
        /// <see cref="MobileServiceSerializer"/>.
        /// </summary>
        public MobileServiceJsonSerializerSettings SerializerSettings { get; set; }

        /// <summary>
        /// Creates a new instance of the <see cref="MobileServiceSerializer"/>
        /// class.
        /// </summary>
        public MobileServiceSerializer()
        {
            this.SerializerSettings = new MobileServiceJsonSerializerSettings();
        }

        /// <summary>
        /// Returns the system properties for a given type.
        /// </summary>
        /// <param name="type">The type for which to get the system properties.</param>
        /// <returns>
        /// The system properties for a given type.
        /// </returns>
        public MobileServiceSystemProperties GetSystemProperties(Type type)
        {
            return this.SerializerSettings.ContractResolver.ResolveSystemProperties(type);
        }

        /// <summary>
        /// Tries to get the value of the id property from an instance.
        /// </summary>
        /// <param name="instance">
        /// The instance to get the id property value from.
        /// </param>
        /// <param name="ignoreCase">
        /// Set to true to find any variant spelling of the id is in the object
        /// </param>
        /// <param name="id">
        /// The value of the id property from the instance if the instance has an
        /// id property.
        /// </param>
        /// <returns>
        /// Returns 'true' if the instance had an id property; 'false' otherwise.
        /// </returns>
        public static bool TryGetId(JObject instance, bool ignoreCase, out object id)
        {
            bool gotId = false;
            JToken idToken = null;

            id = null;

            if (ignoreCase)
            {
                gotId = instance.TryGetValue(MobileServiceSystemColumns.Id, StringComparison.OrdinalIgnoreCase, out idToken);
            }
            else
            {
                gotId = instance.TryGetValue(MobileServiceSystemColumns.Id, out idToken);
            }

            if (gotId)
            {
                JValue idValue = idToken as JValue;
                if (idValue == null)
                {
                    gotId = false;
                }
                else
                {
                    id = idValue.Value;
                }
            }

            return gotId;
        }

        /// <summary>
        /// Gets the value of the id property from an instance. Also ensures that the
        /// id is valid.
        /// </summary>
        /// <param name="instance">
        /// The instance to get the id property value from.
        /// </param>
        /// <param name="ignoreCase">
        /// Set to true to find any variant spelling of the id is in the object
        /// </param>
        /// <param name="allowDefault">
        /// Indicates if a defualt value for the id is considered valid.
        /// </param>
        /// <returns>
        /// The id property value.
        /// </returns>
        public static object GetId(JObject instance, bool ignoreCase = false, bool allowDefault = false)
        {
            Debug.Assert(instance != null);

            object id = null;
            bool gotID = TryGetId(instance, ignoreCase, out id);

            // Check that the id is present but incorrectly cased
            if (!gotID && !ignoreCase && TryGetId(instance, true, out id))
            {
                throw new ArgumentException(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "The casing of the '{0}' property is invalid.",
                        MobileServiceSystemColumns.Id),
                     "instance");
            }

            if (gotID)
            {
                EnsureValidId(id, allowDefault);
            }
            else if (!allowDefault)
            {
                throw new ArgumentException(
                       string.Format(
                           CultureInfo.InvariantCulture,
                           "Expected {0} member not found.",
                           MobileServiceSystemColumns.Id),
                       "instance");
            }

            return id;
        }

        /// <summary>
        /// Removes all system properties from the instance
        /// if the instance is determined to have a string id and therefore be for table that
        /// supports system properties.
        /// </summary>
        /// <param name="instance">The instance to remove the system properties from.</param>
        /// <param name="version">Set to the value of the version system property before it is removed.</param>
        /// <param name="propertiesToKeep">The system properties to keep</param>        /// <returns>
        /// The instance with the system properties removed.
        /// </returns>
        public static JObject RemoveSystemProperties(JObject instance, out string version, MobileServiceSystemProperties propertiesToKeep = MobileServiceSystemProperties.None)
        {
            version = null;
            var systemProperties = new String[]{MobileServiceSerializer.CreatedAtSystemPropertyString, MobileServiceSerializer.DeletedSystemPropertyString, MobileServiceSerializer.VersionSystemPropertyString, MobileServiceSerializer.UpdatedAtSystemPropertyString}.AsEnumerable<String>();

            bool haveCloned = false;
            foreach (JProperty property in instance.Properties())
            {
                if (systemProperties.Contains(property.Name.ToLowerInvariant()))
                {
                    // We don't want to alter the original jtoken passed in by the caller
                    // so if we find a system property to remove, we have to clone first
                    if (!haveCloned)
                    {
                        instance = instance.DeepClone() as JObject;
                        haveCloned = true;
                    }

                    if (String.Equals(property.Name, MobileServiceSystemColumns.Version, StringComparison.OrdinalIgnoreCase))
                    {
                        version = (string)instance[property.Name];
                        if ((propertiesToKeep & MobileServiceSystemProperties.Version) == MobileServiceSystemProperties.Version)
                        {
                            continue;
                        }
                    }
                    else if (propertiesToKeep == MobileServiceSystemProperties.All ||
                        IsKeptSystemProperty(property.Name, propertiesToKeep, MobileServiceSystemProperties.CreatedAt, MobileServiceSerializer.CreatedAtSystemPropertyString) ||
                        IsKeptSystemProperty(property.Name, propertiesToKeep, MobileServiceSystemProperties.UpdatedAt, MobileServiceSerializer.UpdatedAtSystemPropertyString))
                    {
                        continue;
                    }

                    instance.Remove(property.Name);
                }
            }

            return instance;
        }

        /// <summary>
        /// Checks if the given system property should be kept or removed from the returned item
        /// </summary>
        /// <param name="propertyName">
        /// Name of the system property to see if it should be removed
        /// </param>
        /// <param name="propertiesToKeep">
        /// The list of system properties to be kept
        /// </param>
        /// <param name="property">
        /// Type of the system property to check
        /// </param>
        /// <param name="systemPropertyName">
        /// Name of the actual system property to look for
        /// </param>
        private static bool IsKeptSystemProperty(string propertyName, MobileServiceSystemProperties propertiesToKeep, MobileServiceSystemProperties property, string systemPropertyName)
        {
            if ((propertiesToKeep & property) == property &&
                    String.Equals(propertyName, systemPropertyName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Ensures that the id is valid. Throws an exception if the id is not valid.
        /// </summary>
        /// <param name="allowDefault">
        /// Indicates if a defualt value for the id is considered valid.
        /// </param>
        /// <param name="id">The id to validate.</param>
        public static void EnsureValidId(object id, bool allowDefault = false)
        {
            if (id == null)
            {
                if (!allowDefault)
                {
                    throw new InvalidOperationException("The id can not be null or an empty string.");
                }
                return;
            }

            if (id is string)
            {
                EnsureValidStringId(id, allowDefault);
            }
            if (IsIntegerId(id))
            {
                EnsureValidIntId(id, allowDefault);
            }
        }

        public static bool IsIntegerId(JsonProperty idProperty)
        {
            return IsIntegerId(idProperty.PropertyType);
        }

        public static bool IsIntegerId(object id)
        {
            return id != null && IsIntegerId(id.GetType());
        }

        public static bool IsIntegerId(Type idType)
        {
            bool isIntegerIdType = idType == longType ||
                                   idType == intType;
            return isIntegerIdType;
        }

        private static void EnsureValidIntId(object id, bool allowDefault)
        {
            long longId = Convert.ToInt64(id);
            if (longId < 0 ||
                (!allowDefault && longId == 0))
            {
                throw new InvalidOperationException(
                    string.Format("The integer id '{0}' is not a positive integer value.", longId));
            }
        }

        public static void EnsureValidStringId(object id, bool allowDefault = false)
        {
            string stringId = (string)id;
            if (stringId.Length > MaxStringIdLength)
            {
                throw new InvalidOperationException(
                    string.Format("The string id '{0}' is longer than the max string id length of {1} characters.",
                        stringId,
                        MaxStringIdLength));
            }
            else if (stringIdValidationRegex.IsMatch(stringId))
            {
                throw new InvalidOperationException(
                    string.Format("The string id '{0}' is invalid. An id must not contain any control characters or the characters \",+,?,\\,/,`.", stringId));
            }
            else if (!allowDefault && stringId.Length == 0)
            {
                throw new InvalidOperationException("The id can not be null or an empty string.");
            }
        }

        /// <summary>
        /// Ensures that the id type is valid for the given type parameter. Throws an exception if the id is not valid.
        /// </summary>
        /// <typeparam name="T">The type to validate the id against.</typeparam>
        /// <param name="id">The id to validate.</param>
        public void EnsureValidIdForType<T>(object id)
        {
            Type idPropertyType = this.GetIdPropertyType<T>();

            if (id != null)
            {
                Type idType = id.GetType();
                bool isInvalid = false;

                // Allow an int id to be passed in for item types that have a long id and
                // vice-versa
                if (idPropertyType == longType || idPropertyType == intType)
                {
                    if (idType != longType && idType != intType)
                    {
                        isInvalid = true;
                    }

                }
                else if (!idPropertyType.GetTypeInfo().IsAssignableFrom(idType.GetTypeInfo()))
                {
                    isInvalid = true;
                }

                if (isInvalid)
                {
                    throw new InvalidOperationException(
                    string.Format("The id parameter type '{0}' is invalid for looking up items of type '{1}'.",
                        id.GetType().FullName,
                        typeof(T).FullName));
                }

            }
            else if (idPropertyType.GetTypeInfo().IsValueType)
            {
                throw new InvalidOperationException(
                     string.Format("The id parameter type '{0}' is invalid for looking up items of type '{1}'.",
                         "<null>",
                         typeof(T).FullName));
            }

        }

        /// <summary>
        /// Sets the instance's id property value to the default id value.
        /// </summary>
        /// <param name="instance">
        /// The instance on which to clear the id property.
        /// </param>
        public static void SetIdToDefault(JObject instance)
        {
            if (instance != null)
            {
                instance[MobileServiceSystemColumns.Id] = null;
            }
        }

        /// <summary>
        /// Gets the value of the id property from an instance.
        /// </summary>
        /// <param name="instance">
        /// The instance to get the id property value from.
        /// </param>
        /// <param name="ignoreCase">
        /// Set to true to find any variant spelling of the id is in the object
        /// </param>
        /// <param name="allowDefault">
        /// Indicates if a defualt value for the id is considered valid.
        /// </param>
        /// <returns>
        /// The id property value.
        /// </returns>
        public object GetId(object instance, bool ignoreCase = false, bool allowDefault = false)
        {
            Debug.Assert(instance != null);

            object id = null;

            JObject jobject = instance as JObject;
            if (jobject != null)
            {
                id = GetId(jobject, ignoreCase, allowDefault);
            }
            else
            {
                JsonProperty idProperty = this.SerializerSettings.ContractResolver.ResolveIdProperty(instance.GetType());
                id = idProperty.ValueProvider.GetValue(instance);
                EnsureValidId(id, allowDefault);
            }

            return id;
        }

        /// <summary>
        /// Returns the type of the Id property for items of the given type.
        /// </summary>
        /// <typeparam name="T">The type of the item that should have an id property.</typeparam>
        /// <returns>
        /// The type of the Id property for items of the given type, or null if the type does not
        /// have an Id property.
        /// </returns>
        public Type GetIdPropertyType<T>(bool throwIfNotFound = true)
        {
            Type idPropertyType = null;
            JsonProperty idProperty = this.SerializerSettings.ContractResolver.ResolveIdProperty(typeof(T), throwIfNotFound);

            if (idProperty != null)
            {
                idPropertyType = idProperty.PropertyType;
            }

            return idPropertyType;
        }

        /// <summary>
        /// Indicates if the id value is the default id value.
        /// </summary>
        /// <param name="id">
        /// The id value to determine if it is the default.
        /// </param>
        /// <returns>
        /// <c>true</c> if the id value is the default value;
        /// <c>false</c> otherwise.
        /// </returns>
        public static bool IsDefaultId(object id)
        {
            return id == null ||
                   object.Equals(id, 0L) ||
                   object.Equals(id, 0) ||
                   (id is string && string.IsNullOrEmpty((string)id)) ||
                   object.Equals(id, 0.0) ||
                   object.Equals(id, 0.0F) ||
                   object.Equals(id, 0.0M);
        }

        /// <summary>
        /// Sets the instance's id property value to the default id value.
        /// </summary>
        /// <param name="instance">
        /// The instance on which to clear the id property.
        /// </param>
        public void SetIdToDefault(object instance)
        {
            Debug.Assert(instance != null);

            JObject jobject = instance as JObject;
            if (jobject != null)
            {
                SetIdToDefault(jobject);
            }
            else
            {
                JsonProperty idProperty = this.SerializerSettings.ContractResolver.ResolveIdProperty(instance.GetType());
                idProperty.ValueProvider.SetValue(instance, null);
            }
        }

        /// <summary>
        /// Deserializes an array of JSON values into a collection of objects.
        /// </summary>
        /// <param name="json">
        /// The JSON array.
        /// </param>
        /// <param name="type">
        /// The type to deserialize objects into.
        /// </param>
        /// <returns>
        /// The collection of deserialized instances.
        /// </returns>
        public IEnumerable<object> Deserialize(JArray json, Type type)
        {
            Debug.Assert(json != null);
            Debug.Assert(type != null);

            JsonSerializer jsonSerializer = this.SerializerSettings.GetSerializerFromSettings();
            return json.Select(jtoken => jtoken.ToObject(type, jsonSerializer));
        }

        /// <summary>
        /// Deserializes an array of JSON values into a collection of objects.
        /// </summary>
        /// <typeparam name="T">
        /// The type of objects to deserialize to.
        /// </typeparam>
        /// <param name="json">
        /// The JSON array.
        /// </param>
        /// <returns>
        /// The collection of deserialized instances.
        /// </returns>
        public IEnumerable<T> Deserialize<T>(JArray json)
        {
            Debug.Assert(json != null);

            JsonSerializer jsonSerializer = this.SerializerSettings.GetSerializerFromSettings();
            return json.Select(jtoken => Deserialize<T>(jtoken, jsonSerializer));
        }

        /// <summary>
        /// Deserializes a JSON string into an instance of type T.
        /// </summary>
        /// <typeparam name="T">
        /// The type of object to deserialize.
        /// </typeparam>
        /// <param name="json">
        /// The JSON string.
        /// </param>
        /// <returns>
        /// The deserialized instance.
        /// </returns>
        public T Deserialize<T>(JToken json)
        {
            Debug.Assert(json != null);

            JsonSerializer jsonSerializer = this.SerializerSettings.GetSerializerFromSettings();
            return Deserialize<T>(json, jsonSerializer);
        }

        /// <summary>
        /// Deserializes a JSON string into an instance.
        /// </summary>
        /// <remarks>
        /// This method uses JSON.Net's <see cref="JsonConvert.PopulateObject(string, object)"/>
        /// API to set the member values on the instance from the values
        /// in the JSON string.
        /// </remarks>
        /// <typeparam name="T">
        /// The type of object to deserialize into.
        /// </typeparam>
        /// <param name="json">
        /// The JSON.
        /// </param>
        /// <param name="instance">
        /// The instance to deserialize into.
        /// </param>
        public void Deserialize<T>(JToken json, T instance)
        {
            Debug.Assert(json != null);
            Debug.Assert(instance != null);

            TransformSerializationException<T>(() =>
            {
                JsonConvert.PopulateObject(json.ToString(), instance, this.SerializerSettings);
            }, json);
        }

        /// <summary>
        /// Serializes an instance into a JSON string.
        /// </summary>
        /// <param name="instance">
        /// The instance to serialize.
        /// </param>
        /// <returns>
        /// The instance serialized into a JToken.
        /// </returns>
        public JToken Serialize(object instance)
        {
            Debug.Assert(instance != null);

            JsonSerializer jsonSerializer = this.SerializerSettings.GetSerializerFromSettings();
            return JToken.FromObject(instance, jsonSerializer);
        }

        private T Deserialize<T>(JToken json, JsonSerializer jsonSerializer)
        {
            T result = default(T);
            TransformSerializationException<T>(() =>
            {
                result = json.ToObject<T>(jsonSerializer);
            }, json);
            return result;
        }

        private void TransformSerializationException<T>(Action action, JToken token)
        {
            try
            {
                action();
            }
            catch (JsonSerializationException ex)
            {
                var obj = token as JObject;
                if (obj == null)
                {
                    throw;
                }

                object id;
                bool idTokenIsString = TryGetId(obj, true, out id) && id.GetType() == typeof(string);

                JsonProperty idProperty = this.SerializerSettings.ContractResolver.ResolveIdProperty(typeof(T), throwIfNotFound: false);
                bool idPropertyIsInteger = idProperty != null && IsIntegerId(idProperty);

                if (idTokenIsString && idPropertyIsInteger)
                {
                    throw new JsonSerializationException(ex.Message + Environment.NewLine + "You might be affected by Mobile Services latest changes to support string Ids. For more details: http://go.microsoft.com/fwlink/?LinkId=330396", ex);
                }

                throw;
            }
        }
    }
}


text:
//
//  MFMIDIMessage.h
//  MIDIFish
//
//  Created by Hari Karam Singh on 01/02/2015.
//
//

#import <Foundation/Foundation.h>
#import <CoreMIDI/CoreMIDI.h>

/////////////////////////////////////////////////////////////////////////
#pragma mark - Defs
/////////////////////////////////////////////////////////////////////////

typedef NS_ENUM(UInt8, MFMIDIMessageType) {
    kMFMIDIMessageTypeNoteOff                           = 0x80,
    kMFMIDIMessageTypeNoteOn                            = 0x90,
    kMFMIDIMessageTypePolyphonicAftertouch              = 0xA0,
    kMFMIDIMessageTypeControlChange                     = 0xB0,
    kMFMIDIMessageTypeProgramChange                     = 0xC0,
    kMFMIDIMessageTypeChannelAftertouch                 = 0xD0,
    kMFMIDIMessageTypePitchbend                         = 0xE0,
    kMFMIDIMessageTypeSysex                             = 0xF0
};

/////////////////////////////////////////////////////////////////////////
#pragma mark -
/////////////////////////////////////////////////////////////////////////

@interface MFMIDIMessage : NSObject <NSCopying>

/////////////////////////////////////////////////////////////////////////
#pragma mark - Life Cycle
/////////////////////////////////////////////////////////////////////////

/** Init with the Message type anf Channel and then use the setters to assign values in the semantics of the message type */
+ (instancetype)messageWithType:(MFMIDIMessageType)type
                        channel:(UInt8)channel;

/**
 Create a Message with 3 raw bytes.

 @param status The first byte (status byte).
 @param data1  The second byte.
 @param data2  The third byte.
 */
+ (instancetype)messageWithBytes:(UInt8)status :(UInt8)data1 :(UInt8)data2;

/**
 Init with the given data. Can be longer than 3 bytes (ie sysex). Data is copied unless it is NSMutableData in which case it's retained
 */
+ (instancetype)messageWithData:(NSData *)data;

/**
  Creates a new message with the given packet.

 @param packet The packet whose data is to be wrapped in the message.

 @return A new message wrapper for the data.
 */
+ (instancetype)messageWithPacket:(MIDIPacket *)packet;

/**
 Parses data into zerp or more message objects, based on message
 lengths in the MIDI protocol.

 Example: (data)[0x90, 10, 127, 0x80, 10, 0] -> messages would
 result in 2 messages being made, one a note on, another a note off.

 @param data The data to parse.

 @return Zero or more objects in an array (never returns nil).
 */
+ (NSArray *)messagesWithData:(NSData *)data;
+ (NSArray *)messagesWithPacket:(MIDIPacket *)packet;
+ (NSArray *)messagesWithPacketList:(MIDIPacketList *)list;

/** YES if same class and the data bytes equal */
- (BOOL)isEqual:(id)object;

/** Copies the bytes too */
- (id)copyWithZone:(NSZone *)zone;

/////////////////////////////////////////////////////////////////////////
#pragma mark - Properties
/////////////////////////////////////////////////////////////////////////

/** YES when the message is zero-length or zeroed out */
@property (nonatomic, readonly, getter = isEmpty) BOOL empty;

/** The length of the data of this message in bytes */
@property (nonatomic, readonly) NSUInteger length;

/** The MIDI Channel 0-15 */
@property (nonatomic) UInt8 channel;

/** NoteOn, Pitchbend, etc */
@property (nonatomic) MFMIDIMessageType type;

/// The full first byte. For most messages its the type (msb) + channel (lsb)
@property (nonatomic) UInt8 status;

/**
 These all get/set the second byte.
 They are named conveniently for parts of common message types.

 key:            note messages
 controller:     control change messages
 programNumber:  program change messages
 data1:          generic
 */
@property (nonatomic) UInt8 key, controller, data1;

/**
 These all get/set the third byte.
 They are named conveniently for parts of common message types.

 velocity:       note messages
 value:          control change messages
 pressures:      aftertouch messages
 data2:          generic
 */
@property (nonatomic) UInt8 velocity, value, programNumber, channelPressure, keyPressure, data2;

/**
 Used for double (14bit) precision values like Pitchbend
 */
@property (nonatomic) UInt16 doublePrecisionValue, pitchbendValue;

/// The wrapped mutable data object. You can still mutate it even though its readonly
@property (nonatomic, readonly) NSMutableData *data;

/// The mutableBytes on the NSMutableData
@property (nonatomic, readonly) UInt8 *bytes;

/////////////////////////////////////////////////////////////////////////
#pragma mark - Public Methods
/////////////////////////////////////////////////////////////////////////

/**
 Sets a single byte at a given place in the message's data buffer.
 The message will grow if it needs to.

 @param byte  The value to apply.
 @param index The index at which to
 */
- (void)setByte:(UInt8)byte atIndex:(NSUInteger)index;

/** Need to use a block here as packet lists have a scope and their handling needs to occur within the same scope or EXC_BAD_ACCESS will happen sometimes */
- (void)toMIDIPacketList:(void(^)(MIDIPacketList *packetList))packetListHandler;

/////////////////////////////////////////////////////////////////////////
#pragma mark - Subscripting
/////////////////////////////////////////////////////////////////////////

/**
 Subscripting support.

 @param number A one-byte unsigned NSNumber.
 @param idx    The index to set this byte at in the data buffer.
 */
- (void)setObject:(NSNumber *)number atIndexedSubscript:(NSUInteger)idx;

@end


text:
<?php

/* SensioDistributionBundle:Configurator:check.html.twig */
class __TwigTemplate_c2f2b814906c4f3ad5d1b39f4b0eb500 extends Twig_Template
{
    protected $parent;

    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = array();
        $this->blocks = array(
            'content' => array($this, 'block_content'),
        );
    }

    public function getParent(array $context)
    {
        $parent = "SensioDistributionBundle::Configurator/layout.html.twig";
        if ($parent instanceof Twig_Template) {
            $name = $parent->getTemplateName();
            $this->parent[$name] = $parent;
            $parent = $name;
        } elseif (!isset($this->parent[$parent])) {
            $this->parent[$parent] = $this->env->loadTemplate($parent);
        }

        return $this->parent[$parent];
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $context = array_merge($this->env->getGlobals(), $context);

        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_content($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        if (twig_length_filter($this->env, $this->getContext($context, 'majors'))) {
            // line 5
            echo "
Major Problems that need to be fixed now

            We have detected ";
            // line 7
            echo twig_escape_filter($this->env, twig_length_filter($this->env, $this->getContext($context, 'majors')), "html");
            echo " major problems.
            You must fix them before continuing:

            ";
            // line 11
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($this->getContext($context, 'majors'));
            foreach ($context['_seq'] as $context['_key'] => $context['message']) {
                // line 12
                echo "
";
                echo twig_escape_filter($this->env, $this->getContext($context, 'message'), "html");
                echo "

            ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
            $context = array_merge($_parent, array_intersect_key($context, $_parent));
            // line 14
            echo "

    ";
        }
        // line 16
        echo "
    ";
        // line 17
        if (twig_length_filter($this->env, $this->getContext($context, 'minors'))) {
            // line 18
            echo "
Some Recommandations

            ";
            // line 21
            if (twig_length_filter($this->env, $this->getContext($context, 'majors'))) {
                // line 22
                echo "            Additionally, we
            ";
            } else {
                // line 24
                echo "            We
            ";
            }
            // line 26
            echo "            have detected some minor problems that we recommend you to fix to have a better Symfony
            experience:

                ";
            // line 30
            $context['_parent'] = (array) $context;
            $context['_seq'] = twig_ensure_traversable($this->getContext($context, 'minors'));
            foreach ($context['_seq'] as $context['_key'] => $context['message']) {
                // line 31
                echo "
";
                echo twig_escape_filter($this->env, $this->getContext($context, 'message'), "html");
                echo "

                ";
            }
            $_parent = $context['_parent'];
            unset($context['_seq'], $context['_iterated'], $context['_key'], $context['message'], $context['_parent'], $context['loop']);
            $context = array_merge($_parent, array_intersect_key($context, $_parent));
            // line 33
            echo "

    ";
        }
        // line 37
        echo "
    ";
        // line 38
        if ((!twig_length_filter($this->env, $this->getContext($context, 'majors')))) {
            // line 39
            echo "

env, $this->getContext($context, 'url'), "html");
            echo "\">Configure your Symfony Application online

    ";
        }
    }

    public function getTemplateName()
    {
        return "SensioDistributionBundle:Configurator:check.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
@interface CupOverflowException: NSException
@end


text:
function SectionController($scope, $http) {
    $scope.errorMsg = '';

    $scope.showNewSectionDialog = function () {
        $scope.errorMsg = '';
        $scope.newSection = {
            name: ''
        };
        $("#float-box-newSection").modal("show");
    };
    $scope.showEditSectionDialog = function (sectionId) {
        $scope.errorMsg = '';

        $http({
            method: 'GET',
            url: '/sectionadmin/find',
            cache: false,
            params: { id: sectionId, option: 'simple', random: Math.random() }
        })
        .success(function (result, status, headers, config) {
            if (result.success) {
                $scope.editingSection = result.data;
                $("#float-box-editSection").modal("show");
            } else {
                msg(result.errorMsg);
            }
        })
        .error(function (result, status, headers, config) {
            msg(result.errorMsg);
        });
    };

    $scope.createSection = function () {
        if (isStringEmpty($scope.newSection.name)) {
            $scope.errorMsg = '请输入版块名称。';
            return false;
        }

        $http({
            method: 'POST',
            url: '/sectionadmin/create',
            data: $scope.newSection
        })
        .success(function (result, status, headers, config) {
            if (result.success) {
                window.location.reload();
            } else {
                $scope.errorMsg = result.errorMsg;
            }
        })
        .error(function (result, status, headers, config) {
            $scope.errorMsg = result.errorMsg;
        });
    };
    $scope.updateSection = function () {
        if (isStringEmpty($scope.editingSection.name)) {
            $scope.errorMsg = '请输入版块名称。';
            return false;
        }

        $http({
            method: 'POST',
            url: '/sectionadmin/update',
            data: $scope.editingSection
        })
        .success(function (result, status, headers, config) {
            if (result.success) {
                window.location.reload();
            } else {
                $scope.errorMsg = result.errorMsg;
            }
        })
        .error(function (result, status, headers, config) {
            $scope.errorMsg = result.errorMsg;
        });
    };
}


text:
#ifndef _SYS_MMAN_H
# error "Never use <bits/mman.h> directly; include <sys/mman.h> instead."
#endif

/* AArch64 specific definitions, should be in sync with
   arch/arm64/include/uapi/asm/mman.h.  */

#define PROT_BTI	0x10

#include <bits/mman-map-flags-generic.h>

/* Include generic Linux declarations.  */
#include <bits/mman-linux.h>