text:
package amazon

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"expvar"
	"fmt"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"net/url"
	"sync"

	"github.com/asjoyner/shade"
	"github.com/asjoyner/shade/drive"
)

var (
	listFileReq = expvar.NewInt("amazonListFilesReq")
	getFileReq  = expvar.NewInt("amazonGetFileReq")
	putFileReq  = expvar.NewInt("amazonPutFileReq")
	getChunkReq = expvar.NewInt("amazonGetChunkReq")
	putChunkReq = expvar.NewInt("amazonPutChunkReq")
)

func init() {
	drive.RegisterProvider("amazon", NewClient)
}

type getFilesResponse struct {
	Count     int64
	NextToken string
	Data      []fileMetadata
}

type fileMetadata struct {
	ID           string
	Name         string
	ModifiedDate string
	CreatedDate  string
	Labels       []string
	Size         int64
	//Description  string
	//Status       string
	//ContentType  string
}

// NewClient returns an initialized Drive drive.Client object.
func NewClient(c drive.Config) (drive.Client, error) {
	client, err := getOAuthClient(c)
	if err != nil {
		return nil, err
	}
	ep, err := NewEndpoint(client) // endpoint.go
	if err != nil {
		return nil, err
	}
	return &Drive{
		client: client,
		ep:     ep,
		config: c,
		files:  make(map[string]string),
	}, nil
}

// Drive is a representation of the Amazon Cloud storage system.
type Drive struct {
	client *http.Client
	ep     *Endpoint
	config drive.Config
	// files maps from the string([]byte) representation of the file's SHA2 to
	// the corresponding fileID in Drive
	files map[string]string
	fm    sync.RWMutex // protects files
}

// ListFiles retrieves all of the File objects known to the client, and returns
// the corresponding sha256sum of the file object.  Those may be passed to
// GetFile() to retrieve the corresponding shade.File.
func (s *Drive) ListFiles() ([][]byte, error) {
	listFileReq.Add(1)
	// a list mapping the ID(s) of the shade.File(s) in Drive to sha256sum
	filters := "kind:FILE AND labels:shadeFile"
	if s.config.FileParentID != "" {
		filters += " AND parents:s.config.FileParentID"
	}

	v := url.Values{}
	v.Set("filters", filters)
	// TODO(asjoyner): sort modifiedDate:DESC and stop on last seen time?
	//v.Set("sort", `["modifiedDate DESC"]`)

	var nextToken string
	for {
		if nextToken != "" {
			v.Set("startToken", nextToken)
		}
		gfResp, err := s.getMetadata(v)
		if err != nil {
			return nil, err
		}

		s.fm.Lock()
		for _, f := range gfResp.Data {
			b, err := hex.DecodeString(f.Name)
			if err != nil {
				log.Printf("Shade file %q with invalid hex in filename: %s\n", f.Name, err)
			}
			s.files[string(b)] = f.ID
		}
		s.fm.Unlock()
		if gfResp.NextToken == "" {
			break
		}
		nextToken = gfResp.NextToken
	}

	s.fm.RLock()
	defer s.fm.RUnlock()
	resp := make([][]byte, 0, len(s.files))
	for sha256sum := range s.files {
		resp = append(resp, []byte(sha256sum))
	}
	return resp, nil
}

// GetFile retrieves a file by sha256sum, as returned by ListFiles().
// f should be marshalled JSON, and may be encrypted.
func (s *Drive) GetFile(sha256sum []byte) ([]byte, error) {
	getFileReq.Add(1)
	return s.GetChunk(sha256sum, nil)
}

// PutFile writes the manifest describing a new file.
// f should be marshalled JSON, and may be encrypted.
func (s *Drive) PutFile(sha256sum, contents []byte) error {
	putFileReq.Add(1)
	filename := hex.EncodeToString(sha256sum)
	metadata := map[string]interface{}{
		"kind":   "FILE",
		"name":   filename,
		"labels": []string{"shadeFile"},
		// "properties": ... shade version id?
	}
	if s.config.FileParentID != "" {
		metadata["parents"] = s.config.FileParentID
	}
	if err := s.uploadFile(filename, contents, metadata); err != nil {
		return err
	}
	return nil
}

// ReleaseFile removes a file.
func (s *Drive) ReleaseFile(sha256sum []byte) error {
	// TODO: bother to implement this.
	return nil
}

// GetChunk retrieves a chunk with a given SHA-256 sum.
// It first gets the ID of the chunk with the named sha256sum, possibly from a
// cache.  If then fetches the contents of the chunk from Drive.
//
// The cache is especially helpful for shade.File objects, which are
// efficiently looked up on each call of ListFiles.
func (s *Drive) GetChunk(sha256sum []byte, f *shade.File) ([]byte, error) {
	getChunkReq.Add(1)
	s.fm.RLock()
	fileID, ok := s.files[string(sha256sum)]
	s.fm.RUnlock()

	if !ok { // we have to lookup this fileID
		filters := fmt.Sprintf("kind:FILE AND labels:shadeChunk AND name:%x", sha256sum)
		v := url.Values{}
		v.Set("filters", filters)

		gfResp, err := s.getMetadata(v)
		if err != nil {
			return nil, err
		}

		if len(gfResp.Data) > 1 {
			return nil, fmt.Errorf("More than one file with SHA sum: %x", sha256sum)
		}
		fileID = gfResp.Data[0].ID
	}

	// Get the contents of the fileIDs.
	c, err := s.getFileContents(fileID)
	if err != nil {
		return nil, err
	}

	return c, nil
}

// PutChunk writes a chunk and returns its SHA-256 sum
func (s *Drive) PutChunk(sha256sum []byte, chunk []byte, f *shade.File) error {
	putChunkReq.Add(1)
	s.fm.RLock()
	_, ok := s.files[string(sha256sum)]
	s.fm.RUnlock()
	if ok {
		return nil // we know this chunk already exists
	}

	filename := hex.EncodeToString(sha256sum)
	metadata := map[string]interface{}{
		"kind":   "FILE",
		"name":   filename,
		"labels": []string{"shadeChunk"},
		// "properties": ... shade version id?  manifest back reference?
	}
	if s.config.ChunkParentID != "" {
		metadata["parents"] = s.config.ChunkParentID
	}
	if err := s.uploadFile(filename, chunk, metadata); err != nil {
		return err
	}
	return nil
}

// ReleaseChunk removes a chunk file.
func (s *Drive) ReleaseChunk(sha256sum []byte) error {
	// TODO: bother to implement this.
	return nil
}

// Warm would be a useful optimization here...
func (s *Drive) Warm(chunks [][]byte, f *shade.File) {
	return
}

// GetConfig returns the Drive's associated Config object.
func (s *Drive) GetConfig() drive.Config {
	return s.config
}

// Local returns whether the storage is local to this machine.
func (s *Drive) Local() bool { return false }

// Persistent returns whether the storage is persistent across task restarts.
func (s *Drive) Persistent() bool { return true }

// NewChunkLister returns an iterator which returns all chunks in Drive.
func (s *Drive) NewChunkLister() drive.ChunkLister {
	filters := "kind:FILE AND labels:shadeChunk"
	if s.config.FileParentID != "" {
		filters += " AND parents:s.config.FileParentID"
	}

	v := url.Values{}
	v.Set("filters", filters)

	c := &ChunkLister{s: s, values: v, sums: make([][]byte, 0)}
	c.err = c.fetchNextChunkSums()
	return c
}

// ChunkLister allows iterating the chunks in the Drive.
type ChunkLister struct {
	s         *Drive
	values    url.Values
	sums      [][]byte
	ptr       int
	nextToken string
	err       error
}

// Next increments the pointer
func (c *ChunkLister) Next() bool {
	if c.ptr == len(c.sums) {
		if c.nextToken == "" {
			return false // we have reached the end
		}
		if c.err = c.fetchNextChunkSums(); c.err != nil {
			return false // there was an error along the way
		}
		c.ptr = 0 // time to iterate a new set!
		return true
	}
	c.ptr++ // just one more step along the way
	return true
}

// Sha256 returns the chunk pointed to by the pointer.
func (c *ChunkLister) Sha256() []byte {
	if c.ptr > len(c.sums) {
		return nil
	}
	return c.sums[c.ptr-1]
}

// Err returns any error, if it is encountered.
func (c *ChunkLister) Err() error {
	return c.err
}

func (c *ChunkLister) fetchNextChunkSums() error {
	if c.nextToken != "" {
		c.values.Set("startToken", c.nextToken)
	}
	gfResp, err := c.s.getMetadata(c.values)
	if err != nil {
		return err
	}

	for _, f := range gfResp.Data {
		b, err := hex.DecodeString(f.Name)
		if err != nil {
			log.Printf("Shade file %q with invalid hex in filename: %s\n", f.Name, err)
		}
		c.sums = append(c.sums, b)
	}
	c.nextToken = gfResp.NextToken
	return nil
}

// uploadFile pushes the file with the associated metadata describing it
func (s *Drive) uploadFile(filename string, chunk []byte, metadata interface{}) error {
	body, ctype, err := mimeEncode(filename, chunk, metadata)
	if err != nil {
		return err
	}
	url := s.ep.ContentURL() + "nodes"
	req, err := http.NewRequest("POST", url, body)
	if err != nil {
		return err
	}
	req.Header.Add("Content-Type", ctype)
	resp, err := s.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode == 409 {
		// "409 Conflict" indicates the file already exists at this path with this
		// name.  Thus, we do not consider this an error.
		return nil
	} else if resp.StatusCode != 201 {
		buf := new(bytes.Buffer)
		buf.ReadFrom(resp.Body)
		return fmt.Errorf("upload failed: %s: %s", resp.Status, buf.String())
	}
	return nil
}

// mimeEncode creates multipart MIME body text for a file upload
//
// filename and data describe the file to be uploaded, metadata is a set of
// key/value pairs to be associated with the file.
//
// It returns the body as an io.Writer and the matching content-type header, or
// an error.  content-type has to be calculated by the multipart.Writer object
// because it contains the magic string "border" which separates mime parts.
//
// For format details, see the sample request here:
// https://developer.amazon.com/public/apis/experience/cloud-drive/content/nodes
func mimeEncode(filename string, data []byte, metadata interface{}) (io.Reader, string, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	// Order matters: metadata must come before content in the MIME content
	m, err := json.Marshal(metadata)
	if err != nil {
		return nil, "", err
	}
	_ = writer.WriteField("metadata", string(m))

	part, err := writer.CreateFormFile("content", filename)
	if err != nil {
		return nil, "", err
	}
	if _, err := part.Write(data); err != nil {
		return nil, "", err
	}

	err = writer.Close()
	if err != nil {
		return nil, "", err
	}
	ctype := writer.FormDataContentType()
	return body, ctype, err
}

