text:
import React, { Component } from 'react'
import Highlight from 'react-syntax-highlight'
import Note from '../Note'

const connect = `export default connect(state => {
  return {
    results: state.search.results
  }
})(Map)
`

const render = `render () {
  return (
    <View style={styles.container}>
      <BackBar navigate={this.goHome} />

      <MapView
        style={styles.container}
        initialRegion={{
          latitude: mockdata.origin.latitude,
          longitude: mockdata.origin.longitude,
          latitudeDelta: mockdata.origin.latitudeDelta,
          longitudeDelta: mockdata.origin.longitudeDelta
        }}
      >

        {this.props.results.map((result, i) => {
          // create markers & pass setSelectedVenue function
          return (
            <Marker coordinate={result.coordinate} key={i} onPress={() => this.setSelectedVenue(result)}>
              {this.state.selectedVenue && this.state.selectedVenue.name === result.name ? <View style={styles.markerSelected} /> : <View style={styles.marker} /> }
            </Marker>
          )
        })}

      </MapView>

      { /* check if there's any markers to display, if so generate list of results */}
      { this.props.results.length > 0 && !this.state.selectedVenue &&
        <View style={styles.container}>
          <ResultsList
            setSelectedVenue={this.setSelectedVenue}
            results={this.props.results} />
        </View>
      }

      { /* check details for a specific venue if it has been selected */ }
      { this.state.selectedVenue &&
        <View style={styles.container}>
          <VenueDetails
            venue={this.state.selectedVenue}
            closeDetails={this.closeDetails} />
        </View>
      }

    </View>
  )
}`

const styles = `const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  marker: {
    backgroundColor: '#550bbc',
    padding: 7,
    borderRadius: 7
  },
  markerSelected: {
    backgroundColor: GREEN,
    padding: 7,
    borderRadius: 7
  },
  text: {
    color: '#FFF',
    fontWeight: 'bold'
  },
  searchContainer: {
    height: 40,
    backgroundColor: '#fff'
  }
})`

const ResultsList = `import React, { Component } from 'react'
import { ListView } from 'react-native'
import ListItem from './ListItem'

class ResultsList extends Component {
  constructor (props) {
    super(props)

    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
    this.state = {
      dataSource: ds.cloneWithRows(this.props.results)
    }
  }

  renderRow (rowData) {
    return (
      <ListItem
        setSelectedVenue={this.props.setSelectedVenue}
        rowData={rowData} />
    )
  }

  render () {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={rowData => this.renderRow(rowData)} />
    )
  }
}

export default ResultsList

`

const VenueDetails = `import React from 'react'
import { View, Text, Image, TouchableOpacity, StyleSheet, Button, ScrollView, Dimensions } from 'react-native'
import venueImage from './../assets/images/venue-image.png'
import * as colors from '../styles/colors'

export default ({ venue, closeDetails }) => (
  <ScrollView style={styles.mainContainer}>
    <Button
      title='Close'
      onPress={closeDetails}
      color={colors.PRIMARY_PURPLE} />

    <View style={styles.headingContainer}>
      <View style={styles.headingRow}>
        <View>
          <Image source={require('./../assets/images/Beer.png')} style={styles.iconImage} />
        </View>

        <View style={styles.headerMain}>
          <Text>{venue.name}</Text>
          <Text style={styles.venueAddress}>{venue.address}</Text>
        </View>

        <TouchableOpacity>
          <View style={styles.directionsBtn}>
            <Text style={styles.directionsText}>Directions</Text>
          </View>
        </TouchableOpacity>
      </View>

      <View>
        <Text style={styles.tagLine}>{venue.description}</Text>
      </View>
    </View>

    <Image source={{uri: venue.image}} style={{ height: 250, width: Dimensions.get('screen').width }} />
  </ScrollView>
)

const styles = StyleSheet.create({
  mainContainer: {
    backgroundColor: colors.WHITE
  },
  headingContainer: {
    paddingTop: 20,
    paddingBottom: 10,
    paddingHorizontal: 25
  },
  headingRow: {
    flexDirection: 'row',
    marginBottom: 10
  },
  headerMain: {
    flex: 1
  },
  iconImage: {
    height: 50,
    width: 40,
    marginRight: 15
  },
  venueAddress: {
    fontSize: 12,
    marginBottom: 5,
    color: '#777'
  },
  directionsBtn: {
    backgroundColor: colors.GREEN,
    paddingVertical: 6,
    paddingHorizontal: 15,
    borderRadius: 15,
    alignSelf: 'center' // otherwise, 100% width
  },
  directionsText: {
    color: colors.WHITE
  },
  tagLine: {
    color: '#666',
    fontSize: 12
  }
})

`

class SearchUiView extends Component {
  render() {

    return (

16. Map Component

Start by connecting the Map component to the search results

            <Highlight lang='javascript' value={connect} />

Now that we have the component connected we can update the render function with the map markers and results by using this.props.results

            <Highlight lang='javascript' value={render} />

Add the supporting styles for the selected marker. make sure to add the import statement import '{' GREEN '}' from './../styles/colors

            <Highlight lang='javascript' value={styles} />

Now we can update the ResultsList and the VenueDetails components to consume the new data

ResultsList

            <Highlight lang='javascript' value={ResultsList} />

Venue Details

            <Highlight lang='javascript' value={VenueDetails} />

That's it! You should now be able to search for bars by name, see the results list, and view venue details. As the app state changes we see the connected areas updated instantly! Congrats on making an awesome app!

    )
  }
}

export default SearchUiView

redpajama_set_name: RedPajamaGithub


text:
@interface JNImgextraModel : NSObject

@property (nonatomic, copy) NSString * imgsrc;

@end


text:
import { AngularioWithCustomDateadapterPage } from './app.po';

describe('angulario-with-custom-dateadapter App', () => {
  let page: AngularioWithCustomDateadapterPage;

  beforeEach(() => {
    page = new AngularioWithCustomDateadapterPage();
  });

  it('should display welcome message', done => {
    page.navigateTo();
    page.getParagraphText()
      .then(msg => expect(msg).toEqual('Welcome to app!!'))
      .then(done, done.fail);
  });
});


text:
package org.mp.em4so.exceptions;

// TODO: Auto-generated Javadoc
/**
 * The Class DocNotSpecifiedException.
 */
public class DocNotSpecifiedException extends Exception {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/**
	 * Instantiates a new doc not specified exception.
	 *
	 * @param msg the msg
	 */
	public DocNotSpecifiedException(String msg){
		super(msg);
	}

	/**
	 * Instantiates a new doc not specified exception.
	 */
	public DocNotSpecifiedException(){
		super();
	}
}


text:
"use strict";
(function ( root, factory ) {
  if ( typeof exports === 'object' ) {
    module.exports = factory ();
  }
  else if ( typeof define === 'function' && define.amd ) {
    define ( [], factory );
  }
  else {
    root.returnExports = factory ();
  }
} ( this, function () {

  L.HtmlIcon = L.Icon.extend({
    options: {
      iconSize: ['auto', 12], // also can be set through CSS
      /*
      iconAnchor: (Point)
      popupAnchor: (Point)
      html: (String)
      bgPos: (Point)
      */
      className: 'leaflet-html-icon',
      html: false
    },

    createIcon: function (oldIcon) {

      var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
          options = this.options;

      if (!options.html) {
        return;
      }

      if (typeof options.html === 'string') {
        div.innerHTML = options.html;
      } else {
        while ( div.hasChildNodes() ) {
          div.removeChild( div.firstChild );
        }
        div.appendChild( options.html );
      }

      if (options.bgPos) {
        div.style.backgroundPosition =
                (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
      }

      this._setIconStyles(div, 'icon');

      return div;
    },

    createShadow: function () {
      return null;
    }
  });

  L.htmlIcon = function (options) {
    return new L.HtmlIcon(options);
  };

} ));

Polymer( 'leaflet-map-extensions', {
} );


text:
package api

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
)

type service struct {
	srcName string
	dstName string

	serviceVersion string
}

var mergeServices = map[string]service{
	"dynamodbstreams": {
		dstName: "dynamodb",
		srcName: "streams.dynamodb",
	},
	"wafregional": {
		dstName:        "waf",
		srcName:        "waf-regional",
		serviceVersion: "2015-08-24",
	},
}

var serviceAliaseNames = map[string]string{
	"costandusagereportservice": "CostandUsageReportService",
	"elasticloadbalancing":      "ELB",
	"elasticloadbalancingv2":    "ELBV2",
	"config":                    "ConfigService",
}

func (a *API) setServiceAliaseName() {
	if newName, ok := serviceAliaseNames[a.PackageName()]; ok {
		a.name = newName
	}
}

// customizationPasses Executes customization logic for the API by package name.
func (a *API) customizationPasses() error {
	var svcCustomizations = map[string]func(*API) error{
		"s3":         s3Customizations,
		"s3control":  s3ControlCustomizations,
		"cloudfront": cloudfrontCustomizations,
		"rds":        rdsCustomizations,
		"neptune":    neptuneCustomizations,
		"docdb":      docdbCustomizations,

		// Disable endpoint resolving for services that require customer
		// to provide endpoint them selves.
		"cloudsearchdomain": disableEndpointResolving,
		"iotdataplane":      disableEndpointResolving,

		// MTurk smoke test is invalid. The service requires AWS account to be
		// linked to Amazon Mechanical Turk Account.
		"mturk": supressSmokeTest,

		// Backfill the authentication type for cognito identity and sts.
		// Removes the need for the customizations in these services.
		"cognitoidentity": backfillAuthType(NoneAuthType,
			"GetId",
			"GetOpenIdToken",
			"UnlinkIdentity",
			"GetCredentialsForIdentity",
		),
		"sts": backfillAuthType(NoneAuthType,
			"AssumeRoleWithSAML",
			"AssumeRoleWithWebIdentity",
		),
		"eventbridge": eventBridgeCustomizations,
	}

	for k := range mergeServices {
		svcCustomizations[k] = mergeServicesCustomizations
	}

	if fn := svcCustomizations[a.PackageName()]; fn != nil {
		err := fn(a)
		if err != nil {
			return fmt.Errorf("service customization pass failure for %s: %v", a.PackageName(), err)
		}
	}

	if err := addHTTPChecksumCustomDocumentation(a); err != nil {
		if err != nil {
			return fmt.Errorf("service httpChecksum trait customization failed, %s: %v",
				a.PackageName(), err)
		}
	}

	return nil
}

