text:
namespace Mixins.Method1
{
    public class LogicEntity : Entity
    {
        private LogicCollection m_oLogic = new LogicCollection();

        public bool AddLogic(string logic)
        {
            return false;
        }

        public bool AddExistingLogic(Logic logic)
        {
            return false;
        }

        public bool DelLogic(string logic)
        {
            return false;
        }

        public Logic GetLogic(string logic)
        {
            return null;
        }

        public bool HasLogic(string logic)
        {
            return false;
        }

        public int DoAction(Action action)
        {
            return 0;
        }

        public int DoAction(string act, long data1, long data2, long data3, long data4, string data)
        {
            return 0;
        }

        public int DoAction(string act, long data1, long data2, long data3, long data4)
        {
            return DoAction(act, data1, data2, data3, data4, "");
        }

        public int DoAction(string act, long data1, long data2, long data3)
        {
            return DoAction(act, data1, data2, data3, 0);
        }

        public int DoAction(string act, long data1, long data2)
        {
            return DoAction(act, data1, data2, 0);
        }

        public int DoAction(string act, long data1)
        {
            return DoAction(act, data1, 0);
        }

        public int DoAction(string act)
        {
            return DoAction(act, 0);
        }
    }
}


text:
<?php

namespace Bazaar\Component\Cart\Tests\Domain\Model;

use Bazaar\Component\Cart\Domain\Model\CartProvider;

/**
 * CartProvider test
 *
 * @author Beau Simensen <beau@dflydev.com>
 */
class CartProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test getCart() method with valid existing cart identifier.
     */
    public function testGetValidExistingIdentifier()
    {
        $cartStorage = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartStorageInterface');
        $cartFactory = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartFactoryInterface');
        $cartRepository = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartRepositoryInterface');

        $cart = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartInterface');

        $cartStorage
            ->expects($this->once())
            ->method('getCurrentCartIdentifier')
            ->will($this->returnValue('asdf1234'));

        $cartRepository
            ->expects($this->once())
            ->method('find')
            ->with('asdf1234');

        $cartFactory
            ->expects($this->once())
            ->method('createCart')
            ->will($this->returnValue($cart));

        $cartRepository
            ->expects($this->once())
            ->method('store')
            ->with($cart);

        $cart
            ->expects($this->once())
            ->method('identifier')
            ->will($this->returnValue('asdf1234'));

        $cartStorage
            ->expects($this->once())
            ->method('setCurrentCartIdentifier')
            ->with('asdf1234');

        $cartProvider = new CartProvider($cartStorage, $cartFactory, $cartRepository);

        // This time should come from storage + repository.
        $this->assertEquals($cart, $cartProvider->getCart());

        // This time should come from cache.
        $this->assertEquals($cart, $cartProvider->getCart());
    }

    /**
     * Test getCart() method with invalid existing cart identifier.
     */
    public function testGetInvalidExistingIdentifier()
    {
        $cartStorage = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartStorageInterface');
        $cartFactory = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartFactoryInterface');
        $cartRepository = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartRepositoryInterface');

        $cart = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartInterface');

        $cartStorage
            ->expects($this->once())
            ->method('getCurrentCartIdentifier')
            ->will($this->returnValue('asdf1234'));

        $cartRepository
            ->expects($this->once())
            ->method('find')
            ->with('asdf1234')
            ->will($this->returnValue($cart));

        $cartProvider = new CartProvider($cartStorage, $cartFactory, $cartRepository);

        // This time should come from storage + repository.
        $this->assertEquals($cart, $cartProvider->getCart());

        // This time should come from cache.
        $this->assertEquals($cart, $cartProvider->getCart());
    }

    /**
     * Test setCart() method.
     */
    public function testSetCart()
    {
        $cartStorage = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartStorageInterface');
        $cartFactory = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartFactoryInterface');
        $cartRepository = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartRepositoryInterface');

        $cart = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartInterface');

        $cartStorage
            ->expects($this->once())
            ->method('setCurrentCartIdentifier')
            ->with('asdf1234');

        $cartStorage
            ->expects($this->never())
            ->method('getCurrentCartIdentifier');

        $cart
            ->expects($this->once())
            ->method('identifier')
            ->will($this->returnValue('asdf1234'));

        $cartProvider = new CartProvider($cartStorage, $cartFactory, $cartRepository);

        $cartProvider->setCart($cart);

        $this->assertEquals($cart, $cartProvider->getCart());
    }

    /**
     * Test abandonCart() method.
     */
    public function testAbandonCart()
    {
        $cartStorage = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartStorageInterface');
        $cartFactory = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartFactoryInterface');
        $cartRepository = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartRepositoryInterface');

        $cart = $this->getMock('Bazaar\Component\Cart\Domain\Model\CartInterface');

        $cartStorage
            ->expects($this->once())
            ->method('abandonCurrentCart');

        $cartStorage
            ->expects($this->once())
            ->method('getCurrentCartIdentifier')
            ->will($this->throwException(new \Exception('Called because abandon cart worked (cart is null)')));

        $cartProvider = new CartProvider($cartStorage, $cartFactory, $cartRepository);

        $cartProvider->setCart($cart);

        $cartProvider->abandonCart();

        try {
            $cartProvider->getCart();

            $this->fail('The call to getCart did not throw the test exception');
        } catch (\Exception $e) {
            $this->assertEquals('Called because abandon cart worked (cart is null)', $e->getMessage());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package printers

import (
	"bytes"
	"io/ioutil"
	"reflect"
	"strings"
	"testing"
	"time"

	kapi "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/kubernetes/pkg/kubectl/scheme"
	kprinters "k8s.io/kubernetes/pkg/printers"

	appsapi "github.com/openshift/api/apps/v1"
	authorizationapi "github.com/openshift/api/authorization/v1"
	buildapi "github.com/openshift/api/build/v1"
	imageapi "github.com/openshift/api/image/v1"
	oauthapi "github.com/openshift/api/oauth/v1"
	projectapi "github.com/openshift/api/project/v1"
	securityapi "github.com/openshift/api/security/v1"
	templateapi "github.com/openshift/api/template/v1"
)

// PrinterCoverageExceptions is the list of API types that do NOT have corresponding printers
// If you add something to this list, explain why it doesn't need printing.  waaaa is not a valid
// reason.
var PrinterCoverageExceptions = []reflect.Type{
	// reflect.TypeOf(&imageapi.DockerImage{}),         // not a top level resource
	reflect.TypeOf(&imageapi.ImageStreamImport{}),   // normal users don't ever look at these
	reflect.TypeOf(&buildapi.BuildLog{}),            // just a marker type
	reflect.TypeOf(&buildapi.BuildLogOptions{}),     // just a marker type
	reflect.TypeOf(&appsapi.DeploymentRequest{}),    // normal users don't ever look at these
	reflect.TypeOf(&appsapi.DeploymentLog{}),        // just a marker type
	reflect.TypeOf(&appsapi.DeploymentLogOptions{}), // just a marker type

	// these resources can't be "GET"ed, so we probably don't need a printer for them
	reflect.TypeOf(&authorizationapi.SubjectAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReviewResponse{}),
	reflect.TypeOf(&authorizationapi.SubjectAccessReview{}),
	reflect.TypeOf(&imageapi.ImageSignature{}),
	reflect.TypeOf(&authorizationapi.ResourceAccessReview{}),
	reflect.TypeOf(&authorizationapi.LocalSubjectAccessReview{}),
	reflect.TypeOf(&authorizationapi.LocalResourceAccessReview{}),
	reflect.TypeOf(&authorizationapi.SelfSubjectRulesReview{}),
	reflect.TypeOf(&authorizationapi.SubjectRulesReview{}),
	reflect.TypeOf(&buildapi.BuildLog{}),
	reflect.TypeOf(&buildapi.BinaryBuildRequestOptions{}),
	reflect.TypeOf(&buildapi.BuildRequest{}),
	reflect.TypeOf(&buildapi.BuildLogOptions{}),
	reflect.TypeOf(&securityapi.PodSecurityPolicySubjectReview{}),
	reflect.TypeOf(&securityapi.PodSecurityPolicySelfSubjectReview{}),
	reflect.TypeOf(&securityapi.PodSecurityPolicyReview{}),
	reflect.TypeOf(&oauthapi.OAuthRedirectReference{}),
}

// MissingPrinterCoverageExceptions is the list of types that were missing printer methods when I started
// You should never add to this list
// TODO printers should be added for these types
var MissingPrinterCoverageExceptions = []reflect.Type{
	reflect.TypeOf(&appsapi.DeploymentConfigRollback{}),
	reflect.TypeOf(&imageapi.ImageStreamMapping{}),
	reflect.TypeOf(&imageapi.ImageStreamLayers{}),
	reflect.TypeOf(&projectapi.ProjectRequest{}),
}

func TestPrinterCoverage(t *testing.T) {
	printer := kprinters.NewHumanReadablePrinter(nil, kprinters.PrintOptions{})
	AddHandlers(printer)

main:
	for gvk, apiType := range scheme.Scheme.AllKnownTypes() {
		if gvk.Version != runtime.APIVersionInternal {
			continue
		}

		if !strings.Contains(apiType.PkgPath(), "github.com/openshift/origin") || strings.Contains(apiType.PkgPath(), "github.com/openshift/origin/vendor/") {
			continue
		}

		ptrType := reflect.PtrTo(apiType)
		for _, exception := range PrinterCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}
		for _, exception := range MissingPrinterCoverageExceptions {
			if ptrType == exception {
				continue main
			}
		}

		newStructValue := reflect.New(apiType)
		newStruct := newStructValue.Interface()

		if err := printer.PrintObj(newStruct.(runtime.Object), ioutil.Discard); (err != nil) && strings.Contains(err.Error(), "error: unknown type ") {
			t.Errorf("missing printer for %v.  Check pkg/cmd/cli/describe/printer.go", apiType)
		}
	}
}

func TestFormatResourceName(t *testing.T) {
	tests := []struct {
		kind schema.GroupKind
		name string
		want string
	}{
		{schema.GroupKind{}, "", ""},
		{schema.GroupKind{}, "name", "name"},
		{schema.GroupKind{Kind: "Kind"}, "", "kind/"}, // should not happen in practice
		{schema.GroupKind{Kind: "Kind"}, "name", "kind/name"},
	}
	for _, tt := range tests {
		if got := formatResourceName(tt.kind, tt.name, true); got != tt.want {
			t.Errorf("formatResourceName(%q, %q) = %q, want %q", tt.kind, tt.name, got, tt.want)
		}
	}
}

func mockRoleBindingRestriction() []*authorizationapi.RoleBindingRestriction {
	return []*authorizationapi.RoleBindingRestriction{
		{
			ObjectMeta: metav1.ObjectMeta{Name: "match-serviceaccount"},
			Spec: authorizationapi.RoleBindingRestrictionSpec{
				ServiceAccountRestriction: &authorizationapi.ServiceAccountRestriction{
					Namespaces: []string{""},
				},
			},
		},
	}
}

func TestPrintRoleBindingRestriction(t *testing.T) {
	buf := bytes.NewBuffer([]byte{})
	rbrs := mockRoleBindingRestriction()

	tests := []struct {
		name        string
		rbr         *authorizationapi.RoleBindingRestriction
		expectedOut string
		expectedErr error
	}{
		{
			name:        "output check",
			rbr:         rbrs[0],
			expectedOut: "match-serviceaccount\tServiceAccount\t/*\n",
		},
	}

	for _, test := range tests {
		if err := printRoleBindingRestriction(test.rbr, buf, kprinters.PrintOptions{}); err != test.expectedErr {
			t.Errorf("error mismatch: expected %v, got %v", test.expectedErr, err)
			continue
		}
		got := buf.String()
		buf.Reset()

		if !strings.Contains(got, test.expectedOut) {
			t.Errorf("unexpected output:\n%s\nexpected to contain: %s", got, test.expectedOut)
			continue
		}
	}
}

func TestPrintImageStream(t *testing.T) {
	buf := bytes.NewBuffer([]byte{})
	streams := mockStreams()

	tests := []struct {
		name        string
		stream      *imageapi.ImageStream
		expectedOut string
		expectedErr error
	}{
		{
			name:        "less than three tags",
			stream:      streams[0],
			expectedOut: "latest,other",
		},
		{
			name:        "three tags",
			stream:      streams[1],
			expectedOut: "third,latest,other",
		},
		{
			name:        "more than three tags",
			stream:      streams[2],
			expectedOut: "another,third,latest,other",
		},
	}

	for _, test := range tests {
		if err := printImageStream(test.stream, buf, kprinters.PrintOptions{}); err != test.expectedErr {
			t.Errorf("error mismatch: expected %v, got %v", test.expectedErr, err)
			continue
		}
		got := buf.String()
		buf.Reset()

		if !strings.Contains(got, test.expectedOut) {
			t.Errorf("unexpected output:\n%s\nexpected to contain: %s", got, test.expectedOut)
			continue
		}
	}

}

func mockStreams() []*imageapi.ImageStream {
	return []*imageapi.ImageStream{
		{
			ObjectMeta: metav1.ObjectMeta{Name: "less-than-three-tags"},
			Status: imageapi.ImageStreamStatus{
				Tags: []imageapi.NamedTagEventList{
					{
						Tag: "other",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "other-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 52, 0, 0, time.UTC),
								Image:                "other-image",
							},
						},
					},
					{
						Tag: "latest",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "latest-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 53, 0, 0, time.UTC),
								Image:                "latest-image",
							},
						},
					},
				},
			},
		},
		{
			ObjectMeta: metav1.ObjectMeta{Name: "three-tags"},
			Status: imageapi.ImageStreamStatus{
				Tags: []imageapi.NamedTagEventList{
					{
						Tag: "other",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "other-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 52, 0, 0, time.UTC),
								Image:                "other-image",
							},
						},
					},
					{
						Tag: "latest",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "latest-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 53, 0, 0, time.UTC),
								Image:                "latest-image",
							},
						},
					},
					{
						Tag: "third",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "third-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 54, 0, 0, time.UTC),
								Image:                "third-image",
							},
						},
					},
				},
			},
		},
		{
			ObjectMeta: metav1.ObjectMeta{Name: "more-than-three-tags"},
			Status: imageapi.ImageStreamStatus{
				Tags: []imageapi.NamedTagEventList{
					{
						Tag: "other",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "other-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 52, 0, 0, time.UTC),
								Image:                "other-image",
							},
						},
					},
					{
						Tag: "latest",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "latest-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 53, 0, 0, time.UTC),
								Image:                "latest-image",
							},
						},
					},
					{
						Tag: "third",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "third-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 54, 0, 0, time.UTC),
								Image:                "third-image",
							},
						},
					},
					{
						Tag: "another",
						Items: []imageapi.TagEvent{
							{
								DockerImageReference: "another-ref",
								Created:              metav1.Date(2015, 9, 4, 13, 54, 0, 0, time.UTC),
								Image:                "another-image",
							},
						},
					},
				},
			},
		},
	}
}