// getMetadata retrieves the metadata of at most 200 shade.File(s) stored
// in Drive, unmarshals the JSON and returns them.  Use NextToken to
// request the next set of responses.
func (s *Drive) getMetadata(v url.Values) (getFilesResponse, error) {
	// URL from docs here:
	// https://developer.amazon.com/public/apis/experience/cloud-drive/content/nodes
	req := fmt.Sprintf("%s/nodes?%s", s.ep.MetadataURL(), v.Encode())
	resp, err := s.client.Get(req)
	if err != nil {
		return getFilesResponse{}, err
	}
	defer resp.Body.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)
	if resp.StatusCode != 200 {
		return getFilesResponse{}, fmt.Errorf("%s: %s", resp.Status, buf.String())
	}

	// Unmarshal the Amazon metadata about our file object
	var gfResp getFilesResponse
	if err := json.Unmarshal(buf.Bytes(), &gfResp); err != nil {
		return getFilesResponse{}, fmt.Errorf("json unmarshal error: %s", err)
	}
	return gfResp, nil
}

// getFileContents downloads the contents of a given file ID from Drive
// Documentation on the download URL and parameters are here:
// https://developer.amazon.com/public/apis/experience/cloud-drive/content/nodes
func (s *Drive) getFileContents(id string) ([]byte, error) {
	url := fmt.Sprintf("%snodes/%s/content", s.ep.ContentURL(), id)
	resp, err := s.client.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)
	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("%s: %s", resp.Status, buf.String())
	}
	return buf.Bytes(), nil
}


text:
module Spree
  class Address < Spree::Base
    require 'twitter_cldr'

    belongs_to :country, class_name: "Spree::Country"
    belongs_to :state, class_name: "Spree::State"

    has_many :shipments, inverse_of: :address

    with_options presence: true do
      validates :firstname, :lastname, :address1, :city, :country
      validates :zipcode, if: :require_zipcode?
      validates :phone, if: :require_phone?
    end

    validate :state_validate, :postal_code_validate

    alias_attribute :first_name, :firstname
    alias_attribute :last_name, :lastname

    self.whitelisted_ransackable_attributes = %w[firstname lastname company]

    def self.build_default
      country = Spree::Country.find(Spree::Config[:default_country_id]) rescue Spree::Country.first
      new(country: country)
    end

    def self.default(user = nil, kind = "bill")
      if user && user_address = user.public_send(:"#{kind}_address")
        user_address.clone
      else
        build_default
      end
    end

    # Can modify an address if it's not been used in an order (but checkouts controller has finer control)
    # def editable?
    #   new_record? || (shipments.empty? && checkouts.empty?)
    # end

    def full_name
      "#{firstname} #{lastname}".strip
    end

    def state_text
      state.try(:abbr) || state.try(:name) || state_name
    end

    def same_as?(other)
      return false if other.nil?
      attributes.except('id', 'updated_at', 'created_at') == other.attributes.except('id', 'updated_at', 'created_at')
    end

    alias same_as same_as?

    def to_s
      "#{full_name}: #{address1}"
    end

    def clone
      self.class.new(self.attributes.except('id', 'updated_at', 'created_at'))
    end

    def ==(other_address)
      self_attrs = self.attributes
      other_attrs = other_address.respond_to?(:attributes) ? other_address.attributes : {}

      [self_attrs, other_attrs].each { |attrs| attrs.except!('id', 'created_at', 'updated_at') }

      self_attrs == other_attrs
    end

    def empty?
      attributes.except('id', 'created_at', 'updated_at', 'country_id').all? { |_, v| v.nil? }
    end

    # Generates an ActiveMerchant compatible address hash
    def active_merchant_hash
      {
        name: full_name,
        address1: address1,
        address2: address2,
        city: city,
        state: state_text,
        zip: zipcode,
        country: country.try(:iso),
        phone: phone
      }
    end

    def require_phone?
      true
    end

    def require_zipcode?
      true
    end

    private
      def state_validate
        # Skip state validation without country (also required)
        # or when disabled by preference
        return if country.blank? || !Spree::Config[:address_requires_state]
        return unless country.states_required

        # ensure associated state belongs to country
        if state.present?
          if state.country == country
            self.state_name = nil #not required as we have a valid state and country combo
          else
            if state_name.present?
              self.state = nil
            else
              errors.add(:state, :invalid)
            end
          end
        end

        # ensure state_name belongs to country without states, or that it matches a predefined state name/abbr
        if state_name.present?
          if country.states.present?
            states = country.states.find_all_by_name_or_abbr(state_name)

            if states.size == 1
              self.state = states.first
              self.state_name = nil
            else
              errors.add(:state, :invalid)
            end
          end
        end

        # ensure at least one state field is populated
        errors.add :state, :blank if state.blank? && state_name.blank?
      end

      def postal_code_validate
        return if country.blank? || country.iso.blank? || !require_zipcode?
        return if !TwitterCldr::Shared::PostalCodes.territories.include?(country.iso.downcase.to_sym)

        postal_code = TwitterCldr::Shared::PostalCodes.for_territory(country.iso)
        errors.add(:zipcode, :invalid) if !postal_code.valid?(zipcode.to_s.strip)
      end
  end
end

redpajama_set_name: RedPajamaGithub


text:
//
// viztool - a tool for visualizing collections of java classes
// Copyright (c) 2001-2013, Michael Bayne - All rights reserved.
// http://github.com/samskivert/viztool/blob/master/LICENSE

package com.samskivert.viztool.layout;

import java.awt.geom.Rectangle2D;
import java.util.List;

/**
 * The element layout is used to lay a collection of elements out on a
 * page. It computes the desired position of each element and sets it via
 * setBounds() with the expectation that the location of the
 * elements will be used later in the rendering process.
 */
public interface ElementLayout
{
    /**
     * Lay out the supplied list of elements. Any elements that do not fit
     * into the allotted space should be added to the overflow list. The
     * supplied elements list should not be modified.
     *
     * @return the bounding dimensions of the collection of elements that
     * were laid out.
     */
    public <E extends Element> Rectangle2D layout (
        List<E> elements, double pageWidth, double pageHeight, List<E> overflow);
}


text:
/*
 * User: anna
 * Date: 25-Jan-2008
 */
package com.intellij.codeEditor.printing;

import java.util.Map;
import java.util.TreeMap;

import javax.swing.JCheckBox;
import javax.swing.JComponent;

import javax.annotation.Nonnull;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.UnnamedConfigurable;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.PsiReference;

public class HyperlinksToClassesOption extends PrintOption {
  private JCheckBox myCbGenerateHyperlinksToClasses;
  private boolean isGenerateHyperlinksToClasses = false;

  @javax.annotation.Nullable
  public TreeMap<Integer, PsiReference> collectReferences(PsiFile psiFile, Map<PsiFile, PsiFile> filesMap) {
    if (isGenerateHyperlinksToClasses) {
      FileType fileType = psiFile.getFileType();
      if (JavaFileType.INSTANCE == fileType /*|| StdFileTypes.JSP == fileType*/) {
        final TreeMap<Integer, PsiReference> refMap = new TreeMap<Integer, PsiReference>();
        findClassReferences(psiFile, refMap, filesMap, psiFile);
        return refMap;
      }
    }
    return null;
  }

  @Nonnull
  @Override
  public UnnamedConfigurable createConfigurable() {
    return new HyperlinksToClassesConfigurable();
  }

  private static void findClassReferences(PsiElement psiElement, TreeMap<Integer, PsiReference> refMap, Map<PsiFile, PsiFile> filesMap, PsiFile psiFile) {
    PsiReference ref = psiElement.getReference();
    if(ref instanceof PsiJavaCodeReferenceElement) {
      PsiElement refElement = ref.resolve();
      if(refElement instanceof PsiClass) {
        PsiFile containingFile = refElement.getContainingFile();
        if(!containingFile.equals(psiFile) && filesMap.get(containingFile) != null) {
          refMap.put(psiElement.getTextRange().getStartOffset(), ref);
        }
        return;
      }
    }
    PsiElement[] children = psiElement.getChildren();
    for (PsiElement aChildren : children) {
      findClassReferences(aChildren, refMap, filesMap, psiFile);
    }
  }

  private class HyperlinksToClassesConfigurable implements UnnamedConfigurable {
    public JComponent createComponent() {
      myCbGenerateHyperlinksToClasses = new JCheckBox(CodeEditorBundle.message("export.to.html.generate.hyperlinks.checkbox"), isGenerateHyperlinksToClasses);
      return myCbGenerateHyperlinksToClasses;
    }

    public boolean isModified() {
      return myCbGenerateHyperlinksToClasses.isSelected() != isGenerateHyperlinksToClasses;
    }

    public void apply() throws ConfigurationException {
      isGenerateHyperlinksToClasses = myCbGenerateHyperlinksToClasses.isSelected();
    }

    public void reset() {
      myCbGenerateHyperlinksToClasses.setSelected(isGenerateHyperlinksToClasses);
    }

    public void disposeUIResources() {
    }
  }
}


text: export * from './accordion-example';


text:
package org.tanrabad.survey.repository;

import org.tanrabad.survey.domain.place.PlaceSubTypeRepository;
import org.tanrabad.survey.domain.place.PlaceSubTypeRepositoryException;
import org.tanrabad.survey.entity.lookup.PlaceSubType;

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

final class InMemoryPlaceSubTypeRepository implements PlaceSubTypeRepository {

    private static InMemoryPlaceSubTypeRepository instance;
    private List<PlaceSubType> placeSubTypes;

    private InMemoryPlaceSubTypeRepository() {
        placeSubTypes = new ArrayList<>();
    }

    public static InMemoryPlaceSubTypeRepository getInstance() {
        if (instance == null)
            instance = new InMemoryPlaceSubTypeRepository();
        return instance;
    }

    @Override
    public List<PlaceSubType> find() {
        return placeSubTypes;
    }

    @Override
    public PlaceSubType findById(int placeSubTypeId) {
        for (PlaceSubType placeSubType : placeSubTypes) {
            if (placeSubType.getId() == placeSubTypeId)
                return placeSubType;
        }
        return null;
    }

    @Override
    public List<PlaceSubType> findByPlaceTypeId(int placeTypeId) {
        ArrayList<PlaceSubType> queryPlaceSubType = new ArrayList<>();
        for (PlaceSubType placeSubType : placeSubTypes) {
            if (placeSubType.getPlaceTypeId() == placeTypeId)
                queryPlaceSubType.add(placeSubType);
        }
        return queryPlaceSubType;
    }

    @Override
    public int getDefaultPlaceSubTypeId(int placeId) {
        for (PlaceSubType placeSubType : placeSubTypes) {
            if (placeSubType.getPlaceTypeId() == placeId)
                return placeSubType.getId();
        }
        return -1;
    }

    @Override
    public void updateOrInsert(List<PlaceSubType> updateList) {
        for (PlaceSubType placeSubType : updateList) {
            try {
                update(placeSubType);
            } catch (PlaceSubTypeRepositoryException pre) {
                save(placeSubType);
            }
        }
    }

    public boolean save(PlaceSubType placeSubType) {
        if (placeSubTypes.contains(placeSubType)) {
            throw new PlaceSubTypeRepositoryException();
        } else {
            placeSubTypes.add(placeSubType);
        }
        return true;
    }