func addHTTPChecksumCustomDocumentation(a *API) error {
	for opName, o := range a.Operations {
		if o.HTTPChecksum.RequestAlgorithmMember != "" {
			ref := o.InputRef.Shape.GetModeledMember(o.HTTPChecksum.RequestAlgorithmMember)
			if ref == nil {
				return fmt.Errorf(
					"expect httpChecksum.RequestAlgorithmMember %v to be modeled input member for %v",
					o.HTTPChecksum.RequestAlgorithmMember,
					opName,
				)
			}

			ref.Documentation = AppendDocstring(ref.Documentation, `
				The AWS SDK for Go v1 does not support automatic computing
				request payload checksum. This feature is available in the AWS
				SDK for Go v2. If a value is specified for this parameter, the
				matching algorithm's checksum member must be populated with the
				algorithm's checksum of the request payload.
			`)
			if o.RequestChecksumRequired() {
				ref.Documentation = AppendDocstring(ref.Documentation, `
					The SDK will automatically compute the Content-MD5 checksum
					for this operation. The AWS SDK for Go v2 allows you to
					configure alternative checksum algorithm to be used.
				`)
			}
		}

		if o.HTTPChecksum.RequestValidationModeMember != "" {
			ref := o.InputRef.Shape.GetModeledMember(o.HTTPChecksum.RequestValidationModeMember)
			if ref == nil {
				return fmt.Errorf(
					"expect httpChecksum.RequestValidationModeMember %v to be modeled input member for %v",
					o.HTTPChecksum.RequestValidationModeMember,
					opName,
				)
			}

			ref.Documentation = AppendDocstring(ref.Documentation, `
				The AWS SDK for Go v1 does not support automatic response
				payload checksum validation. This feature is available in the
				AWS SDK for Go v2.
			`)
		}
	}

	return nil
}

func eventBridgeCustomizations(a *API) error {
	// Inject documentation to indicate PutEvents API does not support EndpointId routing to a multi-region endpoint
	// using SigV4a signing.

	const docAddon = "// This AWS SDK does not support calling multi-region endpoints with SigV4a authentication."

	var sb strings.Builder

	op, ok := a.Operations["PutEvents"]
	if !ok {
		return nil
	}

	op.Documentation = appendDocString(&sb, op.Documentation, docAddon)

	const putEventsInputShape = "PutEventsInput"
	input, ok := a.Shapes[putEventsInputShape]
	if !ok {
		return nil
	}

	const endpointIdMember = "EndpointId"
	mref, ok := input.MemberRefs[endpointIdMember]
	if !ok {
		return nil
	}

	mref.Documentation = appendDocString(&sb, mref.Documentation, docAddon)

	return nil
}

func appendDocString(sb *strings.Builder, doc, content string) string {
	if len(content) == 0 {
		return doc
	}
	sb.Reset()
	sb.WriteString(doc)
	if sb.Len() > 0 {
		if doc[len(doc)-1] != '\n' {
			sb.WriteRune('\n')
		}
		sb.WriteString("//\n")
	}
	sb.WriteString(content)
	return sb.String()
}

func supressSmokeTest(a *API) error {
	a.SmokeTests.TestCases = []SmokeTestCase{}
	return nil
}

// Customizes the API generation to replace values specific to S3.
func s3Customizations(a *API) error {

	// back-fill signing name as 's3'
	a.Metadata.SigningName = "s3"

	var strExpires *Shape

	var keepContentMD5Ref = map[string]struct{}{
		"PutObjectInput":  {},
		"UploadPartInput": {},
	}

	for name, s := range a.Shapes {
		// Remove ContentMD5 members unless specified otherwise.
		if _, keep := keepContentMD5Ref[name]; !keep {
			if _, have := s.MemberRefs["ContentMD5"]; have {
				delete(s.MemberRefs, "ContentMD5")
			}
		}

		// Generate getter methods for API operation fields used by customizations.
		for _, refName := range []string{"Bucket", "SSECustomerKey", "CopySourceSSECustomerKey"} {
			if ref, ok := s.MemberRefs[refName]; ok {
				ref.GenerateGetter = true
			}
		}

		// Generate a endpointARN method for the BucketName shape if this is used as an operation input
		if s.UsedAsInput {
			if s.ShapeName == "CreateBucketInput" {
				// For all operations but CreateBucket the BucketName shape
				// needs to be decorated.
				continue
			}
			var endpointARNShape *ShapeRef
			for _, ref := range s.MemberRefs {
				if ref.OrigShapeName != "BucketName" || ref.Shape.Type != "string" {
					continue
				}
				if endpointARNShape != nil {
					return fmt.Errorf("more then one BucketName shape present on shape")
				}
				ref.EndpointARN = true
				endpointARNShape = ref
			}
			if endpointARNShape != nil {
				s.HasEndpointARNMember = true
				a.HasEndpointARN = true
			}
		}

		// Decorate member references that are modeled with the wrong type.
		// Specifically the case where a member was modeled as a string, but is
		// expected to sent across the wire as a base64 value.
		//
		// e.g. S3's SSECustomerKey and CopySourceSSECustomerKey
		for _, refName := range []string{
			"SSECustomerKey",
			"CopySourceSSECustomerKey",
		} {
			if ref, ok := s.MemberRefs[refName]; ok {
				ref.CustomTags = append(ref.CustomTags, ShapeTag{
					"marshal-as", "blob",
				})
			}
		}

		// Expires should be a string not time.Time since the format is not
		// enforced by S3, and any value can be set to this field outside of the SDK.
		if strings.HasSuffix(name, "Output") {
			if ref, ok := s.MemberRefs["Expires"]; ok {
				if strExpires == nil {
					newShape := *ref.Shape
					strExpires = &newShape
					strExpires.Type = "string"
					strExpires.refs = []*ShapeRef{}
				}
				ref.Shape.removeRef(ref)
				ref.Shape = strExpires
				ref.Shape.refs = append(ref.Shape.refs, &s.MemberRef)
			}
		}
	}
	s3CustRemoveHeadObjectModeledErrors(a)

	return nil
}

// S3 HeadObject API call incorrect models NoSuchKey as valid
// error code that can be returned. This operation does not
// return error codes, all error codes are derived from HTTP
// status codes.
//
// aws/aws-sdk-go#1208
func s3CustRemoveHeadObjectModeledErrors(a *API) {
	op, ok := a.Operations["HeadObject"]
	if !ok {
		return
	}
	op.Documentation = AppendDocstring(op.Documentation, `
		See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#RESTErrorResponses
		for more information on returned errors.
	`)
	op.ErrorRefs = []ShapeRef{}
}

// S3 service operations with an AccountId need accessors to be generated for
// them so the fields can be dynamically accessed without reflection.
func s3ControlCustomizations(a *API) error {
	for _, s := range a.Shapes {
		// Generate a endpointARN method for the BucketName shape if this is used as an operation input
		if s.UsedAsInput {
			if s.ShapeName == "CreateBucketInput" || s.ShapeName == "ListRegionalBucketsInput" {
				// For operations CreateBucketInput and ListRegionalBuckets the OutpostID shape
				// needs to be decorated
				var outpostIDMemberShape *ShapeRef
				for memberName, ref := range s.MemberRefs {
					if memberName != "OutpostId" || ref.Shape.Type != "string" {
						continue
					}
					if outpostIDMemberShape != nil {
						return fmt.Errorf("more then one OutpostID shape present on shape")
					}
					ref.OutpostIDMember = true
					outpostIDMemberShape = ref
				}
				if outpostIDMemberShape != nil {
					s.HasOutpostIDMember = true
					a.HasOutpostID = true
				}
				continue
			}

			// List of input shapes that use accesspoint names as arnable fields
			accessPointNameArnables := map[string]struct{}{
				"GetAccessPointInput":          {},
				"DeleteAccessPointInput":       {},
				"PutAccessPointPolicyInput":    {},
				"GetAccessPointPolicyInput":    {},
				"DeleteAccessPointPolicyInput": {},
			}

			var endpointARNShape *ShapeRef
			for _, ref := range s.MemberRefs {
				// Operations that have AccessPointName field that takes in an ARN as input
				if _, ok := accessPointNameArnables[s.ShapeName]; ok {
					if ref.OrigShapeName != "AccessPointName" || ref.Shape.Type != "string" {
						continue
					}
				} else if ref.OrigShapeName != "BucketName" || ref.Shape.Type != "string" {
					// All other operations currently allow BucketName field to take in ARN.
					// Exceptions for these are CreateBucket and ListRegionalBucket which use
					// Outpost id and are handled above separately.
					continue
				}

				if endpointARNShape != nil {
					return fmt.Errorf("more then one member present on shape takes arn as input")
				}
				ref.EndpointARN = true
				endpointARNShape = ref
			}
			if endpointARNShape != nil {
				s.HasEndpointARNMember = true
				a.HasEndpointARN = true

				for _, ref := range s.MemberRefs {
					// check for account id customization
					if ref.OrigShapeName == "AccountId" && ref.Shape.Type == "string" {
						ref.AccountIDMemberWithARN = true
						s.HasAccountIdMemberWithARN = true
						a.HasAccountIdWithARN = true
					}
				}
			}
		}
	}

	return nil
}

// cloudfrontCustomizations customized the API generation to replace values
// specific to CloudFront.
func cloudfrontCustomizations(a *API) error {
	// MaxItems members should always be integers
	for _, s := range a.Shapes {
		if ref, ok := s.MemberRefs["MaxItems"]; ok {
			ref.ShapeName = "Integer"
			ref.Shape = a.Shapes["Integer"]
		}
	}
	return nil
}

// mergeServicesCustomizations references any duplicate shapes from DynamoDB
func mergeServicesCustomizations(a *API) error {
	info := mergeServices[a.PackageName()]

	p := strings.Replace(a.path, info.srcName, info.dstName, -1)

	if info.serviceVersion != "" {
		index := strings.LastIndex(p, string(filepath.Separator))
		files, _ := ioutil.ReadDir(p[:index])
		if len(files) > 1 {
			panic("New version was introduced")
		}
		p = p[:index] + "/" + info.serviceVersion
	}

	file := filepath.Join(p, "api-2.json")

	serviceAPI := API{}
	serviceAPI.Attach(file)
	serviceAPI.Setup()

	for n := range a.Shapes {
		if _, ok := serviceAPI.Shapes[n]; ok {
			a.Shapes[n].resolvePkg = SDKImportRoot + "/service/" + info.dstName
		}
	}

	return nil
}

// rdsCustomizations are customization for the service/rds. This adds
// non-modeled fields used for presigning.
func rdsCustomizations(a *API) error {
	inputs := []string{
		"CopyDBSnapshotInput",
		"CreateDBInstanceReadReplicaInput",
		"CopyDBClusterSnapshotInput",
		"CreateDBClusterInput",
		"StartDBInstanceAutomatedBackupsReplicationInput",
	}
	generatePresignedURL(a, inputs)
	return nil
}