func TestPrintTemplate(t *testing.T) {
	tests := []struct {
		template templateapi.Template
		want     string
	}{
		{
			templateapi.Template{
				ObjectMeta: metav1.ObjectMeta{
					Name: "name",
					Annotations: map[string]string{
						"description": "description",
					},
				},
				Parameters: []templateapi.Parameter{{}},
				Objects:    []runtime.RawExtension{{Object: &kapi.Pod{}}},
			},
			"name\tdescription\t1 (1 blank)\t1\n",
		},
		{
			templateapi.Template{
				ObjectMeta: metav1.ObjectMeta{
					Name: "long",
					Annotations: map[string]string{
						"description": "the long description of this template is way way way way way way way way way way way way way too long",
					},
				},
				Parameters: []templateapi.Parameter{},
				Objects:    []runtime.RawExtension{},
			},
			"long\tthe long description of this template is way way way way way way way way way...\t0 (all set)\t0\n",
		},
		{
			templateapi.Template{
				ObjectMeta: metav1.ObjectMeta{
					Name: "multiline",
					Annotations: map[string]string{
						"description": "Once upon a time\nthere was a template\nwith multiple\nlines\n",
					},
				},
				Parameters: []templateapi.Parameter{},
				Objects:    []runtime.RawExtension{},
			},
			"multiline\tOnce upon a time...\t0 (all set)\t0\n",
		},
		{
			templateapi.Template{
				ObjectMeta: metav1.ObjectMeta{
					Name: "trailingnewline",
					Annotations: map[string]string{
						"description": "Next line please\n",
					},
				},
				Parameters: []templateapi.Parameter{},
				Objects:    []runtime.RawExtension{},
			},
			"trailingnewline\tNext line please...\t0 (all set)\t0\n",
		},
		{
			templateapi.Template{
				ObjectMeta: metav1.ObjectMeta{
					Name: "longmultiline",
					Annotations: map[string]string{
						"description": "12345678901234567890123456789012345678901234567890123456789012345678901234567890123\n0",
					},
				},
				Parameters: []templateapi.Parameter{},
				Objects:    []runtime.RawExtension{},
			},
			"longmultiline\t12345678901234567890123456789012345678901234567890123456789012345678901234567...\t0 (all set)\t0\n",
		},
	}

	for i, test := range tests {
		buf := bytes.NewBuffer([]byte{})
		err := printTemplate(&test.template, buf, kprinters.PrintOptions{})
		if err != nil {
			t.Errorf("[%d] unexpected error: %v", i, err)
			continue
		}
		got := buf.String()
		if got != test.want {
			t.Errorf("[%d] expected %q, got %q", i, test.want, got)
			continue
		}
	}
}