    public boolean update(PlaceSubType placeSubType) {
        if (!placeSubTypes.contains(placeSubType)) {
            throw new PlaceSubTypeRepositoryException();
        } else {
            placeSubTypes.set(placeSubTypes.indexOf(placeSubType), placeSubType);
        }
        return true;
    }

    @Override
    public boolean delete(PlaceSubType placeSubType) {
        if (!placeSubTypes.contains(placeSubType)) {
            throw new PlaceSubTypeRepositoryException();
        }
        placeSubTypes.remove(placeSubType);
        return true;
    }
}


text:
from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, TextAreaField, IntegerField,DecimalField,HiddenField, SelectField
#from wtforms_components  import read_only
from wtforms.ext.dateutil.fields import DateField, DateTimeField
from wtforms.validators import Required, Length
from flask.ext.babel import gettext
from app.models import User

class EnvelopeForm(Form):
    id = HiddenField('id')
    description = TextField('description',validators = [Required()])
    start_date = DateField('start_date', validators = [Required()], display_format='%m-%d-%Y')
    end_date = DateField('end_date', validators = [Required()], display_format='%m-%d-%Y')
    amount = DecimalField('amount',  places=2)
    currency = TextField('currency')
    status = TextField('status')

    def __init__(self,   *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

    def validate(self):
	if not Form.validate(self):
            return False
        return True

class EnvelopeHoldersForm(Form):
    someone = TextField('someone',validators = [Required()])

class EnvelopeListForm(Form):
    search = TextField('search',validators = [Required()])
    def __init__(self,   *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

    def validate(self):
	if not Form.validate(self):
            return False
        return True


text:
package org.apache.druid.data.input.impl;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.primitives.Ints;
import org.apache.commons.lang.StringUtils;
import org.apache.druid.data.input.AbstractInputSource;
import org.apache.druid.data.input.InputEntity;
import org.apache.druid.data.input.InputFormat;
import org.apache.druid.data.input.InputRowSchema;
import org.apache.druid.data.input.InputSourceReader;
import org.apache.druid.data.input.InputSplit;
import org.apache.druid.data.input.SplitHintSpec;
import org.apache.druid.utils.CollectionUtils;

import javax.annotation.Nullable;
import java.io.File;
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

public abstract class CloudObjectInputSource extends AbstractInputSource
    implements SplittableInputSource<List<CloudObjectLocation>>
{
  private final String scheme;
  private final List<URI> uris;
  private final List<URI> prefixes;
  private final List<CloudObjectLocation> objects;
  private final String objectGlob;

  public CloudObjectInputSource(
      String scheme,
      @Nullable List<URI> uris,
      @Nullable List<URI> prefixes,
      @Nullable List<CloudObjectLocation> objects
  )
  {
    this.scheme = scheme;
    this.uris = uris;
    this.prefixes = prefixes;
    this.objects = objects;
    this.objectGlob = null;

    illegalArgsChecker();
  }

  public CloudObjectInputSource(
      String scheme,
      @Nullable List<URI> uris,
      @Nullable List<URI> prefixes,
      @Nullable List<CloudObjectLocation> objects,
      @Nullable String objectGlob
  )
  {
    this.scheme = scheme;
    this.uris = uris;
    this.prefixes = prefixes;
    this.objects = objects;
    this.objectGlob = objectGlob;

    illegalArgsChecker();
  }

  @JsonProperty
  @JsonInclude(JsonInclude.Include.NON_NULL)
  public List<URI> getUris()
  {
    return uris;
  }

  @JsonProperty
  @JsonInclude(JsonInclude.Include.NON_NULL)
  public List<URI> getPrefixes()
  {
    return prefixes;
  }

  @Nullable
  @JsonProperty
  @JsonInclude(JsonInclude.Include.NON_NULL)
  public List<CloudObjectLocation> getObjects()
  {
    return objects;
  }

  @Nullable
  @JsonProperty
  @JsonInclude(JsonInclude.Include.NON_NULL)
  public String getObjectGlob()
  {
    return objectGlob;
  }

  /**
   * Create the correct {@link InputEntity} for this input source given a split on a {@link CloudObjectLocation}. This
   * is called internally by {@link #formattableReader} and operates on the output of {@link #createSplits}.
   */
  protected abstract InputEntity createEntity(CloudObjectLocation location);

  /**
   * Create a stream of {@link CloudObjectLocation} splits by listing objects that appear under {@link #prefixes} using
   * this input sources backend API. This is called internally by {@link #createSplits} and {@link #estimateNumSplits},
   * only if {@link #prefixes} is set, otherwise the splits are created directly from {@link #uris} or {@link #objects}.
   * Calling if {@link #prefixes} is not set is likely to either lead to an empty iterator or null pointer exception.
   *
   * If {@link #objectGlob} is set, the objectGlob will be applied on {@link #uris} or {@link #objects}.
   * {@link #objectGlob} uses a glob notation, for example: "**.parquet".
   */
  protected abstract Stream<InputSplit<List<CloudObjectLocation>>> getPrefixesSplitStream(SplitHintSpec splitHintSpec);

  @Override
  public Stream<InputSplit<List<CloudObjectLocation>>> createSplits(
      InputFormat inputFormat,
      @Nullable SplitHintSpec splitHintSpec
  )
  {
    if (!CollectionUtils.isNullOrEmpty(objects)) {
      Stream<CloudObjectLocation> objectStream = objects.stream();

      if (StringUtils.isNotBlank(objectGlob)) {
        PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:" + getObjectGlob());
        objectStream = objectStream.filter(object -> m.matches(Paths.get(object.getPath())));
      }

      return objectStream.map(object -> new InputSplit<>(Collections.singletonList(object)));
    }

    if (!CollectionUtils.isNullOrEmpty(uris)) {
      Stream<URI> uriStream = uris.stream();

      if (StringUtils.isNotBlank(objectGlob)) {
        PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:" + getObjectGlob());
        uriStream = uriStream.filter(uri -> m.matches(Paths.get(uri.toString())));
      }

      return uriStream.map(CloudObjectLocation::new).map(object -> new InputSplit<>(Collections.singletonList(object)));
    }

    return getPrefixesSplitStream(getSplitHintSpecOrDefault(splitHintSpec));
  }

  @Override
  public int estimateNumSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec)
  {
    if (!CollectionUtils.isNullOrEmpty(objects)) {
      return objects.size();
    }

    if (!CollectionUtils.isNullOrEmpty(uris)) {
      return uris.size();
    }

    return Ints.checkedCast(getPrefixesSplitStream(getSplitHintSpecOrDefault(splitHintSpec)).count());
  }

  @Override
  public boolean needsFormat()
  {
    return true;
  }

  @Override
  protected InputSourceReader formattableReader(
      InputRowSchema inputRowSchema,
      InputFormat inputFormat,
      @Nullable File temporaryDirectory
  )
  {
    return new InputEntityIteratingReader(
        inputRowSchema,
        inputFormat,
        createSplits(inputFormat, null).flatMap(split -> split.get().stream()).map(this::createEntity).iterator(),
        temporaryDirectory
    );
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CloudObjectInputSource that = (CloudObjectInputSource) o;
    return Objects.equals(scheme, that.scheme) &&
           Objects.equals(uris, that.uris) &&
           Objects.equals(prefixes, that.prefixes) &&
           Objects.equals(objects, that.objects) &&
           Objects.equals(objectGlob, that.objectGlob);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(scheme, uris, prefixes, objects, objectGlob);
  }

  private void illegalArgsChecker() throws IllegalArgumentException
  {
    if (!CollectionUtils.isNullOrEmpty(objects)) {
      throwIfIllegalArgs(!CollectionUtils.isNullOrEmpty(uris) || !CollectionUtils.isNullOrEmpty(prefixes));
    } else if (!CollectionUtils.isNullOrEmpty(uris)) {
      throwIfIllegalArgs(!CollectionUtils.isNullOrEmpty(prefixes));
      uris.forEach(uri -> CloudObjectLocation.validateUriScheme(scheme, uri));
    } else if (!CollectionUtils.isNullOrEmpty(prefixes)) {
      prefixes.forEach(uri -> CloudObjectLocation.validateUriScheme(scheme, uri));
    } else {
      throwIfIllegalArgs(true);
    }
  }

  private void throwIfIllegalArgs(boolean clause) throws IllegalArgumentException
  {
    if (clause) {
      throw new IllegalArgumentException("exactly one of either uris or prefixes or objects must be specified");
    }
  }
}


text:
require 'spec_helper'
require 'heroku-scaler/web_scale'

module HerokuScaler
  class TestConfig
    def app_name
      "bonanza"
    end

    def big_dyno_type
      "big-boy"
    end

    def big_dyno_count
      99
    end

    def small_dyno_type
      "small-boy"
    end

    def small_dyno_count
      9
    end

    def auth_token
      "some-token"
    end
  end

  class TestPlatformAPI
    def self.connect_oauth(token)
      TestHeroku.new
    end
  end

  class TestHeroku
    def formation
      TestFormation.new
    end
  end

  class TestFormation
    def update(app, type, hash)
    end
  end

  describe WebScale do
    let(:platform_api) { TestPlatformAPI }
    let(:scaler) { HerokuScaler::WebScale.new(TestConfig.new, platform_api) }

    describe "#up!" do
      it "calls update" do
        expect_any_instance_of(TestFormation).to receive(:update).with(
          "bonanza",
          "web",
          {
            size: "big-boy",
            quantity: 99
          }
        )
        scaler.up!
      end
    end

    describe "#down!" do
      it "calls update" do
        expect_any_instance_of(TestFormation).to receive(:update).with(
          "bonanza",
          "web",
          {
            size: "small-boy",
            quantity: 9
          }
        )
        scaler.down!
      end
    end
  end
end


text:
void CarbonMutexInit(carbon_mutex_t* mux)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_MUTEX_INIT << mux;
   emulateRoutine(routine_info);
}

void __CarbonMutexInit(UInt64 time, core_id_t core_id, carbon_mutex_t* mux)
{
   Sim()->getSyncManager()->mutexInit(time, core_id, mux);
}

void CarbonMutexLock(carbon_mutex_t *mux)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_MUTEX_LOCK << mux;
   emulateRoutine(routine_info);
}

void __CarbonMutexLock(UInt64 time, core_id_t core_id, carbon_mutex_t* mux)
{
   Sim()->getSyncManager()->mutexLock(time, core_id, mux);
}

void CarbonMutexUnlock(carbon_mutex_t *mux)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_MUTEX_UNLOCK << mux;
   emulateRoutine(routine_info);
}

void __CarbonMutexUnlock(UInt64 time, core_id_t core_id, carbon_mutex_t* mux)
{
   Sim()->getSyncManager()->mutexUnlock(time, core_id, mux);
}

void CarbonCondInit(carbon_cond_t* cond)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_COND_INIT << cond;
   emulateRoutine(routine_info);
}

void __CarbonCondInit(UInt64 time, core_id_t core_id, carbon_cond_t* cond)
{
   Sim()->getSyncManager()->condInit(time, core_id, cond);
}