// neptuneCustomizations are customization for the service/neptune. This adds
// non-modeled fields used for presigning.
func neptuneCustomizations(a *API) error {
	inputs := []string{
		"CopyDBClusterSnapshotInput",
		"CreateDBClusterInput",
	}
	generatePresignedURL(a, inputs)
	return nil
}

// neptuneCustomizations are customization for the service/neptune. This adds
// non-modeled fields used for presigning.
func docdbCustomizations(a *API) error {
	inputs := []string{
		"CopyDBClusterSnapshotInput",
		"CreateDBClusterInput",
	}
	generatePresignedURL(a, inputs)
	return nil
}

func generatePresignedURL(a *API, inputShapes []string) {
	for _, input := range inputShapes {
		if ref, ok := a.Shapes[input]; ok {
			ref.MemberRefs["SourceRegion"] = &ShapeRef{
				Documentation: docstring(`
				SourceRegion is the source region where the resource exists.
				This is not sent over the wire and is only used for presigning.
				This value should always have the same region as the source
				ARN.
				`),
				ShapeName: "String",
				Shape:     a.Shapes["String"],
				Ignore:    true,
			}
			ref.MemberRefs["DestinationRegion"] = &ShapeRef{
				Documentation: docstring(`
				DestinationRegion is used for presigning the request to a given region.
				`),
				ShapeName: "String",
				Shape:     a.Shapes["String"],
			}
		}
	}
}

func disableEndpointResolving(a *API) error {
	a.Metadata.NoResolveEndpoint = true
	return nil
}

func backfillAuthType(typ AuthType, opNames ...string) func(*API) error {
	return func(a *API) error {
		for _, opName := range opNames {
			op, ok := a.Operations[opName]
			if !ok {
				panic("unable to backfill auth-type for unknown operation " + opName)
			}
			if v := op.AuthType; len(v) != 0 {
				fmt.Fprintf(os.Stderr, "unable to backfill auth-type for %s, already set, %s\n", opName, v)
				continue
			}

			op.AuthType = typ
		}

		return nil
	}
}

// Must be invoked with the original shape name
func removeUnsupportedJSONValue(a *API) error {
	for shapeName, shape := range a.Shapes {
		switch shape.Type {
		case "structure":
			for refName, ref := range shape.MemberRefs {
				if !ref.JSONValue {
					continue
				}
				if err := removeUnsupportedShapeRefJSONValue(a, shapeName, refName, ref); err != nil {
					return fmt.Errorf("failed remove unsupported JSONValue from %v.%v, %v",
						shapeName, refName, err)
				}
			}
		case "list":
			if !shape.MemberRef.JSONValue {
				continue
			}
			if err := removeUnsupportedShapeRefJSONValue(a, shapeName, "", &shape.MemberRef); err != nil {
				return fmt.Errorf("failed remove unsupported JSONValue from %v, %v",
					shapeName, err)
			}
		case "map":
			if !shape.ValueRef.JSONValue {
				continue
			}
			if err := removeUnsupportedShapeRefJSONValue(a, shapeName, "", &shape.ValueRef); err != nil {
				return fmt.Errorf("failed remove unsupported JSONValue from %v, %v",
					shapeName, err)
			}
		}
	}

	return nil
}

func removeUnsupportedShapeRefJSONValue(a *API, parentName, refName string, ref *ShapeRef) (err error) {
	var found bool

	defer func() {
		if !found && err == nil {
			log.Println("removing JSONValue", a.PackageName(), parentName, refName)
			ref.JSONValue = false
			ref.SuppressedJSONValue = true
		}
	}()

	legacyShapes, ok := legacyJSONValueShapes[a.PackageName()]
	if !ok {
		return nil
	}

	legacyShape, ok := legacyShapes[parentName]
	if !ok {
		return nil
	}

	switch legacyShape.Type {
	case "structure":
		_, ok = legacyShape.StructMembers[refName]
		found = ok
	case "list":
		found = legacyShape.ListMemberRef
	case "map":
		found = legacyShape.MapValueRef
	}

	return nil
}


text:
This simple gem takes a structure of arrays and hashes and produces a display in your terminal that makes it easy to parse with your eyes.

## Installation

Install it by running the following command from your terminal:

    $ gem install rainbow_hash

If you use Rbenv to manage your Ruby versions, you may have to run:

    $ rbenv rehash

## Usage

From your terminal, run the `rainbow` command followed by your data structure surrounded by quotation marks.

For example, if you wanted to view the following array in your terminal:

    ['TEST', {a: 1, b: [2, 3, 4, {cow: 'moo'}]}]

you would run:

    $ rainbow "['TEST', {a: 1, b: [2, 3, 4, {cow: 'moo'}]}]"

And watch the results!

## Contributing

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


text:
<resources>
    <string name="app_name">Things</string>

    <!-- MAIN ACTIVITY -->
    <string name="main_activity_title">Things</string>
    <string name="delete_all_things">Delete All</string>

    <!-- ADD THING -->
    <string name="add_thing_activity_title">Add a Thing</string>
    <string name="add_thing_type_label">Thing Type:</string>
    <string name="add_thing_label">Thing:</string>
    <string name="add_thing_create_label">Create Thing</string>

    <!-- THING DETAIL -->
    <string name="thing_detail_activity_title">Thing Detail</string>
    <string name="thing_detail_serial">Serial Number:</string>
    <string name="thing_detail_description">Description: %s</string>
    <string name="thing_detail_select_state">Select a State:</string>
    <string name="thing_detail_send_button">Send Events</string>

    <array
        name="state_array">
        <item>Normal</item>
        <item>Diagnostic</item>
        <item>Warning</item>
        <item>Fault</item>
    </array>

    <!-- ERRORS -->
    <string name="api_error">I\'m sorry, there was a problem.</string>

</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2013-2015 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<resource oid="9792acb2-0b75-11e5-b66e-001e8c717e5b"
		xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
        xmlns:mr="http://prism.evolveum.com/xml/ns/public/matching-rule-3"
        xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9999dddddddd">

	<name>Dummy UUID Resource</name>
	<connectorRef type="c:ConnectorType">
		<filter>
			<q:and>
				<q:equal>
					<q:path>connectorType</q:path>
					<q:value>com.evolveum.icf.dummy.connector.DummyConnector</q:value>
				</q:equal>
				<q:equal>
					<q:path>connectorVersion</q:path>
					<q:value>2.0</q:value>
				</q:equal>
			</q:and>
		</filter>
	</connectorRef>
	<connectorConfiguration xmlns:icfi="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"
	               xmlns:icfc="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3">

		<icfc:configurationProperties>
			<icfi:instanceId>uuid</icfi:instanceId> <!-- Default instance -->
			<icfi:uidMode>uuid</icfi:uidMode>
			<icfi:uselessString>Shiver me timbers!</icfi:uselessString>
			<icfi:uselessGuardedString>       <!-- Add some whitespace -->
				<clearValue>Dead men tell no tales</clearValue>
			</icfi:uselessGuardedString>
			<icfi:supportValidity>true</icfi:supportValidity>
		</icfc:configurationProperties>

	</connectorConfiguration>
	<namespace>http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9999dddddddd</namespace>
	<!-- No schema. It should be generated by provisioning on the first use of this resource. -->
	<schemaHandling>
		<objectType>
			<kind>account</kind>
			<intent>default</intent>
			<displayName>Default Account</displayName>
			<default>true</default>
			<objectClass>ri:AccountObjectClass</objectClass>
			<attribute>
				<ref>icfs:uid</ref>
			</attribute>
			<attribute>
				<ref>icfs:name</ref>
				<displayName>Username</displayName>
				<inbound>
					<strength>weak</strength>
					<target>
						<path>name</path>
					</target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:fullname</ref>
				<displayName>Full Name</displayName>
				<inbound>
					<strength>strong</strength>
					<target>
						<path>fullName</path>
					</target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:weapon</ref>
			</attribute>
			<attribute>
				<ref>ri:ship</ref>
			</attribute>
			<association>
            	<ref>ri:group</ref>
            	<kind>entitlement</kind>
            	<intent>group</intent>
            	<direction>objectToSubject</direction>
            	<associationAttribute>ri:members</associationAttribute>
            	<valueAttribute>icfs:name</valueAttribute>
            </association>
            <association>
            	<ref>ri:priv</ref>
            	<kind>entitlement</kind>
            	<intent>privilege</intent>
            	<direction>subjectToObject</direction>
            	<associationAttribute>ri:privileges</associationAttribute>
            	<valueAttribute>icfs:name</valueAttribute>
            </association>
            <activation>
            	<administrativeStatus>
            		<inbound>
            			<strength>strong</strength>
            		</inbound>
            	</administrativeStatus>
            </activation>
		</objectType>
		<objectType>
			<kind>entitlement</kind>
        	<intent>group</intent>
        	<default>true</default>
        	<objectClass>ri:GroupObjectClass</objectClass>
        </objectType>
        <objectType>
        	<kind>entitlement</kind>
        	<intent>privilege</intent>
        	<default>false</default>
        	<objectClass>ri:CustomprivilegeObjectClass</objectClass>
        </objectType>
	</schemaHandling>
	<consistency>
		<avoidDuplicateValues>true</avoidDuplicateValues>
	</consistency>
	<synchronization>
		<objectSynchronization>
			<enabled>true</enabled>
			<correlation>
				<q:equal>
					<q:path>c:name</q:path>
					<expression>
						<path>$account/attributes/ship</path>
					</expression>
				</q:equal>
			</correlation>
			<reaction>
	            <situation>linked</situation>
	            <synchronize>true</synchronize>
	        </reaction>
	        <reaction>
	            <situation>deleted</situation>
	            <synchronize>true</synchronize>
	            <action>
	            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#deleteFocus</handlerUri>
	            </action>
	        </reaction>
	        <reaction>
	            <situation>unlinked</situation>
	            <synchronize>true</synchronize>
	            <action>
	            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#link</handlerUri>
	            </action>
	        </reaction>
	        <reaction>
	            <situation>unmatched</situation>
	            <synchronize>true</synchronize>
	            <action>
	            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus</handlerUri>
	            </action>
	        </reaction>
        </objectSynchronization>
	</synchronization>
</resource>


text:
package sync

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"sync"
)

// Node represents an object linked in Database. This object
// should not be created by hand, use NewNode when creating
// a new instance of Node.
type Node struct {
	mtx      sync.RWMutex
	Key      string
	Value    interface{}
	Children map[string]*Node

	Parent    *Node
	sliceKids bool
}