func Test_printTagsUpToWidth(t *testing.T) {
	type args struct {
		statusTags     []imageapi.NamedTagEventList
		preferredWidth int
	}
	tests := []struct {
		name string
		args args
		want string
	}{
		{name: "empty"},
		{name: "1", want: "very-long-name", args: args{statusTags: []imageapi.NamedTagEventList{{Tag: "very-long-name", Items: []imageapi.TagEvent{}}}}},
		{name: "2", want: "1234567890", args: args{preferredWidth: 10, statusTags: []imageapi.NamedTagEventList{{Tag: "1234567890", Items: []imageapi.TagEvent{}}}}},
		{name: "3", want: "123456789012", args: args{preferredWidth: 10, statusTags: []imageapi.NamedTagEventList{{Tag: "123456789012", Items: []imageapi.TagEvent{}}}}},
		{name: "4", want: "1234567890 + 1 more...", args: args{preferredWidth: 10, statusTags: []imageapi.NamedTagEventList{{Tag: "2", Items: []imageapi.TagEvent{}}, {Tag: "1234567890", Items: []imageapi.TagEvent{}}}}},
		{name: "if more than 75% full, don't add a tag", want: "1234567890 + 1 more...", args: args{preferredWidth: 12, statusTags: []imageapi.NamedTagEventList{{Tag: "2", Items: []imageapi.TagEvent{}}, {Tag: "1234567890", Items: []imageapi.TagEvent{}}}}},
		{name: "if less than 75% full, add a tag that fits", want: "123456789,2", args: args{preferredWidth: 12, statusTags: []imageapi.NamedTagEventList{{Tag: "2", Items: []imageapi.TagEvent{}}, {Tag: "123456789", Items: []imageapi.TagEvent{}}}}},
		{name: "if less than 75% full, include a large tag", want: "2,3,4234567890", args: args{preferredWidth: 12, statusTags: []imageapi.NamedTagEventList{{Tag: "2", Items: []imageapi.TagEvent{}}, {Tag: "3", Items: []imageapi.TagEvent{}}, {Tag: "4234567890", Items: []imageapi.TagEvent{}}}}},
		{name: "if less than 75% full, don't include a very large tag", want: "2,3 + 1 more...", args: args{preferredWidth: 12, statusTags: []imageapi.NamedTagEventList{{Tag: "2", Items: []imageapi.TagEvent{}}, {Tag: "3", Items: []imageapi.TagEvent{}}, {Tag: "42345678901", Items: []imageapi.TagEvent{}}}}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := printTagsUpToWidth(tt.args.statusTags, tt.args.preferredWidth); got != tt.want {
				t.Errorf("printTagsUpToWidth() = %v, want %v", got, tt.want)
			}
		})
	}
}


text:
package com.opengamma.engine.marketdata;

import com.opengamma.engine.ComputationTargetResolver;

/**
 * Instance of {@link OverrideOperationCompiler} that fails on all inputs.
 */
public class DummyOverrideOperationCompiler implements OverrideOperationCompiler {

  @Override
  public OverrideOperation compile(final String operation, final ComputationTargetResolver.AtVersionCorrection resolver) {
    throw new IllegalArgumentException("Can't compile " + operation);
  }

}


text:
class RpiUser < ApplicationRecord
end


text:
project_euler
=============

This is the repository contains my attempted answers to the questions on https://projecteuler.net/

This my attempt at the algorithms hosted on Project Euler.
Most answers are not revisited after a suitable solution has been found. The idea is to also
study how I form my answers over time, the difference in algorithm design as you encounter
increasingly harder problems which cannot be accomplished by brute force algorithms.
After each solution is found for a problem, the forums on Project Euler are viewed to study
other answers and try and learn from the community.
On Project Euler the bench-mark is that most algorithms should be completed within a minute.
In each solution file you may find more than one solution, each solution will be run for
each problem.

Installation
-------------

The standard requirements.txt file is contained for python packages needing to be installed.
However due to use of python statistical packages eg. numpy, pandas.
To install these packages use the instructions on the page http://www.scipy.org/install.html .

Timer
------
There is a seperate timer for each function and if one minute of execution time is exceeded,
then the solution function will be aborted.

View a Problem
---------------
From the src directory:

	python main.py question <question_number> -s False

View all Problems
------------------
This will give you an idea of the questions that can be run.
From the src directory:

	python main.py all -s False

Run a Solution
---------------
From the src directory:

	# With the question printed out
	python main.py question <question_number>

	# Without the question printed out
	python main.py question <question_number> -q False

Run all Solutions
------------------
From the src directory:

	# With the questions printed out for each solution
	python main.py all

	# Without the questions printed out for each solution
	python main.py all -q False

Help
-----
From the src directory:

	python main.py -h


text:
require 'net/http'
require 'uri'
require 'yaml'

require 'rakismet/model'
require 'rakismet/filter'
require 'rakismet/controller'

module Rakismet
  def self.version
    @version ||= begin
      version = YAML.load_file(File.join(File.dirname(__FILE__), %w(.. VERSION.yml)))
      [version[:major], version[:minor], version[:patch]].join('.')
    end
  end

  class Base
    cattr_accessor :valid_key, :current_request

    class << self
      def validate_key
        validate_constants
        akismet = URI.parse(verify_url)
        _, valid = Net::HTTP.start(akismet.host) do |http|
          data = "key=#{Rakismet::KEY}&blog=#{Rakismet::URL}"
          http.post(akismet.path, data, Rakismet::HEADERS)
        end
        self.valid_key = (valid == 'valid')
      end

      def valid_key?
        @@valid_key == true
      end

      def akismet_call(function, args={})
        validate_constants
        args.merge!(:blog => Rakismet::URL)
        akismet = URI.parse(call_url(function))
        _, response = Net::HTTP.start(akismet.host) do |http|
          data = args.map { |k,v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&')
          http.post(akismet.path, data, Rakismet::HEADERS)
        end
        response
      end

      protected

        def verify_url
          "http://#{Rakismet::HOST}/1.1/verify-key"
        end

        def call_url(function)
          "http://#{Rakismet::KEY}.#{Rakismet::HOST}/1.1/#{function}"
        end

        def validate_constants
          raise Undefined, "Rakismet::KEY is not defined"  if Rakismet::KEY.blank?
          raise Undefined, "Rakismet::URL is not defined"  if Rakismet::URL.blank?
          raise Undefined, "Rakismet::HOST is not defined" if Rakismet::HOST.blank?
        end
    end
  end

  Undefined = Class.new(NameError)

  HEADERS = {
    'User-Agent' => "Rails/#{Rails::VERSION::STRING} | Rakismet/#{Rakismet.version}",
    'Content-Type' => 'application/x-www-form-urlencoded'
  }
end


text:
<?php

/***********************************************************************************
 *  The MIT License (MIT)
 *
 *  Copyright © 2015 Joschi Kuphal <joschi@kuphal.net> / @jkphl
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
 *  this software and associated documentation files (the "Software"), to deal in
 *  the Software without restriction, including without limitation the rights to
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 *  the Software, and to permit persons to whom the Software is furnished to do so,
 *  subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ***********************************************************************************/

namespace App\Http\Controllers;

use App\Models\Organizer;
use Illuminate\Http\Request;

class OrganizerController extends Controller
{
    /**
     * List all organizers
     *
     * @return \Symfony\Component\HttpFoundation\Response Organizer list
     */
    public function listOrganizers()
    {
        return response()->jsonAPI((new Organizer)->newQuery());
    }

    /**
     * Get a single organizer
     *
     * @param int $id Organizer ID
     *
     * @return \Symfony\Component\HttpFoundation\Response Organizer
     */
    public function getOrganizer($id)
    {
        return response()->jsonAPI(Organizer::find($id));
    }

    /**
     * Create a new organizer
     *
     * @param Request $request Request
     *
     * @return \Symfony\Component\HttpFoundation\Response Organizer
     */
    public function createOrganizer(Request $request)
    {

        $Organizer = Organizer::create($request->all());

        return response()->json($Organizer);

    }

    /**
     * Update an organizer
     *
     * @param Request $request Request
     * @param int $id          Organizer ID
     *
     * @return \Symfony\Component\HttpFoundation\Response Organizer
     */
    public function updateOrganizer(Request $request, $id)
    {
        $Organizer         = Organizer::find($id);
        $Organizer->title  = $request->input('title');
        $Organizer->author = $request->input('author');
        $Organizer->isbn   = $request->input('isbn');

//		$Organizer->save();

        return response()->json($Organizer);
    }

    /**
     * Delete an organizer
     *
     * @param int $id Organizer ID
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @todo Set the deleted property to 1 instead of really deleting the organizer
     */
//	public function deleteOrganizer($id)
//	{
//		$Organizer = Organizer::find($id);
//		$Organizer->delete();
//
//		return response()->json('deleted');
//	}
}


text:
name: Feature Request
about: Describe a new feature for MIT App Inventor
labels: 'feature request, status: new'
---

**Describe the desired feature**

<!--
Describe the feature that you'd like to see implemented for App Inventor. More detail is useful as it allows us to better understand the complexity of the task.
-->

**Give an example of how this feature would be used**

<!--
How would a teacher or student use this feature?
-->

**Why doesn't the current App Inventor system address this use case?**

<!--
Explain why the use case cannot be completed using the features of the current system.
-->

**Why is this feature beneficial to App Inventor's educational mission?**

<!--
Because MIT App Inventor is aimed at educational use, we prioritize development of features with an educational benefit. Help us understand how your feature request relates to our mission.
-->


text:
#ifndef STATIC_DRIVER_H
#define STATIC_DRIVER_H

#include "driver.h"

namespace simlocaliser
{

class StaticDriver : public Driver
{
public:

    StaticDriver( const orca::Frame2d & pose );
    virtual ~StaticDriver() {};

    // returns: 0 = success, non-zero = failure
    virtual int enable() { return 0; };
    virtual int repair() { return 0; };
    virtual int disable() { return 0; };

    virtual int read( orca::Localise2dData& location2d );

private:

    orca::Localise2dData location2d_;
};

} // namespace

#endif


text:
package org.springframework.boot.actuate.autoconfigure;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import org.crsh.plugin.PluginLifeCycle;
import org.junit.Assert;
import org.junit.Test;

import org.springframework.beans.MutablePropertyValues;
import org.springframework.boot.actuate.autoconfigure.ShellProperties.CrshShellProperties;
import org.springframework.boot.actuate.autoconfigure.ShellProperties.JaasAuthenticationProperties;
import org.springframework.boot.actuate.autoconfigure.ShellProperties.KeyAuthenticationProperties;
import org.springframework.boot.actuate.autoconfigure.ShellProperties.SimpleAuthenticationProperties;
import org.springframework.boot.actuate.autoconfigure.ShellProperties.SpringAuthenticationProperties;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link ShellProperties}.
 *
 * @author Christian Dupuis
 */