void CarbonCondWait(carbon_cond_t* cond, carbon_mutex_t* mux)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_COND_WAIT << cond << mux;
   emulateRoutine(routine_info);
}

void __CarbonCondWait(UInt64 time, core_id_t core_id, carbon_cond_t* cond, carbon_mutex_t* mux)
{
   Sim()->getSyncManager()->condWait(time, core_id, cond, mux);
}

void CarbonCondSignal(carbon_cond_t* cond)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_COND_SIGNAL << cond;
   emulateRoutine(routine_info);
}

void __CarbonCondSignal(UInt64 time, core_id_t core_id, carbon_cond_t* cond)
{
   Sim()->getSyncManager()->condSignal(time, core_id, cond);
}

void CarbonCondBroadcast(carbon_cond_t* cond)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_COND_BROADCAST << cond;
   emulateRoutine(routine_info);
}

void __CarbonCondBroadcast(UInt64 time, core_id_t core_id, carbon_cond_t* cond)
{
   Sim()->getSyncManager()->condBroadcast(time, core_id, cond);
}

void CarbonBarrierInit(carbon_barrier_t* barrier, UInt32 count)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_BARRIER_INIT << barrier << count;
   emulateRoutine(routine_info);
}

void __CarbonBarrierInit(UInt64 time, core_id_t core_id, carbon_barrier_t* barrier, UInt32 count)
{
   Sim()->getSyncManager()->barrierInit(time, core_id, barrier, count);
}

void CarbonBarrierWait(carbon_barrier_t* barrier)
{
   UnstructuredBuffer* routine_info = new UnstructuredBuffer();
   (*routine_info) << Routine::CARBON_BARRIER_WAIT << barrier;
   emulateRoutine(routine_info);
}

void __CarbonBarrierWait(UInt64 time, core_id_t core_id, carbon_barrier_t* barrier)
{
   Sim()->getSyncManager()->barrierWait(time, core_id, barrier);
}


text:
from os.path import abspath, dirname, join as pjoin
from sys import version_info
from setuptools import setup

here = abspath(dirname(__file__))

classifiers = (
    'Development Status :: 3 - Alpha',
    # 'Development Status :: 5 - Production/Stable',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.1',
    'Programming Language :: Python :: 3.2',
    'Programming Language :: Python :: 3.3',
    'Operating System :: POSIX :: Linux',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: BSD License',
)

console_scripts = [
    'python-module-launcher-{0.major}.{0.minor} = modulelauncher:main'\
    .format(version_info)]

kw = {
    'name'              : 'module-launcher',
    'version'           : '0.2.0',
    'description'       : 'Preforks interpreters to reduce script startup time',
    'long_description'  : open(pjoin(here, 'README.rst')).read(),
    'author'            : 'Georgi Valkov',
    'author_email'      : 'georgi.t.valkov@gmail.com',
    'license'           : 'Revised BSD License',
    'keywords'          : 'module launcher speedup prefork',
    'classifiers'       : classifiers,
    'url'               : 'https://github.com/gvalkov/python-module-launcher',
    'entry_points'      : {'console_scripts' : console_scripts},
    'py_modules'        : ['modulelauncher'],
    'install_requires'  : ['argparse==1.2.1', 'daemonize==2.2.1', 'lockfile==0.9.1'],
    'zip_safe'          : True,
}

if __name__ == '__main__':
    setup(**kw)


text:
Thanks for your interest in contributing to the Open Policy Agent (OPA) project!

# Where to start?

If you have questions, comments, or requests feel free to post on the mailing list or
create an issue on GitHub.

If you want to contribute code and you are new to the Go programming language, check out
the [DEVELOPMENT.md](./docs/devel/DEVELOPMENT.md) reference for help getting started.

We currently welcome contributions of all kinds. For example:

- Development of features, bug fixes, and other improvements.
- Documentation including reference material and examples.
- Bug and feature reports.

# Contribution process

Small bug fixes (or other small improvements) can be submitted directly via a Pull Request on GitHub.
You can expect at least one of the OPA maintainers to respond quickly.

Before submitting large changes, please open an issue on GitHub outlining:

- The use case that your changes are applicable to.
- Steps to reproduce the issue(s) if applicable.
- Detailed description of what your changes would entail.
- Alternative solutions or approaches if applicable.

Use your judgement about what constitutes a large change. If you aren't sure, send a message to the
OPA slack or submit an issue on GitHub.

## Code Contributions

If you are contributing code, please consider the following:

- Most changes should be accompanied with tests.
- Commit messages should explain *why* the changes were made and should probably look like this:

        Description of the change in 50 characters or less

        More detail on what was changed. Provide some background on the issue
        and describe how the changes address the issue. Feel free to use multiple
        paragraphs but please keep each line under 72 characters or so.

- Related commits must be squashed before they are merged.
- All tests must pass and there must be no warnings from the `make check` target.

## Code Review

Before a Pull Request is merged, it will undergo code review from other members
of the OPA community. In order to streamline the code review process, when
amending your Pull Request in response to a review, do not squash your changes
into relevant commits until it has been approved for merge. This allows the
reviewer to see what changes are new and removes the need to wade through code
that has not been modified to search for a small change.

When adding temporary patches in response to review comments, consider
formatting the message subject like one of the following:
- `Fixup into commit <commit ID> (squash before merge)`
- `Fixed changes requested by @username (squash before merge)`
- `Amended <description> (squash before merge)`

The purpose of these formats is to provide some context into the reason the
temporary commit exists, and to label it as needing squashed before a merge
is performed.

It is worth noting that not all changes need be squashed before a merge is
performed. Some changes made as a result of review stand well on their own,
independent of other commits in the series. Such changes should be made into
their own commit and added to the PR.

If your Pull Request is small though, it is acceptable to squash changes during
the review process. Use your judgement about what constitutes a small Pull
Request.  If you aren't sure, send a message to the OPA slack or post a comment
on the Pull Request.


text:
/*
 * This file is part of the Nice GLib ICE library.
 *
 * (C) 2006-2009 Collabora Ltd.
 *  Contact: Youness Alaoui
 * (C) 2006-2009 Nokia Corporation. All rights reserved.
 *  Contact: Kai Vehmanen
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Nice GLib ICE library.
 *
 * The Initial Developers of the Original Code are Collabora Ltd and Nokia
 * Corporation. All Rights Reserved.
 *
 * Contributors:
 *   Dafydd Harries, Collabora Ltd.
 *   Youness Alaoui, Collabora Ltd.
 *   Kai Vehmanen, Nokia
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * the GNU Lesser General Public License Version 2.1 (the "LGPL"), in which
 * case the provisions of LGPL are applicable instead of those above. If you
 * wish to allow use of your version of this file only under the terms of the
 * LGPL and not to allow others to use your version of this file under the
 * MPL, indicate your decision by deleting the provisions above and replace
 * them with the notice and other provisions required by the LGPL. If you do
 * not delete the provisions above, a recipient may use your version of this
 * file under either the MPL or the LGPL.
 */

/*
 * Porting to C library using libevent.
 * Jackie Dinh - 2016
 */

#include "cice/agent.h"
#include "cice/component.h"
#include "cice/network.h"

void
incoming_check_free(incoming_check_head_t *icheck)
{
   /* FIXME: incoming_check_free */
   /*free (icheck->username);
   g_slice_free (IncomingCheck, icheck);*/
}

component_t *
component_new (agent_t *agent, stream_t *stream, uint32_t id)
{
  component_t *component;

  ICE_DEBUG("created component, cid=%u", id);
  component = ICE_MALLOC(component_t);
  if (!component) return 0;
  ICE_MEMZERO(component,component_t);
  component->id = id;
  component->state = ICE_COMPONENT_STATE_DISCONNECTED;
  component->restart_candidate = 0;
  component->tcp = 0;
  component->agent = agent;
  component->stream = stream;
  TAILQ_INIT(&component->local_candidates);
  TAILQ_INIT(&component->remote_candidates);
  TAILQ_INIT(&component->incoming_checks);

  ice_agent_init_stun_agent(agent, &component->stun_agent);
  return component;
}

void
component_set_io_callback (component_t *component,
             agent_recv_func cb, void *user_data) {

  if ( component == 0 )
     return;

  component->io_callback = cb;
  component->io_data = user_data;

  return;
}

void
component_attach_socket (component_t *component, socket_t *nicesock)
{
  if (component == NULL || nicesock == NULL)
     return;

  /* FIXME Create and attach a source */
  //nicesock->component = component;

  return;
}

candidate_t *
component_find_remote_candidate(const component_t *component,
  const address_t *addr, IceCandidateTransport transport)
{
   candidate_t *candidate = NULL;

   TAILQ_FOREACH(candidate,&component->remote_candidates,list) {
      if ( address_equal(&candidate->addr,addr) &&
           candidate->transport == transport ) {
         return candidate;
      }
   }

  return NULL;
}

static void
component_clear_selected_pair (component_t *component)
{
   /* FIXME: clear timeout for selected pair */
  /*if (component->selected_pair.keepalive.tick_source != NULL) {
    g_source_destroy (component->selected_pair.keepalive.tick_source);
    g_source_unref (component->selected_pair.keepalive.tick_source);
    component->selected_pair.keepalive.tick_source = NULL;
  }*/
  memset(&component->selected_pair, 0, sizeof(candidate_pair_t));
}
/*
 * Changes the selected pair for the component to 'pair'. Does not
 * emit the "selected-pair-changed" signal.
 */
void
component_update_selected_pair (component_t *component, const candidate_pair_t *pair)
{
  if ( component == NULL || pair == NULL )
     return;

  ICE_DEBUG("setting SELECTED PAIR for component, "
            "cid=%u, lfoundation=%s, rfoundation=%s ,prio:%lu",
      component->id, pair->local->foundation,
      pair->remote->foundation, pair->priority);

  /* FIXME: clean socket resources */
  /*if (component->selected_pair.local &&
      component->selected_pair.local == component->turn_candidate) {
    refresh_prune_candidate(component->agent, component->turn_candidate);
    discovery_prune_socket(component->agent, component->turn_candidate->sockptr);
    conn_check_prune_socket (component->agent, component->stream, component,
        component->turn_candidate->sockptr);
    component_detach_socket (component, component->turn_candidate->sockptr);
    candidate_free (component->turn_candidate);
    component->turn_candidate = NULL;
  }*/

  component_clear_selected_pair(component);
  ICE_DEBUG("set selected pair, local=%p, remote=%p", pair->local, pair->remote);
  component->selected_pair.local = pair->local;
  component->selected_pair.remote = pair->remote;
  component->selected_pair.priority = pair->priority;

  return;
}

/*
 * Finds a candidate pair that has matching foundation ids.
 *
 * @return TRUE if pair found, pointer to pair stored at 'pair'
 */