// NewNode converts the given data into a node.
func NewNode(key string, data interface{}) *Node {
	n := &Node{
		Key: key,
	}

	n.mtx.Lock()
	n.Children = map[string]*Node{}
	n.mtx.Unlock()

	if data == nil {
		return n
	}

	switch val := reflect.ValueOf(data); val.Kind() {
	case reflect.Map:
		for _, k := range val.MapKeys() {
			v := val.MapIndex(k)
			key := fmt.Sprintf("%s", k.Interface())

			child := NewNode(key, v.Interface())
			child.Parent = n
			n.Children[key] = child
		}

	case reflect.Array, reflect.Slice:
		n.sliceKids = true

		for i := 0; i < val.Len(); i++ {
			v := val.Index(i)
			key := strconv.FormatInt(int64(i), 10)

			child := NewNode(key, v.Interface())
			child.Parent = n
			n.Children[key] = child
		}

	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		fallthrough
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		fallthrough
	case reflect.Float32, reflect.Float64:
		fallthrough
	case reflect.String, reflect.Bool, reflect.Interface:
		n.Value = val.Interface()
	default:
		fmt.Printf("Unsupported type %s(%#v)If you see this log please report an issue on https://github.com/zabawaba99/firego", data, data)
	}

	return n
}

// MarshalJSON turns the node object into JSON bytes.
func (n *Node) MarshalJSON() ([]byte, error) {
	return json.Marshal(n.Objectify())
}

// Objectify turns the node and all its children into a go type.
// If a node was created from a slice initially, a slice will be return.
// If a node has child nodes, a map will be returned.
// Otherwise, a primitive type will be returned.
func (n *Node) Objectify() interface{} {
	n.mtx.RLock()
	defer n.mtx.RUnlock()

	if n.isNil() {
		return nil
	}

	if n.Value != nil {
		return n.Value
	}

	if n.sliceKids {
		obj := make([]interface{}, len(n.Children))
		for k, v := range n.Children {
			index, err := strconv.Atoi(k)
			if err != nil {
				continue
			}
			obj[index] = v.Objectify()
		}
		return obj
	}

	obj := map[string]interface{}{}
	for k, v := range n.Children {
		obj[k] = v.Objectify()
	}

	return obj
}

// Child gets a DataSnapshot for the location at the specified relative path.
// The relative path can either be a simple child key (e.g. 'fred') or a deeper
// slash-separated path (e.g. 'fred/name/first').
func (n *Node) Child(name string) (*Node, bool) {
	n.mtx.RLock()
	defer n.mtx.RUnlock()

	name = strings.Trim(name, "/")
	rabbitHole := strings.Split(name, "/")

	current := n
	for i := 0; i < len(rabbitHole); i++ {
		next, ok := current.Children[rabbitHole[i]]
		if !ok {
			// item does not exist, no need to do anything
			return nil, false
		}

		current = next
	}
	return current, true
}

func (n *Node) isNil() bool {
	n.mtx.RLock()
	defer n.mtx.RUnlock()

	return n.Value == nil && len(n.Children) == 0
}

func (n *Node) merge(newNode *Node) {
	n.mtx.Lock()
	defer n.mtx.Unlock()

	for k, v := range newNode.Children {
		n.Children[k] = v
	}
	n.Value = newNode.Value
}

func (n *Node) prune() *Node {
	n.mtx.Lock()
	defer n.mtx.Unlock()

	if len(n.Children) > 0 || n.Value != nil {
		return nil
	}

	parent := n.Parent
	n.Parent = nil
	return parent
}


text:
<?php

namespace PragmaRX\Health\Events;

use Illuminate\Contracts\Queue\ShouldQueue;

class RaiseHealthIssue implements ShouldQueue
{
    /**
     * @var
     */
    public $failure;

    /**
     * @var
     */
    public $channel;

    /**
     * Create a new event instance.
     */
    public function __construct($failure, $channel)
    {
        $this->failure = $failure;

        $this->channel = $channel;
    }
}


text:
<?php
class ChargeBee_Content extends ChargeBee_Result
{

}
?>


text:
wordClasses = {}
positiveWords = set()
negativeWords = set()

def readVocabulary(input, s):
    with open(input) as fin:
        for line in fin:
            word = line.rstrip('\n')
            if not word or word[0] == ';': continue
            s.add(word)