public class ShellPropertiesTests {

	@Test
	public void testBindingAuth() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.bind(new MutablePropertyValues(
				Collections.singletonMap("shell.auth", "spring")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getAuth()).isEqualTo("spring");
	}

	@Test
	public void testBindingAuthIfEmpty() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.bind(
				new MutablePropertyValues(Collections.singletonMap("shell.auth", "")));
		assertThat(binder.getBindingResult().hasErrors()).isTrue();
		assertThat(props.getAuth()).isEqualTo("simple");
	}

	@Test
	public void testBindingCommandRefreshInterval() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		binder.bind(new MutablePropertyValues(
				Collections.singletonMap("shell.command_refresh_interval", "1")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getCommandRefreshInterval()).isEqualTo(1);
	}

	@Test
	public void testBindingCommandPathPatterns() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		binder.bind(new MutablePropertyValues(Collections
				.singletonMap("shell.command_path_patterns", "pattern1, pattern2")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getCommandPathPatterns().length).isEqualTo(2);
		Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" },
				props.getCommandPathPatterns());
	}

	@Test
	public void testBindingConfigPathPatterns() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		binder.bind(new MutablePropertyValues(Collections
				.singletonMap("shell.config_path_patterns", "pattern1, pattern2")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getConfigPathPatterns().length).isEqualTo(2);
		Assert.assertArrayEquals(new String[] { "pattern1", "pattern2" },
				props.getConfigPathPatterns());
	}

	@Test
	public void testBindingDisabledPlugins() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		binder.bind(new MutablePropertyValues(Collections
				.singletonMap("shell.disabled_plugins", "pattern1, pattern2")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getDisabledPlugins().length).isEqualTo(2);
		assertThat(props.getDisabledPlugins()).containsExactly("pattern1", "pattern2");
	}

	@Test
	public void testBindingDisabledCommands() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		binder.bind(new MutablePropertyValues(Collections
				.singletonMap("shell.disabled_commands", "pattern1, pattern2")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(props.getDisabledCommands()).containsExactly("pattern1", "pattern2");
	}

	@Test
	public void testBindingSsh() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.ssh.enabled", "true");
		map.put("shell.ssh.port", "2222");
		map.put("shell.ssh.key_path", "~/.ssh/test.pem");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = props.asCrshShellConfig();

		assertThat(p.get("crash.ssh.port")).isEqualTo("2222");
		assertThat(p.get("crash.ssh.keypath")).isEqualTo("~/.ssh/test.pem");
	}

	@Test
	public void testBindingSshIgnored() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.ssh.enabled", "false");
		map.put("shell.ssh.port", "2222");
		map.put("shell.ssh.key_path", "~/.ssh/test.pem");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = props.asCrshShellConfig();

		assertThat(p.get("crash.ssh.port")).isNull();
		assertThat(p.get("crash.ssh.keypath")).isNull();
	}

	@Test
	public void testBindingTelnet() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.telnet.enabled", "true");
		map.put("shell.telnet.port", "2222");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = props.asCrshShellConfig();

		assertThat(p.get("crash.telnet.port")).isEqualTo("2222");
	}

	@Test
	public void testBindingTelnetIgnored() {
		ShellProperties props = new ShellProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.telnet.enabled", "false");
		map.put("shell.telnet.port", "2222");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = props.asCrshShellConfig();

		assertThat(p.get("crash.telnet.port")).isNull();
	}

	@Test
	public void testBindingJaas() {
		JaasAuthenticationProperties props = new JaasAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.jaas");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.auth.jaas.domain", "my-test-domain");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = new Properties();
		props.applyToCrshShellConfig(p);

		assertThat(p.get("crash.auth.jaas.domain")).isEqualTo("my-test-domain");
	}

	@Test
	public void testBindingKey() {
		KeyAuthenticationProperties props = new KeyAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.key");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.auth.key.path", "~/.ssh/test.pem");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = new Properties();
		props.applyToCrshShellConfig(p);

		assertThat(p.get("crash.auth.key.path")).isEqualTo("~/.ssh/test.pem");
	}

	@Test
	public void testBindingKeyIgnored() {
		KeyAuthenticationProperties props = new KeyAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.key");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = new Properties();
		props.applyToCrshShellConfig(p);

		assertThat(p.get("crash.auth.key.path")).isNull();
	}

	@Test
	public void testBindingSimple() {
		SimpleAuthenticationProperties props = new SimpleAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.simple");
		binder.setConversionService(new DefaultConversionService());
		Map<String, String> map = new HashMap<String, String>();
		map.put("shell.auth.simple.user.name", "username123");
		map.put("shell.auth.simple.user.password", "password123");
		binder.bind(new MutablePropertyValues(map));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = new Properties();
		props.applyToCrshShellConfig(p);

		assertThat(p.get("crash.auth.simple.username")).isEqualTo("username123");
		assertThat(p.get("crash.auth.simple.password")).isEqualTo("password123");
	}

	@Test
	public void testDefaultPasswordAutogeneratedIfUnresolvedPlaceholder() {
		SimpleAuthenticationProperties security = new SimpleAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(security, "security");
		binder.bind(new MutablePropertyValues(Collections
				.singletonMap("shell.auth.simple.user.password", "${ADMIN_PASSWORD}")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(security.getUser().isDefaultPassword()).isTrue();
	}

	@Test
	public void testDefaultPasswordAutogeneratedIfEmpty() {
		SimpleAuthenticationProperties security = new SimpleAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(security, "security");
		binder.bind(new MutablePropertyValues(
				Collections.singletonMap("shell.auth.simple.user.password", "")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();
		assertThat(security.getUser().isDefaultPassword()).isTrue();
	}

	@Test
	public void testBindingSpring() {
		SpringAuthenticationProperties props = new SpringAuthenticationProperties();
		RelaxedDataBinder binder = new RelaxedDataBinder(props, "shell.auth.spring");
		binder.bind(new MutablePropertyValues(
				Collections.singletonMap("shell.auth.spring.roles", "role1, role2")));
		assertThat(binder.getBindingResult().hasErrors()).isFalse();

		Properties p = new Properties();
		props.applyToCrshShellConfig(p);

		assertThat(p.get("crash.auth.spring.roles")).isEqualTo("role1,role2");
	}

	@Test
	public void testCustomShellProperties() throws Exception {
		MockEnvironment env = new MockEnvironment();
		env.setProperty("shell.auth", "simple");
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.setEnvironment(env);
		context.setServletContext(new MockServletContext());
		context.register(TestShellConfiguration.class);
		context.register(CrshAutoConfiguration.class);
		context.refresh();

		PluginLifeCycle lifeCycle = context.getBean(PluginLifeCycle.class);
		String uuid = lifeCycle.getConfig().getProperty("test.uuid");
		assertThat(uuid).isEqualTo(TestShellConfiguration.uuid);
		context.close();
	}

	@Configuration
	public static class TestShellConfiguration {

		public static String uuid = UUID.randomUUID().toString();

		@Bean
		public CrshShellProperties testProperties() {
			return new CrshShellProperties() {

				@Override
				protected void applyToCrshShellConfig(Properties config) {
					config.put("test.uuid", uuid);
				}
			};
		}
	}
}


text:
import * as m from "mithril";
import {Stream} from "mithril/stream";
import {SecretConfig, SecretConfigs} from "models/secret_configs/secret_configs";
import {PluginInfo} from "models/shared/plugin_infos_new/plugin_info";
import {SecretConfigModal} from "views/pages/secret_configs/modals";

export class TestSecretConfigModal extends SecretConfigModal {

  constructor(entities: Stream<SecretConfigs>,
              entity: SecretConfig,
              pluginInfos: Array<PluginInfo<any>>,
              onSuccessfulSave: (msg: m.Children) => any,
              disableId: boolean = false) {
    super(entities, entity, pluginInfos, onSuccessfulSave, disableId);
    this.isStale(false);
  }

  title(): string {
    return "Modal title for Secret Configuration";
  }

  setErrorMessageForTest(errorMsg: string): void {
    this.errorMessage(errorMsg);
  }

  protected operationPromise(): Promise<any> {
    return Promise.resolve();
  }

  protected successMessage(): m.Children {
    return "Success Messgae";
  }
}


text:
namespace Beanit.MongoIntegrityV2.CollectionStore
{
    public interface ITypedDocument<TIdentifer> : IDocument
    {
        TIdentifer Id { get; set; }
    }
}


text:
package game.controllers.ghosts.game;

import game.core.Game;

public class GameGhostChaseState implements GameGhostAI {
	int X = 0;
	int Y = 1;
	int pinkDist = 16;
	int tileDist = 4;
	int ClydeCornerNode = 1195;
	int ClydeMaintainDistance = 8;
	int InkyPacDistance = 2;

	@Override
	public int[] execute(int ghostType, Game game, long timeDue) {
		int[] target = {0,0};
		if(ghostType == BLINKY){
			target[X] = game.getX(game.getCurPacManLoc());
			target[Y] = game.getY(game.getCurPacManLoc());
		}
		if(ghostType == PINKY){
			target[X] = game.getX(game.getCurPacManLoc());
			target[Y] = game.getY(game.getCurPacManLoc());
			int pacLastDirection = game.getCurPacManDir();
			if (pacLastDirection == Game.UP){
				target[X] -= pinkDist;
				target[Y] -= pinkDist;
			}
			else if(pacLastDirection == Game.LEFT){
				target[X] -= pinkDist;
			}
			else if(pacLastDirection == Game.RIGHT){
				target[X] += pinkDist;
			}
			else if(pacLastDirection == Game.DOWN){
				target[Y] += pinkDist;
			}
		}
		if(ghostType == CLYDE){
			double distanceFromPac = GameGhosts.getEuclideanDistance(game.getX(game.getCurGhostLoc(ghostType)), game.getY(game.getCurGhostLoc(ghostType)),  game.getX(game.getCurPacManLoc()), game.getY(game.getCurPacManLoc()));
			if (distanceFromPac >= ClydeMaintainDistance*tileDist){
				target[X] = game.getX(game.getCurPacManLoc());
				target[Y] = game.getY(game.getCurPacManLoc());
			}
			else{
				target[X] = game.getX(ClydeCornerNode);
				target[Y] = game.getY(ClydeCornerNode);
			}

		}
		if(ghostType == INKY){
			int pacFrontX = game.getX(game.getCurPacManLoc());
			int pacFrontY = game.getY(game.getCurPacManLoc());
			int pacLastDirection = game.getCurPacManDir();
			if (pacLastDirection == Game.UP){
				pacFrontX -= tileDist * InkyPacDistance;
				pacFrontY -= tileDist * InkyPacDistance;
			}
			else if(pacLastDirection == Game.LEFT){
				pacFrontX -= tileDist * InkyPacDistance;
			}
			else if(pacLastDirection == Game.RIGHT){
				pacFrontX += tileDist * InkyPacDistance;
			}
			else if(pacLastDirection == Game.DOWN){
				pacFrontY += tileDist * InkyPacDistance;
			}

			int blinkyLocX = game.getX(game.getCurGhostLoc(BLINKY));
			int blinkyLocY = game.getY(game.getCurGhostLoc(BLINKY));
			int vectorX = pacFrontX - blinkyLocX;
			int vectorY = pacFrontY - blinkyLocY;
			target[X]= blinkyLocX + vectorX*2;
			target[Y]= blinkyLocY + vectorY*2;

		}
		return target;
	}

}


text:
\hypertarget{namespacefoo_8js}{}\section{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/namespacefoo.js File Reference}
\label{namespacefoo_8js}\index{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/namespacefoo.\+js@{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/namespacefoo.\+js}}
\subsection*{Variables}
\begin{DoxyCompactItemize}
\item
var \hyperlink{namespacefoo_8js_a9befe355abf41da3f2a4249505b6acc5}{namespacefoo}
\end{DoxyCompactItemize}

\subsection{Variable Documentation}
\index{namespacefoo.\+js@{namespacefoo.\+js}!namespacefoo@{namespacefoo}}
\index{namespacefoo@{namespacefoo}!namespacefoo.\+js@{namespacefoo.\+js}}
\subsubsection[{\texorpdfstring{namespacefoo}{namespacefoo}}]{\setlength{\rightskip}{0pt plus 5cm}var namespacefoo}\hypertarget{namespacefoo_8js_a9befe355abf41da3f2a4249505b6acc5}{}\label{namespacefoo_8js_a9befe355abf41da3f2a4249505b6acc5}
{\bfseries Initial value\+:}
\begin{DoxyCode}
=
[
    [ \textcolor{stringliteral}{"MixedUpTestCaseTest"}, \textcolor{stringliteral}{"classfoo\_1\_1\_mixed\_up\_test\_case\_test.html"}, null ],
    [ \textcolor{stringliteral}{"MixedUpTestCaseWithSameTestNameTest"}, \textcolor{stringliteral}{"classfoo\_1\_1\_mixed\_up\_test\_case\_with\_same\_test\_name\_test.html
      "}, null ],
    [ \textcolor{stringliteral}{"PointerPrintable"}, \textcolor{stringliteral}{"structfoo\_1\_1\_pointer\_printable.html"}, null ],
    [ \textcolor{stringliteral}{"PrintableViaPrintTo"}, \textcolor{stringliteral}{"structfoo\_1\_1\_printable\_via\_print\_to.html"}, \textcolor{stringliteral}{"
      structfoo\_1\_1\_printable\_via\_print\_to"} ],
    [ \textcolor{stringliteral}{"PrintableViaPrintToTemplate"}, \textcolor{stringliteral}{"classfoo\_1\_1\_printable\_via\_print\_to\_template.html"}, \textcolor{stringliteral}{"
      classfoo\_1\_1\_printable\_via\_print\_to\_template"} ],
    [ \textcolor{stringliteral}{"StreamableTemplateInFoo"}, \textcolor{stringliteral}{"classfoo\_1\_1\_streamable\_template\_in\_foo.html"}, \textcolor{stringliteral}{"
      classfoo\_1\_1\_streamable\_template\_in\_foo"} ],
    [ \textcolor{stringliteral}{"UnprintableInFoo"}, \textcolor{stringliteral}{"classfoo\_1\_1\_unprintable\_in\_foo.html"}, \textcolor{stringliteral}{"classfoo\_1\_1\_unprintable\_in\_foo"} ]
]
\end{DoxyCode}

Definition at line 1 of file namespacefoo.\+js.


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

namespace Quest
{
    class RedPotion : Weapon, IPotion
    {

        private bool used = false;

        public RedPotion(Game game, Point location)
            : base(game, location) { }
        public override string Name { get { return "Blue Potion"; } }

        public override void Attack(Direction direction, Random random)
        {
            game.IncreasePlayerHealth(10, random);
            used = true;
        }

        public bool Used
        {
            get { return used; }
        }
    }
}


text:
import * as collectionHelper from '../../../../src/services/collectionHelper'
import { config, elements } from '../../../../src/config/schemaMapping'

describe('CollectionHelper', () => {
  describe('mergeSchemaMapping', () => {
    it('should return target if target is not an object', () => {
      expect(collectionHelper.mergeSchemaMapping('toto', {toto: 'tata'})).be.eql('toto')
    })

    it('should return target if source is not an object', () => {
      expect(collectionHelper.mergeSchemaMapping({toto: 'tata'}, 'tata')).deep.eql({toto: 'tata'})
    })

    it('should add the default schema from mapping', () => {
      let target = {}
      let source = {
        toto: {type: 'text'}
      }

      expect(collectionHelper.mergeSchemaMapping(target, source)).deep.eql({toto: config['text'].default})
    })

    it('should set the tag json if there is no element for the type', () => {
      let target = {}
      let source = {
        toto: {type: 'toto'}
      }

      expect(collectionHelper.mergeSchemaMapping(target, source)).deep.eql({toto: elements['json']})
    })

    it('should do nothing when the schema is already configured', () => {
      let target = {
        toto: elements['textarea']
      }
      let source = {
        toto: {type: 'text'}
      }

      expect(collectionHelper.mergeSchemaMapping(target, source)).deep.eql({toto: elements['textarea']})
    })

    it('should loop on properties', () => {
      let target = {}
      let source = {
        name: {
          properties: {
            first: {type: 'text'},
            last: {type: 'text'}
          }
        }
      }

      expect(collectionHelper.mergeSchemaMapping(target, source)).deep.eql({
        name: {
          tag: 'fieldset',
          properties: {
            first: config['text'].default,
            last: config['text'].default
          }
        }
      })
    })

    it('should set json when the depth exceed 2', () => {
      let target = {}
      let source = {
        person: {
          tag: 'fieldset',
          properties: {
            identity: {
              tag: 'fieldset',
              properties: {
                name: {
                  properties: {
                    name: {type: 'text'}
                  }
                }
              }
            }
          }
        }
      }

      expect(collectionHelper.mergeSchemaMapping(target, source)).deep.eql({
        person: {
          tag: 'fieldset',
          properties: {
            identity: {
              tag: 'fieldset',
              properties: {
                name: elements['json']
              }
            }
          }
        }
      })
    })
  })

  describe('flattenObjectMapping', () => {
    it('should return empty object if mapping is empty', () => {
      expect(collectionHelper.flattenObjectMapping({})).deep.eql({})
    })

    it('should return attribute with type if there is no depth', () => {
      expect(collectionHelper.flattenObjectMapping({toto: {type: 'text'}})).deep.eql({toto: 'text'})
    })

    it('should loop in properties', () => {
      let mapping = {
        name: {
          properties: {
            first: {type: 'text'},
            last: {type: 'text'}
          }
        }
      }

      expect(collectionHelper.flattenObjectMapping(mapping)).deep.eql({'name.first': 'text', 'name.last': 'text'})
    })

    it('should loop in properties with max depth 2', () => {
      let mapping = {
        person: {
          properties: {
            identity: {
              properties: {
                name: {
                  properties: {
                    first: {type: 'text'},
                    last: {type: 'text'}
                  }
                }
              }
            }
          }
        }
      }

      expect(collectionHelper.flattenObjectMapping(mapping)).deep.eql({'person.identity': 'force-json'})
    })
  })

  describe('flattenObjectSchema', () => {
    it('should return empty object if schema is empty', () => {
      expect(collectionHelper.flattenObjectSchema({})).deep.eql({})
    })

    it('should return schema if there is no depth', () => {
      expect(collectionHelper.flattenObjectSchema({toto: {tag: 'input'}})).deep.eql({toto: {tag: 'input'}})
    })

    it('should loop in properties', () => {
      let mapping = {
        name: {
          properties: {
            first: {tag: 'input'},
            last: {tag: 'input'}
          }
        }
      }

      expect(collectionHelper.flattenObjectSchema(mapping)).deep.eql({'name.first': {tag: 'input'}, 'name.last': {tag: 'input'}})
    })

    it('should loop in properties with max depth 2', () => {
      let mapping = {
        person: {
          properties: {
            identity: {
              properties: {
                name: {
                  properties: {
                    first: {tag: 'input'},
                    last: {tag: 'input'}
                  }
                }
              }
            }
          }
        }
      }

      expect(collectionHelper.flattenObjectSchema(mapping)).deep.eql({'person.identity': {...elements['json']}})
    })
  })

  describe('getSchemaForType', () => {
    it('should return an array with json schema if type does not exist', () => {
      expect(collectionHelper.getSchemaForType('notexist')).deep.eql([{...elements['json']}])
    })

    it('should return the whole list of available elements plus the json element', () => {
      let expected = [
        elements['input:text'],
        elements['textarea'],
        elements['rich-text'],
        elements['select:text'],
        elements['mselect:text'],
        elements['json']
      ]

      expect(collectionHelper.getSchemaForType('text')).deep.eql(expected)
    })
  })

  describe('getDefaultSchemaForType', () => {
    it('should return element json if type does not exist', () => {
      expect(collectionHelper.getDefaultSchemaForType('notexist')).deep.eql({...elements['json']})
    })
    it('should return the default element for the specified type', () => {
      expect(collectionHelper.getDefaultSchemaForType('text')).deep.eql(elements['input:text'])
    })
  })

  describe('castByElementId', () => {
    it('should return same value if element does not exist', () => {
      expect(collectionHelper.castByElementId('toto', '10')).eql('10')
    })
    it('should return same value if element does not have cast', () => {
      expect(collectionHelper.castByElementId('textarea', '10')).eql('10')
    })
    it('should cast to integer the select:integer element', () => {
      expect(collectionHelper.castByElementId('select:integer', '10')).eql(10)
      expect(collectionHelper.castByElementId('select:integer', '10.5')).eql(10)
    })
    it('should cast to float the select:float element', () => {
      expect(collectionHelper.castByElementId('select:float', '10.5')).eql(10.5)
    })
  })

  describe('formatSchema', () => {
    it('should explode to complex json a flat schema', () => {
      let schema = {
        age: elements['integer'],
        'name.first': elements['input:text'],
        'name.last': elements['input:text']
      }

      expect(collectionHelper.formatSchema(schema)).deep.eql({
        age: elements['integer'],
        name: {
          properties: {
            first: elements['input:text'],
            last: elements['input:text']
          }
        }
      })
    })
  })

  describe('mergeMetaAttributes', () => {
    it('should merge meta attributes and mapping', () => {
      let mapping = {mapping: 'mapping'}
      let schema = {schema: 'schema'}
      let allowForm = true

      expect(collectionHelper.mergeMetaAttributes({mapping, schema, allowForm})).deep.eql({
        properties: mapping,
        _meta: {
          schema,
          allowForm
        }
      })
    })
  })

  describe('cleanMapping', () => {
    it('should return a clean mapping with only type', () => {
      let mapping = {
        name: {
          properties: {
            first: {type: 'text'},
            last: {type: 'text'}
          }
        }
      }

      expect(collectionHelper.cleanMapping(mapping)).deep.eql({
        name: {
          first: 'text',
          last: 'text'
        }
      })
    })
  })

  describe('hasSameSchema', () => {
    it('should return true if schema and document have same properties', () => {
      let schema = {
        name: {
          properties: {
            first: {type: 'text'},
            last: {type: 'text'}
          }
        }
      }
      let document = {
        name: {
          first: 'toto',
          last: 'tutu'
        }
      }

      expect(collectionHelper.hasSameSchema(document, schema)).be.eql(true)
    })

    it('should return false if schema and document have not same properties', () => {
      let schema = {
        name: {
          properties: {
            first: {type: 'text'},
            last: {type: 'text'}
          }
        }
      }
      let document = {
        name: {
          first: 'toto',
          last: 'tutu',
          other: 'other'
        }
      }

      expect(collectionHelper.hasSameSchema(document, schema)).be.eql(false)
    })
  })
})


text:
//
//  InfoViewController.m
//  ChooseDay
//
//  Created by Vivian on 16/2/19.
//  Copyright © 2016年 DreamThreeMusketeers. All rights reserved.
//

#import "InfoViewController.h"
#import "GUNMMAFN.h"
#import <MaxLeap/MaxLeap.h>
#import "UIImageView+WebCache.h"
#import "CycleScrollView.h"

#import <AssetsLibrary/AssetsLibrary.h>

// 照片原图路径
#define KOriginalPhotoImagePath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"OriginalPhotoImages"]

@interface InfoViewController ()<CycleScrollViewDelegate>
{

    UIImageView *imgV;

    UILabel *nameLabel;

    UILabel *sexLabel;

    UILabel *addLabel;

    NSMutableArray *_dataArrary;

    CycleScrollView *cycleScroll;
    UIImageView *im;

    ALAssetsLibrary *assetl;
}

@property (nonatomic, strong) NSMutableArray *lists;

@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"个人信息";

    self.view.backgroundColor = kBgColor;

    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor, nil]];

    _dataArrary = [NSMutableArray array];

    //加载个人信息视图
    [self loadInfoView];

    //创建无限轮播图
    [self createCyleScrollView];

    //获取系统相册照片
//    [self getImgs];

}

//加载微博信息数据
-(void)loadWeiBoInformation{

    //url
    NSString *url = @"https://api.weibo.com/2/users/show.json";

    NSDictionary *parameters = @{@"access_token":kAccessToken,@"uid":kUserID};

    [GUNMMAFN getDataWithParameters:parameters withUrl:url withBlock:^(id result) {

        //设置信息显示
        NSString *img = [result objectForKey:@"profile_image_url"];

        [imgV setImageWithURL:[NSURL URLWithString:img]];

        nameLabel.text = [result objectForKey:@"name"];

        NSString *sex = [result objectForKey:@"gender"];

        if ([sex isEqual:@"m"]) {

            sex = @"男";

        }else if ([sex isEqual:@"f"]) {

            sex = @"女";

        }else {

            sex = @"未知";

        }

        sexLabel.text = sex;

        addLabel.text = [result objectForKey:@"location"];

    }];

}

//加载QQ信息数据
-(void)loadQQInformation{

    NSString *url = @"https://graph.qq.com/user/get_user_info";

    NSDictionary *parameters = @{@"access_token":kQQAccessToken,@"oauth_consumer_key":kAppID,@"openid":kQQOpenID};

    [GUNMMAFN getDataWithParameters:parameters withUrl:url withBlock:^(id result) {

        //设置显示信息
        NSString *img = [result objectForKey:@"figureurl_qq_2"];

        [imgV setImageWithURL:[NSURL URLWithString:img]];

        nameLabel.text = [result objectForKey:@"nickname"];

        sexLabel.text = [result objectForKey:@"gender"];

        NSString *country = [result objectForKey:@"country"];

        NSString *province = [result objectForKey:@"province"];

        NSString *city = [result  objectForKey:@"city"];

        if (country != nil) {

            addLabel.text = [NSString stringWithFormat:@"%@%@省%@市",country,province,city];

        }else if (province != nil) {

            addLabel.text = [NSString stringWithFormat:@"%@省%@市",province,city];

        }else {

            addLabel.text = [NSString stringWithFormat:@"%@市",city];

        }

    }];

}

//加载自行注册的信息数据
-(void)loadChooseDayInformation{

    NSLog(@"%@",[MLUser currentUser]);

    nameLabel.text = kUserName;

    sexLabel.text = [MLUser currentUser][@"sex"];

    addLabel.text = [MLUser currentUser][@"address"];

//    NSLog(@"jjjjk%@",addLabel.text);

    //获取MaxLeap中的设置的Photo类
    MLQuery *queryPhoto = [MLQuery queryWithClassName:@"Photo"];

    //查找Name列中的用户名
    [queryPhoto whereKey:@"Name" equalTo:kUserName];

    if (queryPhoto) {

        //查询数据
        [queryPhoto findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {

            //                NSLog(@"obj %@",objects);

            self.lists = [NSMutableArray array];

            //Objects是只读,用一个可变数组接收
            [self.lists addObjectsFromArray:objects];

            //                NSLog(@"count %ld",self.lists.count);

            //判断是否有头像
            if (self.lists.count == 0) {

                imgV.image = [UIImage imageNamed:@"myImage"];

            }else{

                MLObject *list = self.lists[0];

                MLFile *userImgFile = list[@"image"];

                //获取图片数据
                [userImgFile getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) {

                    if (!error) {

                        UIImage *img = [UIImage imageWithData:data];

                        //判断是否存在头像
                        if (img) {

                            imgV.image = img;

                        }else {

                            imgV.image = [UIImage imageNamed:@"myImage"];

                        }

                    }

                }];

            }

        }];

    }

}

//显示信息详情
-(void)loadInfoView{

    UIView *infoView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH-300)];

    [self.view addSubview:infoView];

    imgV = [[UIImageView alloc]initWithFrame:CGRectMake(30, 50, 100, 100)];

    imgV.layer.borderWidth = 1;

    imgV.layer.borderColor = [[UIColor grayColor]CGColor];

    imgV.layer.cornerRadius = 50;

    imgV.clipsToBounds = YES;

    imgV.image = [UIImage imageNamed:@"myImage"];

    [infoView addSubview:imgV];

    nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(imgV.origin.x+imgV.width+10, 50, 200, 30)];

    nameLabel.text = @"未知";

    [infoView addSubview:nameLabel];

    sexLabel = [[UILabel alloc]initWithFrame:CGRectMake(nameLabel.origin.x, nameLabel.origin.y+nameLabel.height+5, nameLabel.width, nameLabel.height)];

    sexLabel.text = @"未知";

    [infoView addSubview:sexLabel];

    UILabel *birthdayLabel = [[UILabel alloc]initWithFrame:CGRectMake(sexLabel.origin.x+sexLabel.width+60, sexLabel.origin.y, kScreenW-sexLabel.origin.x+sexLabel.width, sexLabel.height)];

    birthdayLabel.text = @"1992-01-12";

//    [infoView addSubview:birthdayLabel];

    addLabel = [[UILabel alloc]initWithFrame:CGRectMake(sexLabel.origin.x, sexLabel.origin.y+sexLabel.height+5, nameLabel.width, nameLabel.height)];

    addLabel.text = @"未知";

    [infoView addSubview:addLabel];

}

//创建无限轮播图展示照片
-(void)createCyleScrollView{

    cycleScroll = [[CycleScrollView alloc]initWithFrame:CGRectMake(0, addLabel.bottom + 50, kScreenW, kScreenW*0.8)];

    cycleScroll.imgArray =  @[@"白羊.jpg",@"金牛.jpg",@"双子.jpg",@"巨蟹.jpg",@"狮子.jpg",@"处女.jpg",@"天秤.jpg",@"天蝎.jpg",@"射手.jpg",@"摩羯.jpg",@"水瓶.jpg",@"双鱼.jpg"];

//    cycleScroll.imgArray = _dataArrary;
    cycleScroll.delegate = self;
    cycleScroll.autoScroll = YES;
    cycleScroll.autoTime = 2.5f;

    [self.view addSubview:cycleScroll];

}

//获取系统相册照片
-(void)getImgs{

//    dispatch_async(dispatch_get_main_queue(), ^{

        ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *myerror){

            NSLog(@"相册访问失败 is %@",myerror);

            if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location != NSNotFound) {

                NSLog(@"无法访问相册.请在'设置->定位服务'设置为打开状态");

            }else {

                NSLog(@"相册访问失败");

            }

        };

        ALAssetsGroupEnumerationResultsBlock groupEnumerAtion = ^(ALAsset *result, NSUInteger index, BOOL *stop){

            if (result != NULL) {

                if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {

                    ALAssetRepresentation *rep = [result defaultRepresentation];

                    CGImageRef ref = [rep fullScreenImage];

                    NSString *fileName = [[result defaultRepresentation] filename];

                    UIImage *img = [UIImage imageWithCGImage:ref];

                    im.image = img;

                    [_dataArrary addObject:fileName];

                }

            }

//            cycleScroll.imgArray = (NSArray *)_dataArrary;

        };

    NSLog(@"ghjklfghj%@",_dataArrary);

        ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroup = ^(ALAssetsGroup *group, BOOL *stop) {

            if (group == nil) {

            }else {

                //获取相簿的组
                NSString *g = [NSString stringWithFormat:@"%@",group];

                NSString *g1 = [g substringFromIndex:16];

                NSArray *arr = [NSArray arrayWithArray:[g1 componentsSeparatedByString:@","]];

                NSString *g2 = [[arr objectAtIndex:0] substringFromIndex:5];

                if ([g2 isEqualToString:@"Camera Roll"]) {

                    g2 = @"相机胶卷";

                }

                //组的名字name
                NSString *groupName = g2;

                [group enumerateAssetsUsingBlock:groupEnumerAtion];

            }

        };

        assetl = [[ALAssetsLibrary alloc]init];

        [assetl enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:libraryGroup failureBlock:failureBlock];

//    [self.view addSubview:cycleScroll];

//    });

}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];

    //判断当前的登录账号
    if (kAccessToken) {

        [self loadWeiBoInformation];

    }else if (kQQOpenID) {

        [self loadQQInformation];

    }else {

        [self loadChooseDayInformation];

    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
class MoveState;

typedef const MoveState   _MoveState ;
typedef _MoveState* const _MoveState_;
typedef MoveState* const   MoveState_;

#include "state.h"

class MoveState: public State {
public:
    uint pusher;

     MoveState(_uint   pusher = UINF ,
               _State_ parent = NULL ,
               _uint   g      = 0U  );

     MoveState(_MoveState& copy);
    ~MoveState(void            );

    State* clone(void) const;

    State* get_neighbor(Board_ b, _uint k);

    uint        lower_bound( Board_ b , _State_ other);
    void        set_pusher (_uint   p                );
    StateArray& neighbors  ( Board_ b                );

    void accept(StateVisitor& visitor);

    bool operator==(_State& other) const;

    friend struct MoveStateHash;
};

struct MoveStateHash {
    std::size_t operator()(State_ key) const;
};

typedef StateSet<MoveStateHash>::type MoveStateSet;

#endif


text:
using System;
using System.ComponentModel.Composition;
using System.Data.Services.Design;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using EnvDTE;
using Microsoft.VisualStudio.ConnectedServices;
using NuGet.VisualStudio;
using Microsoft.OData.ConnectedService.Common;

namespace Microsoft.OData.ConnectedService
{
    [ConnectedServiceHandlerExport("ODataConnectedService", AppliesTo = "CSharp")]
    internal class ODataConnectedServiceHandler : ConnectedServiceHandler
    {
        [Import]
        internal IVsPackageInstaller PackageInstaller { get; set; }
        [Import]
        internal IVsPackageInstallerServices PackageInstallerServices { get; set; }

        public override async Task<AddServiceInstanceResult> AddServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            if (codeGenInstance.GenByDataSvcUtil)
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCode(context, project);
            }
            else
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCodeWithoutDataSvcUtil(context, project);
            }

            AddServiceInstanceResult result = new AddServiceInstanceResult(
                context.ServiceInstance.Name,
                new Uri("https://github.com/odata/odata.net"));

            return result;
        }

        public override async Task<UpdateServiceInstanceResult> UpdateServiceInstanceAsync(ConnectedServiceHandlerContext context, CancellationToken ct)
        {
            Project project = ProjectHelper.GetProjectFromHierarchy(context.ProjectHierarchy);
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            if (codeGenInstance.GenByDataSvcUtil)
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCode(context, project);
            }
            else
            {
                await this.AddNuGetPackagesAsync(context, project, new Version(3, 0));
                await this.GenerateClientCodeWithoutDataSvcUtil(context, project);
            }

            UpdateServiceInstanceResult result = new UpdateServiceInstanceResult();
            return result;
        }

        private async Task AddNuGetPackagesAsync(ConnectedServiceHandlerContext context, Project currentProject, Version version)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Adding Nuget Packages");
            Version packageVersion = null;
            if (version.Major.Equals(3))
            {
                var wcfDSInstallLocation = CodeGeneratorUtils.GetWCFDSInstallLocation();

                var packageSource = Path.Combine(wcfDSInstallLocation, @"bin\NuGet");
                if (Directory.Exists(packageSource))
                {
                    var files = Directory.EnumerateFiles(packageSource, "*.nupkg").ToList();
                    foreach (var nugetPackage in Constant.V3NuGetPackages)
                    {
                        if (!files.Any(f => Regex.IsMatch(f, nugetPackage + @"(.\d){2,4}.nupkg")))
                        {
                            packageSource = Constant.NuGetOnlineRepository;
                        }
                    }
                }
                else
                {
                    packageSource = Constant.NuGetOnlineRepository;
                }

                if (!PackageInstallerServices.IsPackageInstalled(currentProject, Constant.V3ClientNuGetPackage))
                {
                    PackageInstaller.InstallPackage(packageSource, currentProject, Constant.V3ClientNuGetPackage, packageVersion, false);
                }
            }
        }

        private async Task GenerateClientCode(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy ...");

            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;

            string command = Path.Combine(CodeGeneratorUtils.GetWCFDSInstallLocation(), @"bin\tools\DataSvcUtil.exe");

            var referenceFolderPath = await CheckAndAddReferenceFolder(context, project);

            string outputFile = Path.Combine(referenceFolderPath, "Reference.cs");

            StringBuilder arguments = new StringBuilder(string.Format("/c \"\"{0}\" /version:3.0 /language:{1} /out:\"{2}\" /uri:{3}", command, "CSharp", outputFile, codeGenInstance.Endpoint));

            if (codeGenInstance.UseDataServiceCollection)
            {
                arguments.Append("/dataServiceCollection");
            }
            arguments.Append("\"");

            ProcessHelper.ExecuteCommand(command, arguments.ToString());
            await context.HandlerHelper.AddFileAsync(outputFile, outputFile);
        }

        private async Task GenerateClientCodeWithoutDataSvcUtil(ConnectedServiceHandlerContext context, Project project)
        {
            await context.Logger.WriteMessageAsync(LoggerMessageCategory.Information, "Generating Client Proxy ...");

            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;
            var address = codeGenInstance.Endpoint;
            if (address.StartsWith("https:") || address.StartsWith("http"))
            {
                if (!address.EndsWith("$metadata"))
                {
                    address = address.TrimEnd('/') + "/$metadata";
                }
            }

            EntityClassGenerator generator = new EntityClassGenerator(LanguageOption.GenerateCSharpCode);
            generator.UseDataServiceCollection = codeGenInstance.UseDataServiceCollection;
            generator.Version = DataServiceCodeVersion.V3;

            var referenceFolderPath = await CheckAndAddReferenceFolder(context, project);

            string outputFile = Path.Combine(referenceFolderPath, "Reference.cs");

            XmlReaderSettings settings = new XmlReaderSettings();
            if (!String.IsNullOrEmpty(address))
            {
                XmlResolver resolver = new XmlUrlResolver();
                {
                    resolver.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                }

                settings.XmlResolver = resolver;
            }

            using (XmlReader reader = XmlReader.Create(address, settings))
            {
                using (StreamWriter writer = File.CreateText(outputFile))
                {
                    var error = generator.GenerateCode(reader, writer, codeGenInstance.NamespacePrefix);
                }
            }
            await context.HandlerHelper.AddFileAsync(outputFile, outputFile);
        }

        private Task<string> CheckAndAddReferenceFolder(ConnectedServiceHandlerContext context, Project project)
        {
            ODataConnectedServiceInstance codeGenInstance = (ODataConnectedServiceInstance)context.ServiceInstance;
            var serviceReferenceFolderName = context.HandlerHelper.GetServiceArtifactsRootFolder();

            ProjectItem serviceReferenceFolder;
            ProjectItem namespaceFolder;
            project.ProjectItems.TryGetFolder(serviceReferenceFolderName, out serviceReferenceFolder);

            if (codeGenInstance.NamespacePrefix != null)
            {
                if (!serviceReferenceFolder.ProjectItems.TryGetFolder(codeGenInstance.NamespacePrefix, out namespaceFolder))
                {
                    serviceReferenceFolder.ProjectItems.AddFolder(codeGenInstance.NamespacePrefix);
                }
            }

            var referenceFolderPath = Path.Combine(
                ProjectHelper.GetProjectFullPath(project),
                serviceReferenceFolderName,
                codeGenInstance.NamespacePrefix ?? "");

            return Task.FromResult<string>(referenceFolderPath);
        }
    }
}


text:
const nodeMailer = require('nodemailer');
const pug = require('pug');
const juice = require('juice');
const htmlToText = require('html-to-text');
const promisify = require('es6-promisify');

const transport = nodeMailer.createTransport({
    host: process.env.MAIL_HOST,
    port: process.env.MAIL_PORT,
    auth: {
        user: process.env.MAIL_USER,
        pass: process.env.MAIL_PASS
    }
});

exports.send = async (options) => {
    const mailOptions = {
        from: process.env.MAIL_FROM,
        to: options.email,
        subject: options.subject,
        html: juice(options.emailView),
        text: 'This will also be filled in later'
    };

    const sendMail = promisify(transport.sendMail, transport);
    return await sendMail(mailOptions);
};


text:
package org.bsworks.x2.resource;

/**
 * Filter condition operand type.
 *
 * @author Lev Himmelfarb
 */
public enum FilterConditionOperandType {

	/**
	 * Constant value.
	 */
	CONSTANT,

	/**
	 * Resource property value.
	 */
	VALUE,

	/**
	 * Resource map property element key.
	 */
	KEY,

	/**
	 * Resource reference property referred record id.
	 */
	ID
}


text:
mvn compile
pause