int
component_find_pair(component_t *cmp, agent_t *agent, const char *lfoundation,
   const char *rfoundation, candidate_pair_t *pair)
{

  candidate_t *candidate = NULL;
  candidate_pair_t result = { 0, };

  TAILQ_FOREACH(candidate,&cmp->local_candidates,list) {
    if (strncmp(candidate->foundation, lfoundation, ICE_CANDIDATE_MAX_FOUNDATION) == 0) {
      result.local = candidate;
      break;
    }
  }

  TAILQ_FOREACH(candidate,&cmp->remote_candidates,list) {
    if (strncmp (candidate->foundation, rfoundation, ICE_CANDIDATE_MAX_FOUNDATION) == 0) {
      result.remote = candidate;
      break;
    }
  }

  if (result.local && result.remote) {
    result.priority = agent_candidate_pair_priority(agent, result.local, result.remote);
    if (pair)
      *pair = result;
    return ICE_OK;
  }

  return ICE_ERR;

}

candidate_t *
component_set_selected_remote_candidate(agent_t *agent,
       component_t *component, candidate_t *candidate)
{
  candidate_t *local = NULL;
  candidate_t *remote = NULL;
  uint64_t priority = 0;
  candidate_t *tmp = NULL;

  if (candidate == NULL)
     return NULL;

  TAILQ_FOREACH(tmp,&component->local_candidates,list) {
    uint64_t tmp_prio = 0;

    if (tmp->transport != candidate->transport ||
	tmp->addr.s.addr.sa_family != candidate->addr.s.addr.sa_family ||
        tmp->type != ICE_CANDIDATE_TYPE_HOST)
      continue;

    tmp_prio = agent_candidate_pair_priority (agent, tmp, candidate);
    ICE_DEBUG("computing priority, temp=%lu, prio=%lu",tmp_prio,priority);
    if (tmp_prio > priority) {
      priority = tmp_prio;
      local = tmp;
    }
  }

  if (local == NULL)
    return NULL;

  remote = component_find_remote_candidate(component, &candidate->addr,
      candidate->transport);

  ICE_DEBUG("got remote, remote=%p",remote);
  if (!remote) {
    remote = candidate_copy(candidate);
    TAILQ_INSERT_HEAD(&component->remote_candidates, remote, list);
    agent_signal_new_remote_candidate(agent, remote);
  }

  component_clear_selected_pair (component);

  ICE_DEBUG("set selected pair, prio=%lu",priority);
  component->selected_pair.local = local;
  component->selected_pair.remote = remote;
  component->selected_pair.priority = priority;

  return local;
}

void
ice_component_close(component_t *c) {
  agent_t *agent = (agent_t*)c->agent;
  candidate_t *candidate = NULL;
  socket_t *sock = 0;

  c->state = ICE_COMPONENT_STATE_DISCONNECTED;

  // free local candidates
  while (!TAILQ_EMPTY(&c->local_candidates)) {
    candidate = TAILQ_FIRST(&c->local_candidates);
    TAILQ_REMOVE(&c->local_candidates, candidate, list);
    candidate_free(candidate);
  }

  while (!TAILQ_EMPTY(&c->remote_candidates)) {
    candidate = TAILQ_FIRST(&c->remote_candidates);
    TAILQ_REMOVE(&c->remote_candidates, candidate, list);
    candidate_free(candidate);
  }
  sock = (socket_t*)c->sock;
  ICE_DEBUG("component close, fd=%d, sid=%u, cid=%u", sock->fd, c->stream->id, c->id);
  sock->agent = 0;
  sock->stream = 0;
  sock->component = 0;
  agent->base->destroy_socket(agent->base,sock);

  return;
}


text:
package net.webownia.applicationmgr;

import net.webownia.applicationmgr.data.model.ApplicationForm;
import net.webownia.applicationmgr.data.model.ApplicationFormAudit;
import net.webownia.applicationmgr.data.repository.ApplicationFormAuditRepository;
import net.webownia.applicationmgr.data.repository.ApplicationFormRepository;
import net.webownia.applicationmgr.exception.ApplicationFormChangingStatusException;
import net.webownia.applicationmgr.exception.ApplicationFormChangingStatusRuntimeException;
import net.webownia.applicationmgr.service.ApplicationFormService;
import net.webownia.applicationmgr.service.ApplicationFormServiceImpl;
import net.webownia.applicationmgr.shared.enums.ApplicationStatus;
import org.joda.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;

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

import static org.mockito.Mockito.*;

/**
 * Created by Adam Barczewski on 2014-12-04.
 */
@RunWith(MockitoJUnitRunner.class)
public class ApplicationFormServiceTest {

    private static final int PAGE_NUMBER = 3;
    private static final PageRequest REQUEST = new PageRequest(PAGE_NUMBER - 1, 10, Sort.Direction.ASC, "lastModifiedDate", "createdDate");
    private static final List<String> STATUS_COLLECTIONS = ApplicationStatus.statusCollectionForEnumSet(ApplicationStatus.allStatusCollection);
    private boolean updateTest = false;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Mock
    private ApplicationFormRepository applicationFormRepository;

    @Mock
    private ApplicationFormAuditRepository auditRepository;

    @Mock
    private Page<ApplicationForm> pageApplicationForms;

    @Mock
    private Page<ApplicationFormAudit> pageApplicationAuditForms;

    @InjectMocks
    private ApplicationFormService testee = new ApplicationFormServiceImpl();

    @Test
    public void shouldCreate() throws Exception {
        //WHEN
        testee.create("name", "content");

        //THEN
        verify(applicationFormRepository, times(1)).save(Matchers.any(ApplicationForm.class));
    }