def processArticle(input, html, txt, skipFirst=True):
    print(html)
    fin = open(input, 'r')
    fhtml = open(html, 'w')
    ftxt = open(txt, 'w')
    fhtml.write("""
<!DOCTYPE html>

<title>%s</title>
<meta charset="utf-8">

%s
""" % (input, input))
    start = 1 if skipFirst else 0
    for line in fin:
        fhtml.write('
')
        for triple in line.rstrip('\n').split(' ')[start:]:
            try:
                word, root, wclass = triple.split('/')
                if root in positiveWords:
                    css = "positive"
                elif root in negativeWords:
                    css = "negative"
                else:
                    css = ""
                fhtml.write('%s ' % (css, triple, word))
                ftxt.write('%s ' % word)
                if wclass not in wordClasses:
                    wordClasses[wclass] = triple
            except:
                print('    skip triple:', triple)
        fhtml.write('
\n')
        ftxt.write('\n')
    fhtml.write('''

''')
    fin.close()
    fhtml.close()
    ftxt.close()

def printWordClasses(output):
    print(output)
    with open(output, 'w') as fout:
        for key, value in wordClasses.items():
            fout.write(value)
            fout.write('\n')

readVocabulary('inputs/positive-words.txt', positiveWords)
readVocabulary('inputs/negative-words.txt', negativeWords)

processArticle('inputs/blender_sentences.txt', 'outputs/blender_sentences.html', 'outputs/blender_sentences.txt', False)
processArticle('inputs/drill_POS.txt',         'outputs/drill_POS.html',         'outputs/drill_POS.txt')
processArticle('inputs/fridge_ann.txt',        'outputs/fridge_ann.html',        'outputs/fridge_ann.txt')
processArticle('inputs/movies_ann.txt',        'outputs/movies_ann.html',        'outputs/movies_ann.txt')
processArticle('inputs/vacuum_ann.txt',        'outputs/vacuum_ann.html',        'outputs/vacuum_ann.txt')
processArticle('inputs/washer_sentences.txt',  'outputs/washer_sentences.html',  'outputs/washer_sentences.txt', False)

printWordClasses('outputs/word_class.txt')


text:
import { FileButtonLineComponent } from "../../components/lines/FileButtonLineComponent";
import type { StoryObj } from "@storybook/react";

export default {
    component: FileButtonLineComponent,
};

export const Default: StoryObj<typeof FileButtonLineComponent> = {};


text:
{% extends 'userena/profile_base.html' %}
{% load i18n %}
{% load url from future %}

{% block content_title %}<h2>{% blocktrans with user.username as username %}Account » {{ username }}{% endblocktrans %}</h2>{% endblock %}

{% block profile_content %}
  <form action="" method="post">
    {% csrf_token %}
    <fieldset>
      <legend>{% trans "Change email address" %}</legend>
      {{ form.as_p }}
    </fieldset>
    <input type="submit" value="{% trans "Change email" %}" />
  </form>
{% endblock profile_content%}

{% block extra_js %}
<script>
  $("#change_email").addClass("active");
</script>
{% endblock extra_js %}


text:
using Convay.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Convay.Core
{
    /// <summary>
    /// Serializuje pliki do formatu .glg - siatka zapisana jako ciąg bitów
    /// </summary>
    public class GridSerializer : IGridSerializer
    {
        /// <summary>
        /// Ładuje ze strumienia
        /// </summary>
        /// <param name="stream">strumień do ładowania</param>
        /// <param name="grid">wczytana siatka</param>
        public void LoadFromStream(Stream stream, IGrid grid)
        {
            BinaryReader reader = new BinaryReader(stream);
            int xSize = reader.ReadInt32();
            int ySize = reader.ReadInt32();
            int counter = 0;
            if (xSize == 0 && ySize == 0)
            {
                return;
            }
            grid.Initialize(xSize, ySize);
            byte readByte = reader.ReadByte();
            for (int i = 0; i < xSize; i++)
            {
                for (int j = 0; j < ySize; j++)
                {
                    if (counter == 8)
                    {
                        readByte = reader.ReadByte();
                        counter = 0;
                    }
                    grid[i, j] = ((readByte & 128) == 128);
                    readByte = (byte)(readByte << 1);
                    counter++;
                }
            }
        }

        /// <summary>
        /// Zapisuje do strumienia
        /// </summary>
        /// <param name="grid">siatka do zapisania</param>
        /// <param name="stream">strumień do zapisania</param>
        public void SaveToStream(IGrid grid, Stream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);
            int counter = 0;
            byte byteToWrite = 0;
            int xSize = grid.XSize;
            int ySize = grid.YSize;
            writer.Write(xSize);
            writer.Write(ySize);
            for (int i = 0; i < xSize; i++)
            {
                for (int j = 0; j < ySize; j++)
                {
                    byteToWrite = (byte)(byteToWrite << 1);
                    if (grid[i, j])
                    {
                        byteToWrite++;
                    }
                    counter++;
                    if (counter == 8)
                    {
                        counter = 0;
                        writer.Write(byteToWrite);
                        byteToWrite = 0;
                    }
                }
            }
            while (counter > 0)
            {
                byteToWrite = (byte)(byteToWrite << 1);
                counter++;
                if (counter == 8)
                {
                    counter = 0;
                    writer.Write(byteToWrite);
                    byteToWrite = 0;
                }
            }
        }
    }
}


text:
require_relative "formatter"

class SuperHTMLFormatter < Formatter

  def initialize(formatter)
    @formatter = formatter
  end

  def format
    <<~EOF
      <html>
        <body>
          #{@formatter.format}
        </body>
      </html>
    EOF
  end

end


text:
package org.apache.roller.pojos;

import java.util.Date;

/**
 * Records change that a user has made to an object.
 * @ejb:bean name="ObjectAuditData"
 * @struts.form include-all="true"
 * @hibernate.class lazy="false" table="roller_audit_log"
 *
 * @author Dave Johnson
 */
public class ObjectAuditData extends PersistentObject
{
    private String id;          // primary key
    private String userId;      // user that made change
    private String objectId;    // id of associated object, if any
    private String objectClass; // name of associated object class (e.g. WeblogEntryData)
    private String comment;     // description of change
    private Date changeTime;    // time that change was made

    public void setData(PersistentObject vo)
    {
    }

    /**
     * @ejb:persistent-field
     * @hibernate.id column="id"
     *     generator-class="uuid.hex" unsaved-value="null"
     */
    public String getId()
    {
        return id;
    }
    /** @ejb:persistent-field */
    public void setId(String id)
    {
        this.id = id;
    }
    /**
     * @ejb:persistent-field
     * @hibernate.property column="change_time" non-null="true" unique="false"
     */
    public Date getChangeTime()
    {
        return changeTime;
    }
    /** @ejb:persistent-field */
    public void setChangeTime(Date changeTime)
    {
        this.changeTime = changeTime;
    }
    /**
     * @ejb:persistent-field
     * @hibernate.property column="comment_text" non-null="true" unique="false"
     */
    public String getComment()
    {
        return comment;
    }
    /** @ejb:persistent-field */
    public void setComment(String comment)
    {
        this.comment = comment;
    }
    /**
     * @ejb:persistent-field
     * @hibernate.property column="object_class" non-null="true" unique="false"
     */
    public String getObjectClass()
    {
        return objectClass;
    }
    /** @ejb:persistent-field */
    public void setObjectClass(String objectClass)
    {
        this.objectClass = objectClass;
    }
    /**
     * @ejb:persistent-field
     * @hibernate.property column="object_id" non-null="true" unique="false"
     */
    public String getObjectId()
    {
        return objectId;
    }
    /** @ejb:persistent-field */
    public void setObjectId(String objectId)
    {
        this.objectId = objectId;
    }
    /**
     * @ejb:persistent-field
     * @hibernate.property column="user_id" non-null="true" unique="false"
     */
    public String getUserId()
    {
        return userId;
    }
    /** @ejb:persistent-field */
    public void setUserId(String userId)
    {
        this.userId = userId;
    }
}


text:
describe("find", function() {
    "use strict";

    it("should find an element by id", function() {
        jasmine.sandbox.set("test");
        expect(DOM.find("#test")).toHaveId("test");

        jasmine.sandbox.set("test");
        expect(DOM.find("#test").find("#test1")).toHaveId("test1");

        jasmine.sandbox.set("test");
        expect(DOM.find("#test").find("#test2")).toBeMock();
    });

    it("should find by id event if node was detached", function() {
        jasmine.sandbox.set("test");

        var el = DOM.find("#test");

        expect(el.find("#test1")).toHaveId("test1");

        el.remove();

        expect(el.find("#test1")).toHaveId("test1");
    });

    it("should find an element by class", function() {
        jasmine.sandbox.set("test");

        expect(DOM.find(".test321")).toHaveClass("test321");
    });

    it("should find an element by selector", function() {
        jasmine.sandbox.set("
test
");
        expect(DOM.find("#test").find("[data-attr='0']")).toHaveAttr("data-attr");

        jasmine.sandbox.set("
test
");
        expect(DOM.find("#test").find("[data-attr='1']")).toHaveAttr("data-attr");

        jasmine.sandbox.set("
test
");
        expect(DOM.find(".test").find("[data-attr='2']")).toHaveAttr("data-attr");

        // TODO: make a cotext bug fix test
    });

    it("should return at least empty element(s)", function() {
        var foo = DOM.find("foo");

        expect(foo.find("a")).toBeMock();
        expect(foo.findAll("a").length).toBe(0);
    });

    it("should fix querySelectorAll on element with context", function() {
        jasmine.sandbox.set("

");

        var foo = DOM.find(".foo");

        expect(foo[0].querySelectorAll("div span").length).toBe(1);

        expect(foo.findAll("div span").length).toBe(0);
        expect(foo.get("id")).toBeFalsy();
    });

    it("should throw error if the first argument is not a string", function() {
        expect(function() { DOM.find(1); }).toThrow();
    });

    it("should throw error if selector is not valid", function() {
        jasmine.clock().install();

        expect(function() { DOM.find("$test"); }).toThrow();

        jasmine.clock().uninstall();
    });

    it("might return empty results", function() {
        expect(DOM.findAll("details")).toEqual([]);
        expect(DOM.find("details")[0]).toBeUndefined();
    });

    it("works for fragments", function() {
        var fragment = document.createDocumentFragment();
        var fragmentEl = DOM.constructor(fragment);

        expect(fragmentEl.findAll("*")).toEqual([]);
    });

});


text:
from django.core.management import call_command
from django.conf import settings
from django.db import connection
from django.test import TransactionTestCase

from django_tenants.utils import get_tenant_model, get_tenant_domain_model, get_public_schema_name

ALLOWED_TEST_DOMAIN = '.test.com'

class TenantTestCase(TransactionTestCase):

    def setUp(self):
        self.sync_shared()
        test_schema_name = self.get_test_schema_name()
        test_tenant_domain_name = self.get_test_tenant_domain()
        self.tenant = get_tenant_model()(schema_name=test_schema_name)
        self.setup_tenant(self.tenant)
        self.tenant.save(verbosity=0)  # todo: is there any way to get the verbosity from the test command here?

        # Set up domain
        self.domain = get_tenant_domain_model()(tenant=self.tenant, domain=test_tenant_domain_name)
        self.setup_domain(self.domain)
        self.domain.save()

        connection.set_tenant(self.tenant)

    def tearDown(self):
        connection.set_schema_to_public()
        self.domain.delete()
        self.tenant.delete(force_drop=True)

    @staticmethod
    def add_allowed_test_domain():
        # ALLOWED_HOSTS is a special setting of Django setup_test_environment so we can't modify it with helpers
        if ALLOWED_TEST_DOMAIN not in settings.ALLOWED_HOSTS:
            settings.ALLOWED_HOSTS += [ALLOWED_TEST_DOMAIN]

    @staticmethod
    def remove_allowed_test_domain():
        if ALLOWED_TEST_DOMAIN in settings.ALLOWED_HOSTS:
            settings.ALLOWED_HOSTS.remove(ALLOWED_TEST_DOMAIN)

    # noinspection PyMethodMayBeStatic
    def setup_tenant(self, tenant):
        """
        Add any additional setting to the tenant before it get saved. This is required if you have
        required fields.
        :param tenant:
        :return:
        """
        pass

    # noinspection PyMethodMayBeStatic
    def setup_domain(self, domain):
        """
        Add any additional setting to the domain before it get saved. This is required if you have
        required fields.
        :param domain:
        :return:
        """
        pass

    @classmethod
    def sync_shared(cls):
        call_command('migrate_schemas',
                     schema_name=get_public_schema_name(),
                     interactive=False,
                     verbosity=0)

    @staticmethod
    def get_test_tenant_domain():
        return 'tenant.test.com'

    @staticmethod
    def get_test_schema_name():
        return 'test'

class FastTenantTestCase(TenantTestCase):

    def setUp(self):
        self.sync_shared()
        tenant_model = get_tenant_model()
        test_schema_name = self.get_test_schema_name()
        test_tenant_domain_name = self.get_test_tenant_domain()

        if tenant_model.objects.filter(schema_name=test_schema_name).exists():
            self.tenant = tenant_model.objects.filter(schema_name=test_schema_name).first()
        else:
            self.tenant = tenant_model(schema_name=test_schema_name)
            self.tenant.save(verbosity=0)

            self.domain = get_tenant_domain_model()(tenant=self.tenant, domain=test_tenant_domain_name)
            self.setup_domain(self.domain)
            self.domain.save()

        connection.set_tenant(self.tenant)

    def tearDown(self):
        connection.set_schema_to_public()
        self.remove_allowed_test_domain()


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sample.app;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("http://localhost:3000/");
    }
}


text:
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Indicator } from '../models/indicator.model';

@Injectable()
export class IndicatorService {

  private url = 'http://localhost:9000';
  private urlGet = this.url + '/indicators';

  constructor(private http: Http) { }

  getStocks(symbols: string[]): Observable<Indicator[]> {
    let params: URLSearchParams = new URLSearchParams();
    for (let symbol of symbols) {
      params.append('symbols', symbol);
    }
    return this.http.get(this.urlGet, {
      search: params
    }).map((response: Response) => response.json() as Indicator[]);
  }
}


text:
import { TabsWithAsynchronouslyLoadingModule } from './tabs-with-asynchronously-loading.module';

describe('TabsWithAsynchronouslyLoadingModule', () => {
  let tabsWithAsynchronouslyLoadingModule: TabsWithAsynchronouslyLoadingModule;

  beforeEach(() => {
    tabsWithAsynchronouslyLoadingModule = new TabsWithAsynchronouslyLoadingModule();
  });

  it('should create an instance', () => {
    expect(tabsWithAsynchronouslyLoadingModule).toBeTruthy();
  });
});


text:
package com.kopysoft.MorseMessenger.recieve;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Vibrator;
import android.util.Log;

import com.kopysoft.MorseMessenger.Defines;
import com.kopysoft.MorseMessenger.StringMap;

/** How all tones will be played
 *
 * @author Ethan Hall
 */
public class PlayMessage extends IntentService {

	private static final String TAG = Defines.TAG + " - PlayMessage";
	private static final boolean printDebugMessages = Defines.printDebugMessages;

	public PlayMessage() {
		super("PlayMessage");
	}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getAction() != null && intent.getAction().equals("stop"))
            stopSelf();
        else
            onStart(intent, startId);
        return START_NOT_STICKY;
    }

	@Override
	protected void onHandleIntent(Intent intent) {
		String Message = intent.getExtras().getString("message").toUpperCase();
		int delay = intent.getExtras().getInt("speed", 75);//tone
		int tone = intent.getExtras().getInt("tone", ToneGenerator.TONE_DTMF_0);
		boolean vib = intent.getExtras().getBoolean("viberate", false);
		int vibSpeed = intent.getExtras().getInt("viberateSpeed", 100);
		if(printDebugMessages) Log.d(TAG, Message);

		try{
			Thread.sleep(3000);
			if(!vib)
				playMessageSound(Message, delay, tone, 100);
			else
				playMessageVib(Message, vibSpeed, getBaseContext());
		} catch( Exception e){
			Log.d(TAG, e.toString());
		}
	}

	/**	Method of playMessageVib(String message, int delay, Context context) throws InterruptedException
	 *
	 * Plays a message out on the vibrator, on general you should set the delay to be 3 times that
	 * 	of the sound delay.
	 *
	 * @author Ethan Hall
	 * @param message	STring that will be viberated out
	 * @param delay		Base delay in MS
	 * @param context	Context of this service
	 * @throws InterruptedException
	 */
	private void playMessageVib(String message, int delay, Context context) throws InterruptedException{
		Vibrator vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
		char[] charMessage = message.toCharArray();
		StringMap map = new StringMap();
		int timeToPlay = 0;
        AudioManager audio = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
        int prevLevel = audio.getStreamVolume(AudioManager.STREAM_RING);

		for(int i = 0; i < charMessage.length; i++){
			String charToSend = map.getVal(Character.toString((char)charMessage[i]));
			if(printDebugMessages) Log.d(TAG, "Message[" + i + "]: " + charMessage[i]);
			if(charToSend != null){
				byte[] brokenString = charToSend.getBytes();
				for(int j = 0; j < brokenString.length; j++){

					if(((char)brokenString[j]) == '.'){
						timeToPlay = delay;
					} else if(((char)brokenString[j]) == '-') {
						timeToPlay = delay * 3;
					} else if(((char)brokenString[j]) == ' ') {
						timeToPlay = delay * 2;	//Will add up to 7
					}

					if(((char)brokenString[j]) != ' '){
						vib.vibrate(timeToPlay);
					}

					Thread.sleep(timeToPlay);
					vib.cancel();
					Thread.sleep(delay);
				}
				Thread.sleep(delay * 3);
                if(prevLevel != audio.getStreamVolume(AudioManager.STREAM_RING)){
                    break;
                }
			}
		}
	}

	/**	Method of playMessageSound(String message, int delay, int tone, int volume) throws InterruptedException
	 *
	 * Plays a message on the speaker using ToneGenerator.
	 *
	 * @author Ethan Hall
	 * @param message	STring that will be vibrated out
	 * @param delay		Base delay in MS
	 * @param tone		a {@link}AudioManager define
	 * @param volume	Percentage from 0 - 100 of the volume
	 * @throws InterruptedException
	 */
	private void playMessageSound(String message, int delay, int tone, int volume) throws InterruptedException{
		ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_RING,volume);
		char[] charMessage = message.toCharArray();
		StringMap map = new StringMap();
		int timeToPlay = 0;
        AudioManager audio = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
        int prevLevel = audio.getStreamVolume(AudioManager.STREAM_RING);

		for(int i = 0; i < charMessage.length; i++){
			String charToSend = map.getVal(Character.toString((char)charMessage[i]));
			if(printDebugMessages) Log.d(TAG, "Message[" + i + "]: " + charMessage[i]);
			if(charToSend != null){
				byte[] brokenString = charToSend.getBytes();
				for(int j = 0; j < brokenString.length; j++){

					if(((char)brokenString[j]) == '.'){
						timeToPlay = delay;
					} else if(((char)brokenString[j]) == '-') {
						timeToPlay = delay * 3;
					} else if(((char)brokenString[j]) == ' ') {
						timeToPlay = delay * 2;	//Will add up to 7
					}

					if(((char)brokenString[j]) != ' '){
						tg.startTone(tone, timeToPlay);
					}

					Thread.sleep(timeToPlay);
					Thread.sleep(delay);
				}
				Thread.sleep(delay * 3);
                if(prevLevel != audio.getStreamVolume(AudioManager.STREAM_RING)){
                    break;
                }
			}
		}
	}

}