    @Test
    public void shouldThrowWhenCreateTestCases() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent(null, null);
    }

    @Test
    public void shouldThrowWhenCreateTestCases1() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent("", "");
    }

    @Test
    public void shouldThrowWhenCreateTestCases2() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent(null, "");
    }

    @Test
    public void shouldThrowWhenCreateTestCases3() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent("", null);
    }

    @Test
    public void shouldThrowWhenCreateTestCases4() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent("xx", null);
    }

    @Test
    public void shouldThrowWhenCreateTestCases5() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent(null, "xx");
    }

    @Test
    public void shouldThrowWhenCreateTestCases6() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent("", "xx");
    }

    @Test
    public void shouldThrowWhenCreateTestCases7() throws Exception {
        shouldThrowRuntimeWithOutNameOrContent("xx", "");
    }

    @Test
    public void shouldVerify() throws Exception {
        shouldChangedForStatusAndAction(ApplicationStatus.CREATED, Action.VERIFY);
    }

    @Test
    public void shouldThrowWhenVerifyTestCases() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.VERIFIED, Action.VERIFY);
    }

    @Test
    public void shouldThrowWhenVerifyTestCases1() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.DELETED, Action.VERIFY);
    }

    @Test
    public void shouldThrowWhenVerifyTestCases2() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.REJECTED, Action.VERIFY);
    }

    @Test
    public void shouldThrowWhenVerifyTestCases3() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.ACCEPTED, Action.VERIFY);
    }

    @Test
    public void shouldThrowWhenVerifyTestCases4() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.PUBLISHED, Action.VERIFY);
    }

    @Test
    public void shouldDelete() throws Exception {
        shouldChangedForStatusAndAction(ApplicationStatus.CREATED, Action.DELETE);
    }

    @Test
    public void shouldThrowWhenDeleteTestCases() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.VERIFIED, Action.DELETE);
    }

    @Test
    public void shouldThrowWhenDeleteTestCases1() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.REJECTED, Action.DELETE);
    }

    @Test
    public void shouldThrowWhenDeleteTestCases2() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.ACCEPTED, Action.DELETE);
    }

    @Test
    public void shouldThrowWhenDeleteTestCases3() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.PUBLISHED, Action.DELETE);
    }

    @Test
    public void shouldThrowWhenDeleteTestCases4() throws Exception {
        shouldThrowRuntimeWithOutCause(ApplicationStatus.VERIFIED, Action.DELETE);
    }

    @Test
    public void shouldReject() throws Exception {
        shouldChangedForStatusAndAction(ApplicationStatus.VERIFIED, Action.REJECT);
    }

    @Test
    public void shouldThrowWhenRejectTestCases() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.CREATED, Action.REJECT);
    }

    @Test
    public void shouldThrowWhenRejectTestCases1() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.DELETED, Action.REJECT);
    }

    @Test
    public void shouldThrowWhenRejectTestCases2() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.REJECTED, Action.REJECT);
    }

    @Test
    public void shouldThrowWhenRejectTestCases3() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.PUBLISHED, Action.REJECT);
    }

    @Test
    public void shouldThrowWhenRejectTestCases4() throws Exception {
        shouldThrowRuntimeWithOutCause(ApplicationStatus.CREATED, Action.REJECT);
    }

    @Test
    public void shouldAccept() throws Exception {
        shouldChangedForStatusAndAction(ApplicationStatus.VERIFIED, Action.ACCEPT);
    }

    @Test
    public void shouldThrowWhenAcceptTestCases() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.ACCEPTED, Action.ACCEPT);
    }

    @Test
    public void shouldThrowWhenAcceptTestCases1() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.CREATED, Action.ACCEPT);
    }

    @Test
    public void shouldThrowWhenAcceptTestCases2() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.DELETED, Action.ACCEPT);
    }

    @Test
    public void shouldThrowWhenAcceptTestCases3() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.REJECTED, Action.ACCEPT);
    }

    @Test
    public void shouldThrowWhenAcceptTestCases4() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.PUBLISHED, Action.ACCEPT);
    }

    @Test
    public void shouldPublish() throws Exception {
        shouldChangedForStatusAndAction(ApplicationStatus.ACCEPTED, Action.PUBLISH);
    }

    @Test
    public void shouldThrowWhenPublishTestCases() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.PUBLISHED, Action.PUBLISH);
    }

    @Test
    public void shouldThrowWhenPublishTestCases1() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.VERIFIED, Action.PUBLISH);
    }

    @Test
    public void shouldThrowWhenPublishTestCases2() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.REJECTED, Action.PUBLISH);
    }

    @Test
    public void shouldThrowWhenPublishTestCases3() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.DELETED, Action.PUBLISH);
    }

    @Test
    public void shouldThrowWhenPublishTestCases4() throws Exception {
        shouldThrowForStatusAndAction(ApplicationStatus.CREATED, Action.PUBLISH);
    }

    @Test
    public void shouldFindApplicationsPageable() {
        //GIVEN
        when(applicationFormRepository.findAll(REQUEST)).thenReturn(pageApplicationForms);
        when(pageApplicationForms.getTotalElements()).thenReturn(10l);

        //WHEN
        long totalElements = testee.findAll(PAGE_NUMBER).getTotalElements();

        //THEN
        Assert.assertTrue(totalElements == 10L);
    }

    @Test
    public void shouldFindApplicationTestCases() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter(null, null);
    }

    @Test
    public void shouldFindApplicationTestCases1() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("", null);
    }

    @Test
    public void shouldFindApplicationTestCases2() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("xxx", null);
    }

    @Test
    public void shouldFindApplicationTestCases3() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter(null, new ArrayList<>(0));
    }

    @Test
    public void shouldFindApplicationTestCases4() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("", new ArrayList<>(0));
    }

    @Test
    public void shouldFindApplicationTestCases5() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("xxx", new ArrayList<>(0));
    }

    @Test
    public void shouldFindApplicationTestCases6() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter(null, STATUS_COLLECTIONS);
    }

    @Test
    public void shouldFindApplicationTestCases7() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("", STATUS_COLLECTIONS);
    }

    @Test
    public void shouldFindApplicationTestCases8() throws ApplicationFormChangingStatusException {
        shouldFindApplicationForFilter("xxx", STATUS_COLLECTIONS);
    }

    @Test
    public void shouldThrowRuntimeWhenFilteringPageWithWrongStatusCollections() throws ApplicationFormChangingStatusException {
        //GIVEN
        List<String> wrongStatusCollection = new ArrayList<>(1);
        wrongStatusCollection.add("WRONG_STATUS");

        thrown.expect(ApplicationFormChangingStatusRuntimeException.class);
        thrown.expectMessage("Wrong status collections.");

        //WHEN
        testee.findByNameOrStatusIn("xxx", wrongStatusCollection, PAGE_NUMBER);
    }

    @Test
    public void shouldFindAuditApplicationsPageable() {
        //GIVEN
        when(auditRepository.findByApplicationFormId(1l, REQUEST)).thenReturn(pageApplicationAuditForms);
        when(pageApplicationAuditForms.getTotalElements()).thenReturn(10l);

        //WHEN
        long totalElements = testee.findByApplicationFormId(1L, PAGE_NUMBER).getTotalElements();

        //THEN
        Assert.assertTrue(totalElements == 10L);
    }

    @Test
    public void shouldUpdate() {
        //GIVEN
        when(applicationFormRepository.findById(1)).thenReturn(getApplicationForm(ApplicationStatus.CREATED));

        //WHEN
        testee.update(1l, "new name", "new content");

        //THEN
        verify(applicationFormRepository, times(1)).findById(1);
        verify(applicationFormRepository, times(1)).save(Matchers.any(ApplicationForm.class));
    }

    @Test
    public void shouldThrowRuntimeWhenUpdateUnValidFieldTestCase() {
        updateTest = true;
        shouldThrowRuntimeWithOutNameOrContent(null, null);
        updateTest = false;
    }

    @Test
    public void shouldThrowRuntimeWhenUpdateUnValidFieldTestCase1() {
        updateTest = true;
        shouldThrowRuntimeWithOutNameOrContent("", "");
        updateTest = false;
    }

    @Test
    public void shouldThrowRuntimeWhenUpdateUnValidFieldTestCase2() {
        updateTest = true;
        shouldThrowRuntimeWithOutNameOrContent(null, "");
        updateTest = false;
    }

    @Test
    public void shouldThrowRuntimeWhenUpdateUnValidFieldTestCase3() {
        updateTest = true;
        shouldThrowRuntimeWithOutNameOrContent("", null);
        updateTest = false;
    }

    /**
     * dynamic method for assert find applications for filter
     *
     * @param name             - name application form
     * @param statusCollection - Collection<String>
     */
    private void shouldFindApplicationForFilter(String name, List<String> statusCollection) throws ApplicationFormChangingStatusException {
        //GIVEN
        EnumSet applicationStatuses = ApplicationStatus.enumSetForStatusCollection(statusCollection);
        boolean forStatus = false;
        if (applicationStatuses != null && ApplicationStatus.allStatusCollection.containsAll(applicationStatuses)) {
            forStatus = true;
        }
        if (name != null && !name.isEmpty() && forStatus) {
            //  for  shouldFindApplicationForFilter("xxx", STATUS_COLLECTIONS);
            when(applicationFormRepository.findByNameContainingAndStatusIn(name, applicationStatuses, REQUEST)).thenReturn(pageApplicationForms);
            check(name, statusCollection, 10);
        } else if ((name == null || name.isEmpty()) && (statusCollection == null || statusCollection.isEmpty())) {
            //  for  shouldFindApplicationForFilter(null, null);
            //  for  shouldFindApplicationForFilter("", new ArrayList<>(0));
            //  for  shouldFindApplicationForFilter(null, new ArrayList<>(0));
            //  for  shouldFindApplicationForFilter("", null);
            //WHEN
            Page<ApplicationForm> page = testee.findByNameOrStatusIn(name, statusCollection, PAGE_NUMBER);
            //THEN
            Assert.assertTrue(page == null);
        } else if (name != null && !name.isEmpty()) {
            //  for  shouldFindApplicationForFilter("xxx", new ArrayList<>(0));
            //  for  shouldFindApplicationForFilter("xxx", null);
            when(applicationFormRepository.findByNameContaining(name, REQUEST)).thenReturn(pageApplicationForms);
            check(name, statusCollection, 10);
        } else if (forStatus) {
            //  for  shouldFindApplicationForFilter("", STATUS_COLLECTIONS);
            //  for  shouldFindApplicationForFilter(null, STATUS_COLLECTIONS);
            when(applicationFormRepository.findByStatusIn(applicationStatuses, REQUEST)).thenReturn(pageApplicationForms);
            check(name, statusCollection, 10);
        }
    }

    private void check(String name, List<String> statusCollection, long total) throws ApplicationFormChangingStatusException {
        when(pageApplicationForms.getTotalElements()).thenReturn(total);
        //WHEN
        long totalElements = testee.findByNameOrStatusIn(name, statusCollection, PAGE_NUMBER).getTotalElements();
        //THEN
        Assert.assertTrue(totalElements == total);
    }

    /**
     * Dynamic method for success in run service action for changing status
     *
     * @param oldStatus - status before action
     * @param action    - name for service action
     * @throws Exception
     */
    private void shouldChangedForStatusAndAction(ApplicationStatus oldStatus, Action action) throws Exception {
        //GIVEN
        when(applicationFormRepository.findById(1)).thenReturn(getApplicationForm(oldStatus));

        //WHEN
        switch (action) {
            case REJECT:
                testee.reject(1, "Cause message...");
                break;
            case DELETE:
                testee.delete(1, "Cause message...");
                break;
            case VERIFY:
                testee.verify(1);
                break;
            case ACCEPT:
                testee.accept(1);
                break;
            case PUBLISH:
                testee.publish(1);
                break;
            default:
                break;
        }

        //THEN
        verify(applicationFormRepository, times(1)).findById(1);
        verify(applicationFormRepository, times(1)).save(Matchers.any(ApplicationForm.class));
        verify(auditRepository, times(1)).save(Matchers.any(ApplicationFormAudit.class));
    }

    /**
     * Expected ApplicationFormChangingStatusException
     *
     * @param oldStatus - status before action
     * @param action    - name for service action
     * @throws Exception
     */
    private void shouldThrowForStatusAndAction(ApplicationStatus oldStatus, Action action) throws Exception {
        //GIVEN
        when(applicationFormRepository.findById(1)).thenReturn(getApplicationForm(oldStatus));

        thrown.expect(ApplicationFormChangingStatusException.class);
        thrown.expectMessage("Can not changing status.");

        //WHEN
        switch (action) {
            case REJECT:
                testee.reject(1, "Cause message...");
                break;
            case DELETE:
                testee.delete(1, "Cause message...");
                break;
            case VERIFY:
                testee.verify(1);
                break;
            case ACCEPT:
                testee.accept(1);
                break;
            case PUBLISH:
                testee.publish(1);
                break;
            default:
                break;
        }
    }

    /**
     * Expected ApplicationFormChangingStatusRuntimeException for create service action
     *
     * @param name    - name application form
     * @param content - content application form
     * @throws ApplicationFormChangingStatusRuntimeException - java.lang.RuntimeException
     */
    private void shouldThrowRuntimeWithOutNameOrContent(String name, String content) throws ApplicationFormChangingStatusRuntimeException {
        thrown.expect(ApplicationFormChangingStatusRuntimeException.class);
        if ((content == null || content.isEmpty()) && (name == null || name.isEmpty())) {
            thrown.expectMessage("Name and content are required.");
        } else if (name == null || name.isEmpty()) {
            thrown.expectMessage("Name is required.");
        } else if (content == null || content.isEmpty()) {
            thrown.expectMessage("Content is required.");
        }

        if (updateTest) {
            testee.update(1l, name, content);
        } else {
            testee.create(name, content);
        }
    }

    /**
     * Expected ApplicationFormChangingStatusRuntimeException for delete or reject service action
     *
     * @param oldStatus - status before action
     * @param action    - name for service action
     * @throws Exception - java.lang.RuntimeException
     */
    private void shouldThrowRuntimeWithOutCause(ApplicationStatus oldStatus, Action action) throws Exception {
        //GIVEN
        when(applicationFormRepository.findById(1)).thenReturn(getApplicationForm(oldStatus));

        if (ApplicationStatus.CREATED.equals(oldStatus) && Action.REJECT.equals(action)) {
            thrown.expect(ApplicationFormChangingStatusException.class);
            thrown.expectMessage("Can not changing status.");
        } else if (ApplicationStatus.VERIFIED.equals(oldStatus) && Action.DELETE.equals(action)) {
            thrown.expect(ApplicationFormChangingStatusException.class);
            thrown.expectMessage("Can not changing status.");
        } else {
            thrown.expect(ApplicationFormChangingStatusRuntimeException.class);
            thrown.expectMessage("Cause is required.");
        }

        //WHEN
        switch (action) {
            case REJECT:
                testee.reject(1, null);
                break;
            case DELETE:
                testee.delete(1, null);
                break;
            default:
                break;
        }
    }

    private ApplicationForm getApplicationForm(ApplicationStatus oldStatus) {
        return new ApplicationForm("note", "contentMessage", oldStatus, LocalDateTime.now());
    }

    /**
     * Representation service actions
     */
    private enum Action {
        DELETE,
        VERIFY,
        REJECT,
        ACCEPT,
        PUBLISH
    }
}


text:
@class CHTTPServer;
@class CHTTPMessage;
@class CHTTPRequestHandler;

@interface CHTTPConnection : CWireProtocol {
	CHTTPServer *server; // Never retained.
	NSMutableArray *requestHandlers;
	CHTTPMessage *currentRequest;
}

@property (readonly, nonatomic, assign) CHTTPServer *server;
@property (readwrite, nonatomic, retain) NSMutableArray *requestHandlers;

- (id)initWithServer:(CHTTPServer *)inServer;

- (CHTTPMessage *)responseForRequest:(CHTTPMessage *)inRequest;
- (void)sendResponse:(CHTTPMessage *)inResponse;

@end


text:
**Note that this repo is now deprecated in favor of [Microsoft/cordova-simulate](https://github.com/microsoft/cordova-simulate)**

Server and app host support for cordova-simulate.

# Installation

```
npm install cordova-simulator-server
```


text:
/*
 * Source code generated by Celerio, a Jaxio product.
 * Documentation: http://www.jaxio.com/documentation/celerio/
 * Follow us on twitter: @jaxiosoft
 * Need commercial support ? Contact us: info@jaxio.com
 * Template angular-lab:springboot/src/main/java/rest/dto/LoggerDTO.p.vm.java
 */
package com.jaxio.demo.rest.dto;

import ch.qos.logback.classic.Logger;
import com.fasterxml.jackson.annotation.JsonCreator;

/**
 * Transfert object between web page and Spring Controller named LogsResource.
 *
 */
public class LoggerDTO {

    private String name;

    private String level;

    public LoggerDTO(Logger logger) {
        this.name = logger.getName();
        this.level = logger.getEffectiveLevel().toString();
    }

    @JsonCreator
    public LoggerDTO() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    @Override
    public String toString() {
        return "LoggerDTO{" + "name='" + name + '\'' + ", level='" + level + '\'' + '}';
    }
}


text:
<?php

declare(strict_types=1);

namespace Skimpy\Contracts;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * Defines an entity that has the potential to have taxonomies and terms
 *
 * Currently, this is only 'ContentItem'
 */
interface Classifiable
{
    public function getTaxonomies(): ArrayCollection;

    public function getTerms(): ArrayCollection;
}


text:
import java.util.ArrayList;
import java.util.List;

import com.google.java.contract.Ensures;
import com.google.java.contract.Invariant;
import com.google.java.contract.Requires;

@Invariant("((left==null) ? true : left.data<data)&&((right==null) ? true : right.data>data)")
public class Node {
	private int data;
	private Node left;
	private Node right;

	public Node(int d, Node l, Node r) {
		data = d;
		left = l;
		right = r;
	}

	public Node(Node n){
		data = n.data;
		if(n.left!=null)
			left = new Node(n.left);
		if(n.right!= null)
			right = new Node(n.right);
	}

	public boolean equals(Object N){
		if(! (N instanceof Node)) return false;
		Node temp = (Node) N;
		if(this.data!=temp.data)
			return false;
		boolean leftTrue = false;
		boolean rightTrue = false;
		if(this.left==null&&temp.left==null)
			leftTrue = true;
		else if(this.left==null||temp.left==null)
			return false;
		if(this.right==null&&temp.right==null)
			rightTrue = true;
		else if(this.right==null||temp.right==null)
			return false;
		return (leftTrue||this.left.equals(temp.left))&&(rightTrue||this.right.equals(temp.right));
	}

	public String toString() {
		String l = (left==null) ? "" : (left + ", ");
		String r = (right==null) ? "" : (", " + right);
		return l + data + r;
	}

	@Requires("this!=null")
	@Ensures("true")
	public void insert(int d) {
		if(data==d) return;

		if(data > d) {
			if(left==null)
				left = new Node(d, null, null);
			else
				left.insert(d);

		} else {
			if(right==null)
				right = new Node(d, null, null);
			else
				right.insert(d);
		}
	}

	public ArrayList<Integer> toList(){
		ArrayList<Integer> tempList = new ArrayList<Integer>();
		if(left!=null)
			tempList.addAll(left.toList());
		tempList.add(data);
		if(right!=null)
			tempList.addAll(right.toList());
		ArrayList<Integer> retList = tempList;
		return retList;
	}

	public boolean contains(int d) {
		if(data == d) return true;

		if(data > d)
			return (left==null) ? false : left.contains(d);

		return (right==null) ? false : right.contains(d);
	}
}


text:
'use strict';

angular.module('pms3App')
  .service('propertyService', ['$log', '$rootScope',
    function propertyService($log, $rootScope) {
      var codes;
      var editing = {};

      function find(items, prop, val) {
        for(var i = 0; i < items.length; i++) {
          var item = items[i];
          var toCheck = item[prop];
          if(val == toCheck) {
            return item;
          }
        }
        return undefined;
      }

      this.loadPropertyByCode = function($scope, code) {
        $scope.editing = [];

        $rootScope.createGet('landlord/load').then(function(data) {
          var landlords = $scope.rests.convertItems(data.data);
          $scope.landlords = landlords;
          $log.info('propertyService landlords transformed: ' + landlords.length);

          var landlord = find(landlords, 'l_number', editing.p_llnumb);
          if(landlord) {
            $scope.landlord = landlord.l_name;
          }
        });

        $rootScope.createGet('townsuburb/load').then(function(data) {
          var townsuburbs = $scope.rests.convertItems(data.data);
          $scope.townsuburbs = townsuburbs;
          $log.info('propertyService townsuburb transformed: ' + townsuburbs.length);

          var townsuburb = find(townsuburbs, 'name', editing.p_townsuburb);
//          if(townsuburb) {
//            $scope.landlord = townsuburb.name;
//          }
        });

        $rootScope.createLoadProperty(code).then(function(data) {
          editing = $scope.rests.convertItem(data.data);
          $scope.editing = editing;

          $scope.puchDate = (editing.p_purchdate?new Date(editing.p_purchdate):'');
          $scope.settleDate = (editing.p_settledate?new Date(editing.p_settledate):'')
          $log.info('propertyService.createLoadProperty transformed: ' +
                     angular.toJson($scope.editing));
        });
      }

      this.loadCodes = function($scope) {
        $scope.properties = [];

        if(!!codes) {
          $scope.properties = codes;
          return;
        }

        $rootScope.createGet('property/codes/load').then(function(data) {
          var ps = (data.data.DATA);
          codes = [];
          ps.forEach(function(p) {
            codes.push(p[0]);
          });

          $scope.properties = codes;

          $log.info('propertyService.loadCodes transformed: ' + $scope.properties.length);
        });
      }
  }]);


text:
from streamsx.spl import spl

#------------------------------------------------------------------
# Example functions
#------------------------------------------------------------------

# Defines the SPL namespace for any functions in this module
# Multiple modules can map to the same namespace
def spl_namespace():
    return "com.ibm.streamsx.topology.pysamples.kwargs"

@spl.map()
class DeltaFilter(object):
    "Drops any tuple that is within a delta of the last tuple for the attribute named `value`."
    def __init__(self, delta):
        self.delta = delta
        self.empty = ()
        self.last_value = None

    # Signature has **kwargs parameter which fixes the
    # SPL tuple parameter passing style to be dictionary
    def __call__(self, **tuple_):
        value = tuple_['value']
        if self.last_value is not None:
            if abs(value - self.last_value) <= self.delta:
                self.last_value = value
                return None
        self.last_value = value
        # Empty tuple will cause any matching input attributes
        # to be carried across to the output tuple
        return self.empty

@spl.filter()
class ContainsFilter(object):
    """
    Looks for a string term in any attribute in the tuple.
    """
    def __init__(self, term):
        self.term = term;

    def __call__(self, **tuple_):
        for s in tuple_.values():
            if self.term in str(s):
                return True
        return False


text:
import Test from '../helpers/test';
import describeOptionalProp from '../describeOptionalProp';
import itsInvalid from '../itsInvalid';
import {
  score,
  booleanValue,
  stringValue,
  duration,
  extensions,
} from '../factory';

const validData = {
  score: {},
  success: false,
  completion: false,
  response: 'test',
  duration: 'P3Y6M4DT12H30M5S',
  extensions: {},
};

export default (test: Test) => {
  itsInvalid(10, 'not an object', test);
  describeOptionalProp('score', score, validData, test);
  describeOptionalProp('success', booleanValue, validData, test);
  describeOptionalProp('completion', booleanValue, validData, test);
  describeOptionalProp('response', stringValue, validData, test);
  describeOptionalProp('duration', duration, validData, test);
  describeOptionalProp('extensions', extensions, validData, test);
};


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

<meta name="collection" content="api">

<TITLE>
Option (Java 2 Platform SE 5.0)
</TITLE>

<META NAME="keywords" CONTENT="javax.swing.text.html.Option class">
<META NAME="keywords" CONTENT="setLabel()">
<META NAME="keywords" CONTENT="getLabel()">
<META NAME="keywords" CONTENT="getAttributes()">
<META NAME="keywords" CONTENT="toString()">
<META NAME="keywords" CONTENT="setSelection()">
<META NAME="keywords" CONTENT="isSelected()">
<META NAME="keywords" CONTENT="getValue()">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javax.swing.text.html

Class Option

java.lang.Object
  javax.swing.text.html.Option

public class Option
extends Object

Value for the ListModel used to represent
 <option> elements.  This is the object
 installed as items of the DefaultComboBoxModel
 used to represent the <select> element.

Constructor Summary

Option(AttributeSet attr)

          Creates a new Option object.

Method Summary

 AttributeSet
getAttributes()

          Fetch the attributes associated with this option.

 String
getLabel()

          Fetch the label associated with the option.

 String
getValue()

          Convenience method to return the string associated
 with the value attribute.

 boolean
isSelected()

          Fetches the selection state associated with this option.

 void
setLabel(String label)

          Sets the label to be used for the option.

protected  void
setSelection(boolean state)

          Sets the selected state.

 String
toString()

          String representation is the label.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Option

public Option(AttributeSet attr)

Creates a new Option object.

Parameters:
attr - the attributes associated with the
  option element.  The attributes are copied to
  ensure they won't change.

Method Detail

setLabel

public void setLabel(String label)

Sets the label to be used for the option.

getLabel

public String getLabel()

Fetch the label associated with the option.

getAttributes

public AttributeSet getAttributes()

Fetch the attributes associated with this option.

toString

public String toString()

String representation is the label.

Overrides:
toString in class Object

Returns:
a string representation of the object.

setSelection

protected void setSelection(boolean state)

Sets the selected state.

isSelected

public boolean isSelected()

Fetches the selection state associated with this option.

getValue

public String getValue()

Convenience method to return the string associated
 with the value attribute.  If the
 value has not been specified, the label will be
 returned.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
struct default_init_tag;

class javax::crypto::spec::IvParameterSpec
    : public virtual ::java::lang::Object
    , public virtual ::java::security::spec::AlgorithmParameterSpec
{

public:
    typedef ::java::lang::Object super;

private:
    ::int8_tArray* iv {  };

protected:
    void ctor(::int8_tArray* arg0);
    void ctor(::int8_tArray* arg0, int32_t arg1, int32_t arg2);

public:
    virtual ::int8_tArray* getIV();

    // Generated
    IvParameterSpec(::int8_tArray* arg0);
    IvParameterSpec(::int8_tArray* arg0, int32_t arg1, int32_t arg2);
protected:
    IvParameterSpec(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT!

package fallk.jfunktion;

/**
 * Represents an operation that accepts a {@code float}-valued and a generic argument and
 * returns no result.  This is the two-arity specialization of {@link java.util.function.Consumer}.
 *
 * @see java.util.function.BiConsumer
 */
@FunctionalInterface
public interface FloatObjectConsumer<E> {

    /**
     * Performs this operation on the given arguments.
     *
     * @param v1 the {@code float} argument
     * @param v2 the generic argument
     */
    void apply(float v1, E v2);
}


text:
.. CyrTranslit documentation master file, created by
   sphinx-quickstart on Sat Feb 18 05:20:15 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

CyrTranslit 1.0
===============
:Source Code: https://github.com/opendatakosovo/cyrillic-transliteration
:PyPI: https://pypi.python.org/pypi/cyrtranslit
:License: MIT
:Author: Georges Labrèche, Open Data Kosovo
:Version: 1.0

====================
What is CyrTranslit?
====================
A Python package for bi-directional transliteration of Cyrillic script to Latin script and vice versa.

By default, transliterates for the Serbian language. A language flag can be set in order to transliterate to and from Bulgarian, Montenegrin, Macedonian, Russian, Serbian, Tajik, and Ukrainian.

========================
What is transliteration?
========================

Transliteration is the conversion of a text from one script to another. For instance, a Latin alphabet transliteration of the Serbian phrase "Мој ховеркрафт је пун јегуља" is "Moj hoverkraft je pun jegulja".

======================
How do I install this?
======================
CyrTranslit is hosted in the Python Package Index (PyPI_) so it can be installed in the Terminal using pip:

Latest version:
    ``$ python -m pip install cyrtranslit``

Specific version:
    ``$ python -m pip install cyrtranslit==1.0``

Minimum version:
    ``$ python -m pip install cyrtranslit>=1.0``

=============================
What languages are supported?
=============================
CyrTranslit currently supports bi-directional transliteration of Bulgarian, Montenegrin, Macedonian, Russian, Serbian, Tajik, and Ukrainian:

>>> import cyrtranslit
>>> cyrtranslit.supported()
['bg', 'me', 'mk', 'ru', 'sr', 'tj', 'ua']

==================
How do I use this?
==================
*********
Bulgarian
*********
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Съединението прави силата!", "bg")
"Săedinenieto pravi silata!"
>>> cyrtranslit.to_cyrillic("Săedinenieto pravi silata!", "bg")
"Съединението прави силата!"

***********
Montenegrin
***********
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Република", "me")
"Republika Kosovo"
>>> cyrtranslit.to_cyrillic("Republika", "me")
"Република Косово"

**********
Macedonian
**********
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Моето летачко возило е полно со јагули", "mk")
"Moeto letačko vozilo e polno so jaguli"
>>> cyrtranslit.to_cyrillic("Moeto letačko vozilo e polno so jaguli", "mk")
"Моето летачко возило е полно со јагули"

*******
Russian
*******
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Моё судно на воздушной подушке полно угрей", "ru")
"Moyo sudno na vozdushnoj podushke polno ugrej"
>>> cyrtranslit.to_cyrillic("Moyo sudno na vozdushnoj podushke polno ugrej", "ru")
"Моё судно на воздушной подушке полно угрей"

*******
Serbian
*******
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Мој ховеркрафт је пун јегуља")
"Moj hoverkraft je pun jegulja"
>>> cyrtranslit.to_cyrillic("Moj hoverkraft je pun jegulja")
"Мој ховеркрафт је пун јегуља"

*****
Tajik
*****
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Ман мактуб навишта истодам", "tj")
"Man maktub navišta istodam"
>>> cyrtranslit.to_cyrillic("Man maktub navišta istodam", "tj")
"Ман мактуб навишта истодам"

*********
Ukrainian
*********
>>> import cyrtranslit
>>> cyrtranslit.to_latin("Під лежачий камінь вода не тече", "ua")
"Pid ležačyj kamin' voda ne teče"
>>> cyrtranslit.to_cyrillic("Pid ležačyj kamin' voda ne teče", "ua")
"Під лежачий камінь вода не тече"

=====================
How can I contribute?
=====================

You can include support for other Cyrillic script alphabets. Follow these steps in order to do so:

1. Create a new transliteration dictionary in the mapping.py_ file and reference to it in the TRANSLIT\_DICT dictionary_.
2. Watch out for cases where two consecutive Roman alphabet letters are meant to transliterate into a single Cyrillic script letter. These cases need to be explicitely checked for inside the to\_cyrillic() function_ in \_\_init\_\_.py.
3. Add test cases inside of tests.py_.
4. Update the documentation in the README.md_ and in the doc directory_.

.. _PyPI: https://pypi.python.org/pypi/cyrtranslit
.. _mapping.py: https://github.com/opendatakosovo/cyrillic-transliteration/blob/master/cyrtranslit/mapping.py
.. _dictionary: https://github.com/opendatakosovo/cyrillic-transliteration/blob/4eabac0526f7cfb0fa39d6b9481ee3b5189dafe2/cyrtranslit/mapping.py#L261-L290
.. _function: https://github.com/opendatakosovo/cyrillic-transliteration/blob/4eabac0526f7cfb0fa39d6b9481ee3b5189dafe2/cyrtranslit/__init__.py#L62-L156
.. _tests.py: https://github.com/opendatakosovo/cyrillic-transliteration/blob/master/tests.py
.. _README.md: https://github.com/opendatakosovo/cyrillic-transliteration/blob/master/README.md
.. _directory: https://github.com/opendatakosovo/cyrillic-transliteration/blob/master/doc


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace RohBot
{
    public enum ImageScale
    {
        Small = 0,
        Medium = 1,
        Large = 2,
        Original = 3
    }

    internal static class Utils
    {
        public static ScrollViewer GetScrollViewer(DependencyObject element)
        {
            var viewer = element as ScrollViewer;
            if (viewer != null)
            {
                return viewer;
            }

            for (var i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);

                var result = GetScrollViewer(child);
                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }

        public static int BinarySearch<T>(this IList<T> list, T value)
            where T : IComparable<T>
        {
            int lo = 0;
            int hi = list.Count - 1;

            while (lo <= hi)
            {
                int i = lo + ((hi - lo) / 2);
                int order = list[i].CompareTo(value);

                if (order == 0)
                    return i;

                if (order < 0)
                    lo = i + 1;
                else
                    hi = i - 1;
            }

            return ~lo;
        }

        public static Task<IRandomAccessStream> ProcessImage(
            IRandomAccessStream imageData, ImageScale scale)
        {
            uint maxDim = 0;
            switch (scale)
            {
                case ImageScale.Small:
                    maxDim = 500;
                    break;

                case ImageScale.Medium:
                    maxDim = 1000;
                    break;

                case ImageScale.Large:
                    maxDim = 2000;
                    break;
            }

            return ProcessImage(imageData, maxDim, maxDim);
        }

        public static Task<IRandomAccessStream> ProcessImage(
            IRandomAccessStream imageData, uint reqWidth, uint reqHeight)
        {
            return Task.Run(async () =>
                await CorrectRotation(await ResizeImage(imageData, reqWidth, reqHeight)));
        }

        private static async Task<IRandomAccessStream> CorrectRotation(IRandomAccessStream imageStream)
        {
            const string orientationKey = "System.Photo.Orientation";

            var decoder = await BitmapDecoder.CreateAsync(imageStream);

            try
            {
                var properties = await decoder.BitmapProperties.GetPropertiesAsync(new[] { orientationKey });
                if (!properties.TryGetValue(orientationKey, out var orientationValue) ||
                    (ushort)orientationValue.Value == 1)
                {
                    // normal orientation doesn't need to be processed
                    return imageStream;
                }
            }
            catch
            {
                // format doesn't support orientation
                return imageStream;
            }

            using (imageStream)
            {
                var bitmap = await decoder.GetSoftwareBitmapAsync(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Straight,
                    new BitmapTransform(),
                    ExifOrientationMode.RespectExifOrientation,
                    ColorManagementMode.DoNotColorManage);

                var memStream = new InMemoryRandomAccessStream();

                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, memStream);
                encoder.SetSoftwareBitmap(bitmap);
                await encoder.FlushAsync();

                return memStream;
            }
        }

        private static async Task<IRandomAccessStream> ResizeImage(
           IRandomAccessStream imageStream, uint reqWidth, uint reqHeight)
        {
            if (reqWidth == 0 && reqHeight == 0)
                return imageStream;

            var decoder = await BitmapDecoder.CreateAsync(imageStream);
            if (decoder.PixelHeight <= reqHeight && decoder.PixelWidth <= reqWidth)
                return imageStream;

            using (imageStream)
            {
                var resizedStream = new InMemoryRandomAccessStream();

                var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
                var widthRatio = (double)reqWidth / decoder.PixelWidth;
                var heightRatio = (double)reqHeight / decoder.PixelHeight;

                var scaleRatio = Math.Min(widthRatio, heightRatio);

                if (reqWidth == 0)
                    scaleRatio = heightRatio;

                if (reqHeight == 0)
                    scaleRatio = widthRatio;

                var aspectHeight = (uint)Math.Floor(decoder.PixelHeight * scaleRatio);
                var aspectWidth = (uint)Math.Floor(decoder.PixelWidth * scaleRatio);

                encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;

                encoder.BitmapTransform.ScaledHeight = aspectHeight;
                encoder.BitmapTransform.ScaledWidth = aspectWidth;

                await encoder.FlushAsync();
                resizedStream.Seek(0);
                return resizedStream;
            }
        }

        public static string GetNamedStringOrNull(this JsonObject obj, string key)
        {
            if (!obj.ContainsKey(key))
                return null;

            var value = obj.GetNamedValue(key);
            if (value.ValueType != JsonValueType.String)
                return null;

            return value.GetString();
        }
    }
}


text:
package main

import (
	"flag"

	"github.com/cloustone/sentel/pkg/config"
	"github.com/golang/glog"

	"github.com/cloustone/sentel/iothub/watcher"
	"github.com/cloustone/sentel/pkg/service"
)

var (
	configFileName = flag.String("c", "/etc/sentel/gateway.conf", "config file")
)

func main() {
	flag.Parse()
	glog.Info("Starting  iothub...")

	c := config.New("iothub")
	c.AddConfig(defaultConfigs)
	c.AddConfigFile(*configFileName)
	service.ResolveServiceConfigs(c, "zookeeper")

	mgr, err := service.NewServiceManager("iothub", c)
	if err != nil {
		glog.Fatalf("iothub create failed: '%s'", err.Error())
	}
	mgr.AddService(watcher.ServiceFactory{})
	glog.Fatal(mgr.RunAndWait())
}


text:
using System;
using AForge.Math;
using STPLoader.Implementation.Parser;

namespace STPLoader.Implementation.Model.Entity
{
    public class CartesianPoint : Entity
    {
        public Vector3 Vector;
        public string Info;

        public override void Init()
        {
            Info = ParseHelper.ParseString(Data[0]);
            var coord = ParseHelper.ParseList<float>(Data[1]);
            Vector = new Vector3(coord[0], coord[1], coord[2]);
        }

        public override string ToString()
        {
            return String.Format("<CartesianPoint({0}, {1})", Info, Vector);
        }
    }
}


text:
/* global angular */
angular.module('youScriberApp').directive('navbar', function (User, Videos) {
  return {
    restrict: 'E',
    // scope: {
    //   userService: '=',
    // },
    replace: true,
    templateUrl: 'views/directives/navbar.html',
    link: function (scope, elem, attrs) {
      scope.userService = User

      scope.logout = function () {
        User.logout()
      }
      scope.query = ''
      scope.search = function () {
        console.log(scope.query)
        Videos.filter = scope.query
      }
    }
  }
})