text:
package com.cool.session;

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

/**
 *
* @ClassName: UserSession
* @Description: 用户属性的信息存储
* @author panlei
* @date 2017年7月21日 下午1:52:27
*
 */
public class UserSession implements Serializable {
	/**
	* @Fields serialVersionUID : 序列化
	*/
	private static final long serialVersionUID = 7542738449824934875L;

	private Long id;

	private String account;

	private String userType;

	private Long shopId;
	/**
	 * 用户权限
	 */
	private List<String> permissionList;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getUserType() {
		return userType;
	}
	public void setUserType(String userType) {
		this.userType = userType;
	}
	public List<String> getPermissionList() {
		return permissionList;
	}
	public void setPermissionList(List<String> permissionList) {
		this.permissionList = permissionList;
	}
	public Long getShopId() {
		return shopId;
	}
	public void setShopId(Long shopId) {
		this.shopId = shopId;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Footer</title>

    <link rel="stylesheet" href="../assets/icons/icomoon/style.css">
    <link rel="stylesheet" href="../assets/normalize/normalize.css">
    <link rel="stylesheet" href="../assets/pure/base.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-grid.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-base-styles.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-typography.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-links.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-buttons.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-forms.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-code.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-tables.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-spacing.css">
    <link rel="stylesheet" href="../assets/skeleton/skeleton-utilities.css">
    <link rel="stylesheet" href="trim-text.css">
    <link rel="stylesheet" href="nowrap-text.css">
    <link rel="stylesheet" href="anchor.css">
    <link rel="stylesheet" href="footer.css">

          Projet
            GitHub

         English


text:
<?xml version="1.0" encoding="utf-8"?>
<resources >
	<string name = "pull_to_refresh_pull_label" >Trage pentru a reîmprospăta…</string >
	<string name = "pull_to_refresh_release_label" >Eliberează pentru a reîmprospăta…</string >
	<string name = "pull_to_refresh_refreshing_label" >Încărcare…</string >
</resources >


text:
<?php

// Check user and app status
OCP\JSON::checkAdminUser();
OCP\JSON::checkAppEnabled('user_ldap');
OCP\JSON::callCheck();

$prefix = $_POST['ldap_serverconfig_chooser'];
if(\OCA\user_ldap\lib\Helper::deleteServerConfiguration($prefix)) {
	OCP\JSON::success();
} else {
	$l=OC_L10N::get('user_ldap');
	OCP\JSON::error(array('message' => $l->t('Failed to delete the server configuration')));
}


text: module.exports = require('../lib/Storage/BrowserLocalStorage');


text:
/* @flow */

import { extend, warn, isObject } from 'core/util/index'

/**
 * Runtime helper for rendering <slot>
 */
export function renderSlot (
  name: string,
  fallbackRender: ?((() => Array<VNode>) | Array<VNode>),
  props: ?Object,
  bindObject: ?Object
): ?Array<VNode> {
  const scopedSlotFn = this.$scopedSlots[name]
  let nodes
  if (scopedSlotFn) {
    // scoped slot
    props = props || {}
    if (bindObject) {
      if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
        warn('slot v-bind without argument expects an Object', this)
      }
      props = extend(extend({}, bindObject), props)
    }
    nodes =
      scopedSlotFn(props) ||
      (typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender)
  } else {
    nodes =
      this.$slots[name] ||
      (typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender)
  }

  const target = props && props.slot
  if (target) {
    return this.$createElement('template', { slot: target }, nodes)
  } else {
    return nodes
  }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace SharpRT
{
    /// <summary>
    /// Represents a rendering context for a worker thread.
    /// </summary>
    public struct RenderContext
    {
        public Random Random;
        public Scene Scene;

        public RenderContext(Scene scene)
        {
            this.Scene = scene;
            this.Random = new Random();
        }
    }

    class MainClass
    {
        private static IList<Light> lights = new List<Light>() {
            new Light(new Point(-2, 1, 0), 20),
        };

        // used when a ray escapes from the scene (assumes constant sky radiance)
        // later on you could implement a sky/environment class that takes the
        // escaped direction and works out the incoming radiance using e.g. an
        // environment map or atmospheric simulation
        private static Vector skyRadiance = new Vector(0.5f, 0.5f, 0.5f);

        public static Vector Radiance(RenderContext ctx, Ray ray)
        {
            const int MAX_BOUNCES = 10;

            Vector weights = new Vector(1.0f, 1.0f, 1.0f);
            Vector radiance = Vector.Zero;

            for (int bounce = 0; bounce < MAX_BOUNCES; ++bounce) {
                Surface.Intersection intersection;

                if (!ctx.Scene.Intersect(ray, 1e-4f, float.PositiveInfinity, out intersection)) {
                    radiance += weights * skyRadiance;
                    break;
                }

                var surface = ctx.Scene[intersection.SurfaceID];
                var surf = surface.At(intersection);

                var outgoing = new Direction(-ray.Direction, surf.Basis);
                var hitPoint = Ray.PointAt(ray, intersection.Distance);

                /* Include object emittance as light path */

                radiance += weights * surf.Material.Emittance(outgoing, surf.Basis);

                /* Include point light source light paths */

                foreach (var light in lights) {
                    var pointToLight = light.position - hitPoint;
                    var lightDistance = pointToLight.Length();

                    if (!ctx.Scene.Occlusion(new Ray(hitPoint, pointToLight), 1e-4f, lightDistance)) {
                        Direction incomimg = new Direction(pointToLight / lightDistance, surf.Basis);

                        radiance += weights * surf.Material.BRDF(incomimg, outgoing, surf.Basis) * incomimg.CosTheta
                                  * light.intensity / (lightDistance * lightDistance);
                    }
                }

                /* Russian roulette */

                Vector weight = surf.Material.WeightPDF(outgoing, surf.Basis);
                float p = Math.Max(weight.X, Math.Max(weight.Y, weight.Z));

                if (bounce > 2) {
                    if (ctx.Random.NextDouble() <= p) {
                        weight /= p;
                    } else {
                        break;
                    }
                }

                /* Update light path weights and prepare for next bounce */

                weights *= weight;

                var newDir = surf.Material.SamplePDF(outgoing, surf.Basis, ctx.Random);

                ray = new Ray(hitPoint, newDir);
            }

            return radiance;
        }

        public static int FloatToInt(float rgb)
        {
            if (rgb < 0) {
                return 0;
            } else if (rgb > 1) {
                return 255;
            } else {
                return (int)(rgb * 255);
            }
        }

        public static void Main(string[] args)
        {
            if ((args.Length < 2) || (args.Length > 5)) {
                Console.WriteLine("Usage:\n\tRaytracer.exe [scene file] [output file] [sample count = 250] [width = 800] [height = 600]");
                return;
            }

            Camera camera;

            using (var scene = Loader.LoadScene(args[0], out camera)) {
                int width = args.Length >= 4 ? int.Parse(args[3]) : 800;
                int height = args.Length >= 5 ? int.Parse(args[4]) : 600;
                var img = new Bitmap(width, height, PixelFormat.Format24bppRgb);

                float uScale = 1;
                float vScale = 1;

                if (img.Width > img.Height) {
                    uScale = (float)img.Width / img.Height;
                } else if (img.Height > img.Width) {
                    vScale = (float)img.Height / img.Width;
                }

                byte[] pixelData = new byte[img.Width * img.Height * 3];

                Parallel.For(0, height, () => new RenderContext(scene), (y, pls, ctx) => {
                    for (int x = 0; x < width; ++x) {
                        float u = 2 * ((float)x / (width - 1)) - 1;
                        float v = 1 - 2 * ((float)y / (height - 1));

                        u *= uScale;
                        v *= vScale;

                        var ray = camera.TraceRay(u, v);

                        Vector radiance = Vector.Zero;

                        int SAMPLES = args.Length >= 3 ? int.Parse(args[2]) : 250; // more = crisper image

                        for (int s = 0; s < SAMPLES; ++s) {
                            radiance += Radiance(ctx, ray);
                        }

                        pixelData[3 * (y * width + x) + 2] = (byte)FloatToInt(radiance.X / SAMPLES); /* BGR legacy */
                        pixelData[3 * (y * width + x) + 1] = (byte)FloatToInt(radiance.Y / SAMPLES);
                        pixelData[3 * (y * width + x) + 0] = (byte)FloatToInt(radiance.Z / SAMPLES);
                    }

                    return ctx;
                }, (ctx) => {});

                var bitmapData = img.LockBits(new Rectangle(0, 0, width, height),
                                              ImageLockMode.WriteOnly,
                                              PixelFormat.Format24bppRgb);
                Marshal.Copy(pixelData, 0, bitmapData.Scan0, pixelData.Length);
                img.UnlockBits(bitmapData);

                img.Save(args[1], ImageFormat.Png);
            }
        }
    }
}


text:
title: Telerik.Web.UI.RadFilterContainsFilterExpression
page_title: Telerik.Web.UI.RadFilterContainsFilterExpression
description: Telerik.Web.UI.RadFilterContainsFilterExpression
---

# Telerik.Web.UI.RadFilterContainsFilterExpression

Represents a strongly typed Contains filter expression.

## Inheritance Hierarchy

* System.Object
* Telerik.Web.StateManager : IMarkableStateManager, IStateManager
* Telerik.Web.UI.RadFilterExpression
* Telerik.Web.UI.RadFilterNonGroupExpression
* Telerik.Web.UI.RadFilterSingleValueExpression`1 : IRadFilterValueExpression
* Telerik.Web.UI.RadFilterContainsFilterExpression

## Properties

###  FieldName `String`

Gets or sets the name of the field the current expression is used for.

###  FieldType `Type`

Gets the type of the field the expression is built for.

###  FieldType `Type`

Gets or sets the name of the field the current expression is used for.

###  FilterFunction `RadFilterFunction`

Gets a RadFilterFunction value representing the Contains filter function.

###  FilterFunction `RadFilterFunction`

Gets the filter function used in the current expression.

###  Value `T`

Gets or sets the value of the type provided when initializing the generic class.


text:
div.loader {
    position: absolute;
    background: url(ajax_loader_gray_512.gif);
    background-size: 200px 200px;
/*    background-color: #00ff00;
*/ top: 50px;
 left: 54px;
 display: none;
    width: 200px;
    height: 200px;
 z-index: 20;
}

div.loader-container {
    position: relative;
}


text:
export default function isFunction(x: any): boolean {
    return (typeof x === 'function');
}


text:
package org.mockserver.test;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

/**
 * <pre>
 *  <plugin>
 *  <groupId>org.apache.maven.plugins</groupId>
 *  <artifactId>maven-failsafe-plugin</artifactId>
 *  <version>2.20.1</version>
 *  <configuration>
 *     <properties>;
 *     <property>
 *     <name>listener</name>
 *     <value>org.mockserver.test.PrintCurrentTestListener</value>
 *     </property>
 *     </properties>
 *     </configuration>
 *     <executions>
 *     <execution>
 *     <goals>
 *     <goal>integration-test</goal>
 *     <goal>verify</goal>
 *     </goals>
 *     </execution>
 *     </executions>
 *  </plugin>
 * </pre>
 */
public class PrintCurrentTestListener extends RunListener {

    @Override
    public void testRunStarted(Description description) {
        if (description != null) {
            System.out.println("testRunStarted " + String.valueOf(description.getClassName()) + " " + String.valueOf(description.getDisplayName()) + " " + String.valueOf(description.toString()));
        }
    }

    @Override
    public void testStarted(Description description) {
        System.out.println("testStarted " + String.valueOf(description));
    }

    @Override
    public void testFinished(Description description) {
        System.out.println("testFinished " + String.valueOf(description));
    }

    public void testFailure(Failure failure) {
        System.out.println("testFailure " + String.valueOf(failure));
    }

    public void testAssumptionFailure(Failure failure) {
        System.out.println("testAssumptionFailure " + String.valueOf(failure));
    }

    public void testIgnored(Description description) {
        System.out.println("testIgnored " + String.valueOf(description));
    }

    @Override
    public void testRunFinished(Result result) {
        if (result != null) {
            System.out.println("testRunFinished " + String.valueOf(result)
                + " time:" + String.valueOf(result.getRunTime())
                + " R" + String.valueOf(result.getRunCount())
                + " F" + String.valueOf(result.getFailureCount())
                + " I" + String.valueOf(result.getIgnoreCount())
            );
        }
    }

}


text:
package com.fjj.ui.servlet;

import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.imgscalr.Scalr;
import org.json.JSONArray;
import org.json.JSONObject;

import com.fjj.ui.utils.RequestUtil;

/**
 * @author owen li
 *
 */
public class UploadServlet extends HttpServlet {
	private transient static Log log = LogFactory.getLog(UploadServlet.class);
	private File fileUploadPath;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		fileUploadPath = new File(config.getInitParameter("upload_path"));
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getParameter("getfile") != null
				&& request.getParameter("getfile").length() > 0) {
			File file = new File(fileUploadPath,
					request.getParameter("getfile"));
			if (file.exists()) {
				int bytes = 0;
				ServletOutputStream op = response.getOutputStream();
				response.setContentType(getMimeType(file));
				response.setContentLength((int) file.length());
				response.setHeader("Content-Disposition", "inline; filename=\""
						+ file.getName() + "\"");
				byte[] bbuf = new byte[1024];
				DataInputStream in = new DataInputStream(new FileInputStream(
						file));
				while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
					op.write(bbuf, 0, bytes);
				}
				in.close();
				op.flush();
				op.close();
			}
		} else if (request.getParameter("delfile") != null
				&& request.getParameter("delfile").length() > 0) {
			File file = new File(fileUploadPath,
					request.getParameter("delfile"));
			if (file.exists()) {
				file.delete(); // TODO:check and report success
			}
		} else if (request.getParameter("getthumb") != null
				&& request.getParameter("getthumb").length() > 0) {
			File file = new File(fileUploadPath,
					request.getParameter("getthumb"));
			if (file.exists()) {
				String mimetype = getMimeType(file);
				if (mimetype.endsWith("png") || mimetype.endsWith("jpeg")
						|| mimetype.endsWith("gif")) {
					BufferedImage im = ImageIO.read(file);
					if (im != null) {
						BufferedImage thumb = Scalr.resize(im, 75);
						ByteArrayOutputStream os = new ByteArrayOutputStream();
						if (mimetype.endsWith("png")) {
							ImageIO.write(thumb, "PNG", os);
							response.setContentType("image/png");
						} else if (mimetype.endsWith("jpeg")) {
							ImageIO.write(thumb, "jpg", os);
							response.setContentType("image/jpeg");
						} else {
							ImageIO.write(thumb, "GIF", os);
							response.setContentType("image/gif");
						}
						ServletOutputStream srvos = response.getOutputStream();
						response.setContentLength(os.size());
						response.setHeader("Content-Disposition",
								"inline; filename=\"" + file.getName() + "\"");
						os.writeTo(srvos);
						srvos.flush();
						srvos.close();
					}
				}
			} // TODO: check and report success
		} else {
			PrintWriter writer = response.getWriter();
			writer.write("call POST with multipart form data");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (!ServletFileUpload.isMultipartContent(request)) {
			throw new IllegalArgumentException(
					"Request is not multipart, please 'multipart/form-data' enctype for your form.");
		}
		ServletFileUpload uploadHandler = new ServletFileUpload(
				new DiskFileItemFactory());
		PrintWriter writer = response.getWriter();
		response.setContentType("application/json");
		JSONArray json = new JSONArray();
		try {
			List<FileItem> items = uploadHandler.parseRequest(request);
			for (FileItem item : items) {
				if (!item.isFormField()) {
					File file = new File(fileUploadPath, item.getName());
					item.write(file);
					JSONObject jsono = new JSONObject();
					jsono.put("name", item.getName());
					jsono.put("size", item.getSize());
					jsono.put("url", "upload?getfile=" + item.getName());
					jsono.put("thumbnail_url",
							"upload?getthumb=" + item.getName());
					jsono.put("delete_url", "upload?delfile=" + item.getName());
					jsono.put("delete_type", "GET");
					json.put(jsono);
				}
			}
		} catch (FileUploadException e) {
			throw new RuntimeException(e);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			writer.write(json.toString());
			writer.close();
		}
	}

	private String getMimeType(File file) {
		String mimetype = "";
		if (file.exists()) {
			// URLConnection uc = new URL("file://" +
			// file.getAbsolutePath()).openConnection();
			// String mimetype = uc.getContentType();
			// MimetypesFIleTypeMap gives PNG as application/octet-stream, but
			// it seems so does URLConnection
			// have to make dirty workaround
			if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
				mimetype = "image/png";
			} else {
				javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
				mimetype = mtMap.getContentType(file);
			}
		}
		System.out.println("mimetype: " + mimetype);
		log.debug("mimetype: " + mimetype);
		return mimetype;
	}

	private String getSuffix(String filename) {
		String suffix = "";
		int pos = filename.lastIndexOf('.');
		if (pos > 0 && pos < filename.length() - 1) {
			suffix = filename.substring(pos + 1);
		}
		System.out.println("suffix: " + suffix);
		log.debug("suffix: " + suffix);
		return suffix;
	}

}


text:
\Section{Results}
\label{section:results}

Introduce specific example along with details that get all the way down to the measurement points.

% Insert deployed software diagram here


text:
package com.tags.others;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.ui.ApiUi;

@SuppressWarnings("serial")
public class Small extends TagSupport{
	private String value;

	public int doStartTag() throws JspException {
		ApiUi api= ApiUi.getInstance();

		//Armo un mapa con los valores de configuracion del Componente
		Map<String, Object> valores= new HashMap<String, Object>();
		valores.put("config.value", this.getValue());

		//Perform substr operation on string.
		try {
			//Get the writer object for output.
			JspWriter out = pageContext.getOut();
			//Imprimo el resultado en la JSP
			out.println(api.imprimirComponente("small", valores));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return EVAL_BODY_INCLUDE;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}


text:
import subprocess
import sys
import os
import math

# This code is meant to manage running multiple instances of my KMCLib codes at the same time,
# in the name of time efficiency
numConcs = 16
numLambda = 16
numStepsEquilib = 1600000
numStepsAnal = 512
numStepsReq = 4096
sysWidth = 16
sysLength = 16
analInterval = 1
numPasses = 10000
timeInterval = 1.0
aParam = 1.0
dataLocation = "dim2Runs/periodic/periodicSmall"
lambdaMin = 0.01
lambdaMax = 100.0
rateStepSize = (lambdaMax-lambdaMin)/float(numLambda-1)
concMax = 0.99
concMin = 0.01
concStepSize = (concMax-concMin)/float(numConcs-1)

jobIndex = 1

runningJobs = []

for rateIndex in range(0, numLambda):
    tempRate = lambdaMin + rateStepSize*rateIndex
    currentRate = (lambdaMax - lambdaMin)*(math.exp(aParam*(tempRate-lambdaMin)/(lambdaMax-lambdaMin))-1.0)/(math.exp(aParam)-1) + lambdaMin
    for concIndex in range(0, numConcs):
        conc = concMin + concStepSize*concIndex
        jobInput = "2dPeriodic.py "+str(conc)+" "+str(currentRate)+" "+str(sysWidth)+" "+str(sysLength)+" "+str(analInterval)+" "+str(numStepsEquilib)+" "+str(numStepsAnal)+" "+str(numStepsReq)+" "+str(numPasses)+" "+dataLocation+"/"+str(rateIndex)+"/"+str(concIndex)+"\n"
        with open("jobInputs/testInput."+str(jobIndex), 'w') as f:
            f.write(jobInput)
        jobIndex += 1


text:
package com.wantdo.stat.schedule;

import com.wantdo.stat.entity.shop.Express;
import com.wantdo.stat.entity.shop.Order;
import com.wantdo.stat.service.account.ExpressService;
import com.wantdo.stat.web.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ Date : 15/10/8
 * @ From : stat
 * @ Author : luanx@wantdo.com
 */

@Component
public class ExpressScanner {

    @Autowired
    private ExpressService expressService;

    public void executeByJdk() {
        execute("jdk timer job");
    }

    public void executeBySpringCronByJava(){
        execute("spring cron job by java");
    }

    //被Spring的quartz MethodInvokingjobDetailFactoryBean反射执行
    public void executeByQuartzLocalJob(){
        execute("quartz local job");
    }

    //被Spring的Scheduler namespace发射构造成ScheduleMethodRunnable
    public void executeBySpringCronByXml(){
        execute("spring cron job by xml");
    }

    //被Spring的Scheduler namespace发射构造成ScheduleMethodRunnable
    public void executeBySpringTimerByXml(){
        execute("spring timer job by xml");
    }

    /**
     * 定时查询快递状态
     */
    private void execute(String by) {
        Logger logger = LoggerFactory.getLogger(ExpressScanner.class.getName() + "." + by);
        List<Order> orderList = expressService.getAllOrderWithinAMonth();

        for (Order order: orderList){
            String url = "http://www.17track.net/r/handlertrack" +
                    ".ashx?callback=express";
            String trackno = order.getTrackno();
            Express express = order.getExpress();
            if (express != null){
                String expressCode = express.getCode();
                url += "&num=" + trackno + "&et=" + expressCode + "&_=" + System.currentTimeMillis();
                String str = HttpClientUtil.get(url);
                logger.info("{}", url);
            }
        }
    }

}


text:
package server

import (
	"github.com/gocraft/web"
	"os"
	"os/user"
	"runtime"
	"sync"
)

var (
	serverStatusGetwdWarnOnce       sync.Once
	serverStatusHostnameWarnOnce    sync.Once
	serverStatusUserCurrentWarnOnce sync.Once
)

type serverStatus struct {
	*APIContext
}

func setUpServerStatusRouter(prefix string, router *web.Router) {
	root := router.Subrouter(serverStatus{}, "")
	root.Get("/runtime_status", (*serverStatus).RuntimeStatus)
}

func (ss *serverStatus) RuntimeStatus(rw web.ResponseWriter, req *web.Request) {
	res := map[string]interface{}{
		"num_goroutine": runtime.NumGoroutine(),
		"num_cgo_call":  runtime.NumCgoCall(),
		"gomaxprocs":    runtime.GOMAXPROCS(0),
		"goroot":        runtime.GOROOT(),
		"num_cpu":       runtime.NumCPU(),
		"goversion":     runtime.Version(),
		"pid":           os.Getpid(),
	}

	logOnce := func(name string, once *sync.Once) {
		once.Do(func() {
			ss.APIContext.Log().Warnf("runtime status '%v' isn't supported on this environment (this log is only written once)", name)
		})
	}

	if dir, err := os.Getwd(); err != nil {
		logOnce("working_directory", &serverStatusGetwdWarnOnce)
	} else {
		res["working_directory"] = dir
	}
	if host, err := os.Hostname(); err != nil {
		logOnce("hostname", &serverStatusHostnameWarnOnce)
	} else {
		res["hostname"] = host
	}
	if user, err := user.Current(); err != nil {
		logOnce("user", &serverStatusUserCurrentWarnOnce)
	} else {
		res["user"] = user.Username
	}
	ss.Render(res)
}


text:
Completed ZF2 Tutorial
=======================

Introduction
------------
Functional ZF2 tutorial.

Installation
------------
    cd my/project/dir
    git clone git@github.com:danieljin/zf2-tutorial-completed.git
    cd zf2-tutorial-completed
    php composer.phar self-update
    php composer.phar install

Replace config/autoload/sample-local.php credentials and rename file to local.php

Setup Apache and point to to the public/ directory of the project.


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18444
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace OpenRiaServices.Controls {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class EntityCollectionViewResources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal EntityCollectionViewResources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OpenRiaServices.Windows.Controls.OpenRiaServices.Windows.Controls.EntityCollectio" +
                            "nViewResources", typeof(EntityCollectionViewResources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Changing the PageSize is not allowed during an AddNew or EditItem transaction..
        /// </summary>
        internal static string ChangingPageSizeNotAllowedDuringAddOrEdit {
            get {
                return ResourceManager.GetString("ChangingPageSizeNotAllowedDuringAddOrEdit", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Index was out of range. Must be non-negative and less than the size of the collection..
        /// </summary>
        internal static string IndexOutOfRange {
            get {
                return ResourceManager.GetString("IndexOutOfRange", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The value of argument '{0}' ({1}) is invalid for Enum type '{2}'..
        /// </summary>
        internal static string InvalidEnumArgument {
            get {
                return ResourceManager.GetString("InvalidEnumArgument", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to PageSize cannot be a negative value..
        /// </summary>
        internal static string InvalidPageSize {
            get {
                return ResourceManager.GetString("InvalidPageSize", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The item provided is not an instance of type '{0}'..
        /// </summary>
        internal static string ItemNotEntityType {
            get {
                return ResourceManager.GetString("ItemNotEntityType", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cannot change or check the contents or Current position of the ICollectionView while Refresh is being deferred..
        /// </summary>
        internal static string NoCheckOrChangeWhenDeferred {
            get {
                return ResourceManager.GetString("NoCheckOrChangeWhenDeferred", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to '{0}' is not supported by this ICollectionView..
        /// </summary>
        internal static string NotSupported {
            get {
                return ResourceManager.GetString("NotSupported", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to '{0}' is not allowed during an AddNew or EditItem transaction..
        /// </summary>
        internal static string OperationNotAllowedDuringAddOrEdit {
            get {
                return ResourceManager.GetString("OperationNotAllowedDuringAddOrEdit", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to '{0}' is not allowed during a transaction begun by '{1}'..
        /// </summary>
        internal static string OperationNotAllowedDuringTransaction {
            get {
                return ResourceManager.GetString("OperationNotAllowedDuringTransaction", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Refresh() cannot be called inside a DeferRefresh() transaction..
        /// </summary>
        internal static string RefreshWithinDeferRefresh {
            get {
                return ResourceManager.GetString("RefreshWithinDeferRefresh", resourceCulture);
            }
        }
    }
}


text:
package java.util

trait Formattable {
  def formatTo(formatter: Formatter, flags: Int, width: Int, precision: Int): Unit
}


text:
package com.garlicg.cutinlib;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

/**
 * カットインマネージャーとの連携関係のUtiltyです。
 */
public class CutinManagerUtils {
	public final static String ACTION_PICK_CUTIN ="com.garlicg.cutin.action.PICK";
	public final static String ACTION_SET_CUTIN ="com.garlicg.cutin.action.SET";
	public static final String PACKAGE_NAME_CUTIN_MANAGER = "com.garlicg.cutin";

	/**
	 * カットインマネージャーからよばれた際のResultとして返却するIntentを構築します。
	 *
	 */
	public static Intent buildResultIntent(CutinItem item){
		Intent intent = new Intent();
		intent.putExtra(CutinService.EXTRA_CUTIN_ACTION, item.serviceClass.getName());
		intent.putExtra(CutinService.EXTRA_CUTIN_TITLE, item.cutinName);
		intent.putExtra(CutinService.EXTRA_CUTIN_ID, item.cutinId);
		return intent;
	}

	/**
	 * カットイン設定Activityを呼び出すIntentを構築します。
	 * 呼び出されるActivityはカットインマネージャーのダイアログテーマになっています。
	 */
	public static Intent buildInAppSetIntent(CutinItem item){
		Intent intent = new Intent(ACTION_SET_CUTIN);
		intent.setPackage(PACKAGE_NAME_CUTIN_MANAGER);
		intent.putExtra(CutinService.EXTRA_CUTIN_ACTION, item.serviceClass.getName());
		intent.putExtra(CutinService.EXTRA_CUTIN_TITLE, item.cutinName);
		intent.putExtra(CutinService.EXTRA_CUTIN_ID, item.cutinId);
		return intent;
	}

	/**
	 * カットインマネージャーからカットイン設定Activityを呼び出します。
	 */
	public static boolean startActivityInAppSet(Context context , CutinItem item){
		try{
			context.startActivity(buildInAppSetIntent(item));
		}catch(ActivityNotFoundException e){
			return false;
		}
		return true;
	}

	/**
	 * カットインマネージャーが存在するか否かを判定します。
	 */
	public static boolean existManager(Context context){
		PackageManager pm = context.getPackageManager();
		Intent intent = pm.getLaunchIntentForPackage(PACKAGE_NAME_CUTIN_MANAGER);
		return intent != null;
	}

	/**
	 * GooglePlayのカットインマネージャーに遷移するIntentを構築します。
	 */
	public static Intent buildMarketIntent(){
		Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.garlicg.cutin"));
		return intent;
	}

	/**
	 * GooglePlayのカットインマネージャーページに遷移します。
	 */
	public static void startActivityMarketOnCutinManagerPage(Context context){
		Intent intent = buildMarketIntent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	/**
	 * カットインマネージャーからアプリが起動したかを判定します。
	 */
	public static boolean isCalledFromCutinManager(Intent intent){
		if(intent == null) return false;
		String action = intent.getAction();
		if(action == null) return false;

		if(action.equals(ACTION_PICK_CUTIN)){
			return true;
		}
		else {
			return false;
		}
	}

}