text:
import 'whatwg-fetch';

export const fetchGif = topic =>
  fetch(`http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=${topic}`)
    .then(response => {
      if (response.status > 400) {
        throw new Error('Error while fetching from the server');
      } else {
        return response.json();
      }
    })
    .then(body => body.data.image_url);


text:
var fs = require('fs');

var file = './data/specialCommandWhitelistUsers.json';
var superAdminsFile = './data/superAdmins.json';

var whitelist = {};
var superAdmins = {};

loadSuperAdmins();
loadWhitelist();

function saveWhitelist() {
    fs.writeFileSync(file, JSON.stringify(whitelist));
    return;
}

function loadSuperAdmins() {
    try {
        if (fs.existsSync(file)) {
            var loaded = JSON.parse(fs.readFileSync(superAdminsFile, 'utf8')) || {};
            Object.keys(loaded).forEach(function (k) {
                superAdmins[k.toLowerCase()] = loaded[k];
            });
        }
    } catch (e) {
        console.log(e);
    }
    return superAdmins;
}

function loadWhitelist() {
    try {
        if (fs.existsSync(file)) {
            var loaded = JSON.parse(fs.readFileSync(file, 'utf8')) || {};
            Object.keys(loaded).forEach(function (k) {
                whitelist[k.toLowerCase()] = loaded[k];
            });
        } else {
            saveWhitelist();
        }
    } catch (e) {
        console.log(e);
    }
    return whitelist;
}

module.exports = {
    isWhitelisted: function (username) {
        if (username !== undefined && username !== null) {
            return !!whitelist[username.toLowerCase()];
        }
        return false;
    },
    hasAdminPermission: function (username) {
        if (username !== undefined && username !== null) {
            return !!superAdmins[username.toLowerCase()];
        }
        return false;
    },
    add: function (username) {
        if (username !== undefined && username !== null) {
            var formatted = username.toLowerCase();
            whitelist[formatted] = true;
            saveWhitelist();
            return !!whitelist[formatted];
        }
        return false;
    },
    remove: function (username) {
        if (username !== undefined && username !== null) {
            var formatted = username.toLowerCase();
            whitelist[formatted] = false;
            saveWhitelist();
            return !!whitelist[formatted];
        }
        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.openapi.editor.impl;

import consulo.editor.impl.CodeEditorInlayModelBase;

import javax.annotation.Nonnull;

public class InlayModelImpl extends CodeEditorInlayModelBase {
  InlayModelImpl(@Nonnull DesktopEditorImpl editor) {
    super(editor);
  }
}


text:
namespace tensor {

// Yes, I know people dislike this...
// Deal with it. Tired of the stds...
using std::enable_if;
using std::is_base_of;

template <typename E, typename T, std::size_t O>
class TensorContract : public TensorExpression<TensorContract<E,T,O>,T,O> {
  public:
    typedef typename TensorExpression<TensorContract<E,T,O>,T,O>::size_type size_type;
    typedef typename TensorExpression<TensorContract<E,T,O>,T,O>::value_type value_type;

    TensorExpression<E,T,O> const& t;
    size_type               const& a;
    size_type               const& b;

  public:
    TensorContract(TensorExpression<E,T,O> const& t,
                   size_type const& a, size_type const& b) : t(t),a(a),b(b) {
      // Check the incoming parameters.
      if(t.size(a) != t.size(b)) throw TensorException("size mismatch on contraction");
      // Calculate the contraction constants.
      // TODO
    };

    inline size_type dims() const { return O-2; }
    inline size_type size() const { return t.size()-t.size(a); }
    inline size_type size(size_type i) const { return t.size(i); }
    inline size_type stride(size_type i) const { return t.stride(i); }

    template <typename... I>
    inline value_type at(I... i) const {
      // TODO Split indices and multiply values from each tensor.
      return 0; // TODO Return actual value.
    }
    template <typename... I>
    inline value_type operator()(I... i) const {
      // TODO Split indices and multiply values from each tensor.
      return 0; // TODO Return actual value.
    }
};

}//namespace tensor

#endif//__TENSOREXPR_CONTRACT_HPP__


text:
import sbt._
import blended.sbt.Dependencies

object BlendedDomino extends ProjectFactory {

  private[this] val helper = new ProjectSettings(
    projectName = "blended.domino",
    description = "Blended Domino extension for new Capsule scopes.",
    deps = Seq(
      Dependencies.typesafeConfig,
      Dependencies.domino
    )
  )

  override val project = helper.baseProject.dependsOn(
    BlendedContainerContextApi.project
  )

}


text:
package rpc

import (
	"fmt"
	"math"
	"time"

	"github.com/btcboost/copernicus/net/server"
	"github.com/btcboost/copernicus/net/wire"
	"github.com/btcboost/copernicus/rpc/btcjson"
	"github.com/btcboost/copernicus/util"
	"github.com/btcboost/copernicus/service"
)

var netHandlers = map[string]commandHandler{
	"getconnectioncount": handleGetConnectionCount,
	"ping":               handlePing,
	"getpeerinfo":        handleGetPeerInfo,
	"addnode":            handleAddNode,
	"disconnectnode":     handleDisconnectNode,
	"getaddednodeinfo":   handleGetAddedNodeInfo,
	"getnettotals":       handleGetNetTotals,
	"getnetworkinfo":     handleGetnetWorkInfo,
	"setban":             handleSetBan,
	"listbanned":         handleListBanned,
	"clearbanned":        handleClearBanned,
	"setnetworkactive":   handleSetNetWorkActive,
}

func handleGetConnectionCount(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	request := service.GetConnectionCountRequest{}
	response, err := server.ProcessForRpc(request)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}
	count, ok := response.(*service.GetConnectionCountResponse)
	if !ok {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Server handle error",
		}
	}

	return count.Count, nil
}

func handlePing(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	nonce := util.GetRand(math.MaxInt64)
	pingCmd := wire.NewMsgPing(nonce)
	_, err := server.ProcessForRpc(pingCmd)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return nil, nil
}

func handleGetPeerInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	getPeerInfoCmd := &service.GetPeersInfoRequest{}

	ret, _ := server.ProcessForRpc(getPeerInfoCmd) // todo Alert: match with return type
	peers := ret.([]server.RpcServerPeer)
	//syncPeerID := s.cfg.SyncMgr.SyncPeerID()
	infos := make([]*btcjson.GetPeerInfoResult, 0, len(peers))
	for _, item := range peers {
		statsSnap := item.ToPeer().StatsSnapshot()
		info := &btcjson.GetPeerInfoResult{
			ID:              statsSnap.ID,
			Addr:            statsSnap.Addr,
			AddrLocal:       item.ToPeer().LocalAddr().String(),
			Services:        fmt.Sprintf("%08d", uint64(statsSnap.Services)),
			RelayTxes:       !item.IsTxRelayDisabled(),
			LastSend:        statsSnap.LastSend.Unix(),
			LastRecv:        statsSnap.LastRecv.Unix(),
			BytesSent:       statsSnap.BytesSent,
			BytesRecv:       statsSnap.BytesRecv,
			ConnTime:        statsSnap.ConnTime.Unix(),
			TimeOffset:      statsSnap.TimeOffset,
			PingTime:        float64(statsSnap.LastPingMicros),
			MinPing:         statsSnap.MingPing,
			Version:         statsSnap.Version,
			SubVer:          statsSnap.UserAgent,
			Inbound:         statsSnap.Inbound,
			AddNode:         statsSnap.AddNode,
			StartingHeight:  statsSnap.StartingHeight,
			BanScore:        int32(item.BanScore()), // TODO
			SyncedHeaders:   statsSnap.SyncedHeaders,
			SyncedBlocks:    statsSnap.SyncedBlocks,
			Inflight:        []int{}, // TODO
			WhiteListed:     statsSnap.WhiteListed,
			CashMagic:       statsSnap.UsesCashMagic,
			BytesSendPerMsg: statsSnap.MapSendBytesPerMsgCmd,
			BytesRecvPerMsg: statsSnap.MapRecvBytesPerMsgCmd,
		}
		if item.ToPeer().LastPingNonce() != 0 {
			wait := float64(time.Since(statsSnap.LastPingTime).Nanoseconds())
			// We actually want microseconds.
			info.PingWait = wait / 1000
		}
		infos = append(infos, info)
	}
	return infos, nil
}

func handleAddNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.AddNodeCmd)
	_, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCInvalidParameter,
			Message: err.Error(),
		}
	}

	return nil, nil
}

func handleDisconnectNode(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.DisconnectNodeCmd)

	_, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCInvalidParameter,
			Message: err.Error(),
		}
	}

	return nil, nil
}

func handleGetAddedNodeInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.GetAddedNodeInfoCmd)

	ret, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return ret, nil
}

func handleGetNetTotals(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	ret, err := server.ProcessForRpc(&service.GetNetTotalsRequest{})
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCInvalidParameter,
			Message: err.Error(),
		}
	}
	return ret, nil
}

func handleGetnetWorkInfo(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.GetNetworkInfoCmd)

	ret, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return ret, nil
}

func handleSetBan(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.SetBanCmd)

	_, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return nil, nil
}

func handleListBanned(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	ret, err := server.ProcessForRpc(&service.ListBannedRequest{})
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}
	return ret, nil
}

func handleClearBanned(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	_, err := server.ProcessForRpc(&service.ClearBannedRequest{})
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return nil, nil
}

func handleSetNetWorkActive(s *Server, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	c := cmd.(*btcjson.SetNetWorkActiveCmd)

	ret, err := server.ProcessForRpc(c)
	if err != nil {
		return nil, btcjson.RPCError{
			Code:    btcjson.RPCInternalError,
			Message: "Can not acquire connection count",
		}
	}

	return ret, nil
}

func registerNetRPCCommands() {
	for name, handler := range netHandlers {
		appendCommand(name, handler)
	}
}


text:
#include "vecamole/map.h"
#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <stdexcept>
#include <iostream>

vecamole_map_t *vecamole_map_new(int width, int height) {
  try {
    mapnik::Map *ptr = new mapnik::Map(width, height);
    return static_cast<vecamole_map_t *>(ptr);

  } catch (...) {
    // bad alloc should be the only thing thrown by operator new
  }

  return nullptr;
}

int vecamole_map_delete(vecamole_map_t *map) {
  mapnik::Map *ptr = static_cast<mapnik::Map *>(map);

  if (ptr != nullptr) {
    delete ptr;
    return 0;
  }

  return 1;
}

int vecamole_map_register_fonts(vecamole_map_t *map, const char *dir, int recurse) {
  mapnik::Map *ptr = static_cast<mapnik::Map *>(map);

  if (ptr != nullptr) {
    try {
      std::string cpp_dir(dir);
      bool cpp_recurse(recurse);

      bool result = ptr->register_fonts(cpp_dir, cpp_recurse);

      return result ? 1 : 0;

    } catch (...) {
      // not sure what exceptions mapnik::Map::register_fonts could throw
      // but result is error regardless.
    }
  }

  return -1;
}

int vecamole_map_load_file(vecamole_map_t *map, const char *file, int strict, const char *base_path) {
  mapnik::Map *ptr = static_cast<mapnik::Map *>(map);

  if (ptr != nullptr) {
    try {
      std::string cpp_file(file);
      bool cpp_strict(strict);
      std::string cpp_base_path;
      if (base_path != nullptr) {
        cpp_base_path = base_path;
      }

      mapnik::load_map(*ptr, cpp_file, cpp_strict, cpp_base_path);

      return 0;

    } catch (...) {
      // not sure what exceptions mapnik::load_map could throw
      // but result is error regardless.
    }
  }

  return -1;
}

int vecamole_map_load_string(vecamole_map_t *map, const char *string, int strict, const char *base_path) {
  mapnik::Map *ptr = static_cast<mapnik::Map *>(map);

  if (ptr != nullptr) {
    try {
      std::string cpp_string(string);
      bool cpp_strict(strict);
      std::string cpp_base_path;
      if (base_path != nullptr) {
        cpp_base_path = base_path;
      }

      mapnik::load_map_string(*ptr, cpp_string, cpp_strict, cpp_base_path);

      return 0;

    } catch (const std::exception &e) {
      std::cerr << "EXCEPTION: " << e.what() << std::endl;

    } catch (...) {
      // not sure what exceptions mapnik::load_map could throw
      // but result is error regardless.
    }
  }

  return -1;
}


text:
package main

import (
	"fmt"
	"time"

	"github.com/gilramir/argparse/v2"
)

type MyOptions struct {
	Count      int
	Expiration time.Duration
	Verbose    bool
	Names      []string
}

func main() {
	opts := &MyOptions{}
	ap := argparse.New(&argparse.Command{
		Name:        "Example 1",
		Description: "This is an example program",
		Values:      opts,
	})

	// These are switch arguments
	ap.Add(&argparse.Argument{
		Switches: []string{"--count"},
		MetaVar:  "N",
		Help:     "How many items",
	})

	ap.Add(&argparse.Argument{
		Switches: []string{"--expiration", "-x"},
		Help:     "How long: #(h|m|s|ms|us|ns)",
	})

	ap.Add(&argparse.Argument{
		Switches: []string{"-v", "--verbose"},
		Help:     "Set verbose mode",
	})

	// This is a positional argument
	ap.Add(&argparse.Argument{
		Name: "names",
		Help: "Some names passed into the program",
		// We require one or more names
		NumArgsGlob: "+",
	})

	// The library handles errors, and -h/--help
	ap.Parse()

	fmt.Printf("Verbose is %t\n", opts.Verbose)
	fmt.Printf("Count is %d\n", opts.Count)

	if ap.Root.Seen["Expiration"] {
		fmt.Printf("Expiration: %s\n", opts.Expiration.String())
	}

	fmt.Printf("Number of names: %d\n", len(opts.Names))
	for i := 0; i < len(opts.Names); i++ {
		fmt.Printf("%d. %s\n", i+1, opts.Names[i])
	}
}


text:
.reveal img.inline {
  margin: 0;
  vertical-align: middle;
}

.reveal .visible-links a {
  color: white;
}


text:
package org.takes.facets.fallback;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import lombok.EqualsAndHashCode;
import org.takes.HttpException;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.tk.TkWrap;

/**
 * Fallback.
 *
 * <p>The class is immutable and thread-safe.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 0.1
 * @checkstyle IllegalCatchCheck (500 lines)
 */
@EqualsAndHashCode(callSuper = true)
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public final class TkFallback extends TkWrap {

    /**
     * Ctor.
     * @param take Original take
     * @param fbk Fallback
     */
    public TkFallback(final Take take, final Fallback fbk) {
        super(
            new Take() {
                @Override
                public Response act(final Request req) throws IOException {
                    return TkFallback.route(take, fbk, req);
                }
            }
        );
    }

    /**
     * Route this request.
     * @param take The take
     * @param fbk Fallback
     * @param req Request
     * @return Response
     * @throws IOException If fails
     */
    private static Response route(final Take take, final Fallback fbk,
        final Request req) throws IOException {
        Response res;
        try {
            res = TkFallback.wrap(
                take.act(req), fbk, req
            );
        } catch (final HttpException ex) {
            res = TkFallback.wrap(
                fbk.route(new RqFallback.Fake(req, ex.code(), ex)).get(),
                fbk, req
            );
        } catch (final Throwable ex) {
            res = TkFallback.wrap(
                fbk.route(
                    new RqFallback.Fake(
                        req, HttpURLConnection.HTTP_INTERNAL_ERROR, ex
                    )
                ).get(),
                fbk, req
            );
        }
        return res;
    }

    /**
     * Wrap response.
     * @param res Response to wrap
     * @param fbk Fallback
     * @param req Request
     * @return Response
     */
    private static Response wrap(final Response res, final Fallback fbk,
        final Request req) {
        // @checkstyle AnonInnerLengthCheck (50 lines)
        return new Response() {
            @Override
            public Iterable<String> head() throws IOException {
                Iterable<String> head;
                try {
                    head = res.head();
                } catch (final HttpException ex) {
                    head = fbk.route(
                        new RqFallback.Fake(req, ex.code(), ex)
                    ).get().head();
                } catch (final Throwable ex) {
                    head = fbk.route(
                        new RqFallback.Fake(
                            req, HttpURLConnection.HTTP_INTERNAL_ERROR, ex
                        )
                    ).get().head();
                }
                return head;
            }
            @Override
            public InputStream body() throws IOException {
                InputStream body;
                try {
                    body = res.body();
                } catch (final HttpException ex) {
                    body = fbk.route(
                        new RqFallback.Fake(req, ex.code(), ex)
                    ).get().body();
                } catch (final Throwable ex) {
                    body = fbk.route(
                        new RqFallback.Fake(
                            req, HttpURLConnection.HTTP_INTERNAL_ERROR, ex
                        )
                    ).get().body();
                }
                return body;
            }
        };
    }

}


text:
<component name="InspectionProjectProfileManager">
  <profile version="1.0">
    <option name="myName" value="Project Default" />
    <inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="TOP_LEVEL_CLASS_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="INNER_CLASS_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="METHOD_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
        </value>
      </option>
      <option name="FIELD_OPTIONS">
        <value>
          <option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
          <option name="REQUIRED_TAGS" value="" />
        </value>
      </option>
      <option name="IGNORE_DEPRECATED" value="false" />
      <option name="IGNORE_JAVADOC_PERIOD" value="true" />
      <option name="IGNORE_DUPLICATED_THROWS" value="false" />
      <option name="IGNORE_POINT_TO_ITSELF" value="false" />
      <option name="myAdditionalJavadocTags" value="author" />
    </inspection_tool>
    <inspection_tool class="SerialVersionUIDNotStaticFinal" enabled="true" level="WARNING" enabled_by_default="true" />
    <inspection_tool class="SerializableHasSerialVersionUIDField" enabled="true" level="WARNING" enabled_by_default="true">
      <option name="ignoreAnonymousInnerClasses" value="false" />
      <option name="superClassString" value="" />
    </inspection_tool>
  </profile>
</component>


text:
@interface OOMoreAppsView : UIView
{
}
// default: 10 ~ 12
@property(nonatomic, assign) float randomTimeFrom, randomTimeTo;

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
- (void)startAnimate;
- (void)stopAnimate;
- (void)setBannerImageUrls:(NSArray *)imageUrls;

//- (void)bindWithData:(OOMoreAppsEntity *)moreAppsEntity;

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>Ilwis-Objects: Ilwis::IlwisObjectConnector Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Ilwis-Objects
    1.0

GIS and Remote Sensing framework for data access and processing

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Enumerations Pages

Ilwis

IlwisObjectConnector

Public Member Functions |
Protected Member Functions |
Protected Attributes |
List of all members

Ilwis::IlwisObjectConnector Class Referenceabstract

Inheritance diagram for Ilwis::IlwisObjectConnector:

  <map id="Ilwis::IlwisObjectConnector_map" name="Ilwis::IlwisObjectConnector_map">
<area href="class_ilwis_1_1_connector_interface.html" title="The ConnectorInterface class all connectors are derived from this interface." alt="Ilwis::ConnectorInterface" shape="rect" coords="86,0,248,24"/>
<area href="class_ilwis_1_1_catalog_connector.html" alt="Ilwis::CatalogConnector" shape="rect" coords="0,112,162,136"/>
<area href="class_ilwis_1_1_operation_connector.html" alt="Ilwis::OperationConnector" shape="rect" coords="172,112,334,136"/>
</map>

Public Member Functions

 	IlwisObjectConnector (const Ilwis::Resource &resource, bool, const PrepareOptions &options=PrepareOptions())

virtual IlwisObject * 	create () const =0

IlwisTypes 	type () const

Resource & 	source ()

 	source returns the resource location were this connector is attached to  More...

const Resource & 	source () const

bool 	dataIsLoaded () const

 Public Member Functions inherited from Ilwis::ConnectorInterface

virtual bool 	loadMetaData (IlwisObject *)

 	loads the metadata and non binary information into the ilwisobject. After this method it should be a valid object  More...

virtual Grid * 	loadGridData (IlwisObject *)

 	loadGridData loads the 2D or 3D raster data from the source into memory  More...

virtual bool 	loadData (IlwisObject *)

 	loadData loads bulk binary data into the ilwisobject.  More...

virtual bool 	store (IlwisObject *, int)

virtual bool 	execute (const OperationExpression &, ExecutionContext *)

virtual bool 	isReadOnly ()

 	isReadOnly returns if a connector can write to a source.  More...

virtual ConnectorInterface * 	clone () const

 	clone copies the connector for use with another object  More...

virtual QString 	provider () const =0

virtual void 	format (const QString &)

virtual QString 	format () const

virtual bool 	isValid () const

virtual bool 	canUse (const Resource &) const

Protected Member Functions

template<class T >

T 	setObject (const QString &propeprty, const QString defaultName)

UPCatalogConnector & 	containerConnector (IlwisObject::ConnectorMode mode=IlwisObject::cmINPUT)

const UPCatalogConnector & 	containerConnector (IlwisObject::ConnectorMode mode=IlwisObject::cmINPUT) const

Protected Attributes

Resource 	_resource

bool 	_binaryIsLoaded

std::mutex 	_mutex

Member Function Documentation

          Resource & IlwisObjectConnector::source
          (
          	)

virtual

source returns the resource location were this connector is attached to

Returns

the url of the source

Implements Ilwis::ConnectorInterface.

The documentation for this class was generated from the following files:

ilwisobjects/ilwisobjectconnector.h

ilwisobjects/ilwisobjectconnector.cpp

<address class="footer">
Generated on Fri Mar 28 2014 13:51:05 for Ilwis-Objects by

 1.8.3.1
</address>


text:
function plterrel(xo,yo,C,s,ltype)
% PLTERREL  Plots an error ellipse on screen.
%   Note 1: x & y represent north & south (opposite of
%   normal MatLab convention).  Note 2: use a square
%   aspect ratio for plot; i.e., use axis('square')
%   command.  Non-vectorized.
% Version: 18 Jan 96
% Useage:  plterrel(xo,yo,C,s,ltype)
% Input:   xo - x (north) origin of ellipse
%          yo - y (east) origin of ellipse
%          C  - covariance matrix (2x2)
%          s  - ellipse scale factor (default=1)
%          ltype - line type for error ellipse
%                  (default=solid,red)
% Output:  Plotted error ellipse centred at (xo,yo)

% Copyright (c) 2011, Michael R. Craymer
% All rights reserved.
% Email: mike@craymer.com

if nargin<3
  error('Too few input arguements');
end
if nargin<4
  s=1;             % Define default scale factor
end
if nargin<5
  ltype='-r';      % Define default color red
end
dt=0.1;            % Angular resolution
t=[(0:dt:2*pi)';0];
[V,D]=eig(C);      % Eigenvalues & vectors
r=sqrt(diag(D));   % Length of axes
x=s*r(1)*cos(t);
y=s*r(2)*sin(t);
xx=xo+[x y]*V(1,:)';
yy=yo+[x y]*V(2,:)';
plot(yy,xx,ltype);  % Switch x (north) & y (east)


text:
package action

import (
	"crypto/md5"
	"github.com/jmoiron/sqlx"
)

// Defines the execution context of actions
type Context struct {
	Tx        *sqlx.Tx
	Db        *sqlx.DB
	stmtCache map[string]*sqlx.Stmt
}

func NewContext(tx *sqlx.Tx, db *sqlx.DB) *Context {
	return &Context{
		tx,
		db,
		make(map[string]*sqlx.Stmt),
	}
}

func (c *Context) getHash(str string) string {
	h := md5.New()
	return string(h.Sum([]byte(str)))
}

func (c *Context) GetPreparedStatement(statement string) (*sqlx.Stmt, error) {
	hash := c.getHash(statement)

	if stmt, ok := c.stmtCache[hash]; ok {
		return stmt, nil
	} else {
		stmt, err := c.Tx.Preparex(statement)

		if err != nil {
			return nil, err
		}

		c.stmtCache[hash] = stmt

		return stmt, nil
	}

	return nil, nil
}

func (c *Context) FlushStatements() error {
	for _, stmt := range c.stmtCache {
		// Exec and close each statement
		_, err := stmt.Exec()
		if err != nil {
			return err
		}

		err = stmt.Close()
		if err != nil {
			return err
		}
	}

	return nil
}

func (c *Context) Commit() error {
	return c.Tx.Commit()
}


text:
package griffon.pivot.support.adapters;

import griffon.core.CallableWithArgs;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class ActivityIndicatorAdapterTest {
    private ActivityIndicatorAdapter adapter = new ActivityIndicatorAdapter();

    @Test
    public void testActiveChanged() {
        final boolean[] invoked = new boolean[1];
        CallableWithArgs<Void> callable = new CallableWithArgs<Void>() {
            public Void call(Object... args) {
                invoked[0] = true;
                return null;
            }
        };

        assertNull(adapter.getActiveChanged());
        adapter.activeChanged(null);
        assertFalse(invoked[0]);

        adapter.setActiveChanged(callable);
        adapter.activeChanged(null);
        assertTrue(invoked[0]);
    }

}


text:
$platform = 'win32-ia32'

. "$PSScriptRoot\..\win32-shared\build.ps1" -platform $platform


text:
package java.util;

import com.google.j2objc.annotations.Weak;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.io.Serializable;
import java.lang.ref.WeakReference;

import libcore.util.Objects;

/**
 * HashMap is an implementation of {@link Map}. All optional operations are supported.
 *
 *
All elements are permitted as keys or values, including null.
 *
 *
Note that the iteration order for HashMap is non-deterministic. If you want
 * deterministic iteration, use {@link LinkedHashMap}.
 *
 *
Note: the implementation of {@code HashMap} is not synchronized.
 * If one thread of several threads accessing an instance modifies the map
 * structurally, access to the map needs to be synchronized. A structural
 * modification is an operation that adds or removes an entry. Changes in
 * the value of an entry are not structural changes.
 *
 *
The {@code Iterator} created by calling the {@code iterator} method
 * may throw a {@code ConcurrentModificationException} if the map is structurally
 * changed while an iterator is used to iterate over the elements. Only the
 * {@code remove} method that is provided by the iterator allows for removal of
 * elements during iteration. It is not possible to guarantee that this
 * mechanism works in all cases of unsynchronized concurrent modification. It
 * should only be used for debugging purposes.
 *
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */
public class HashMap<K, V> extends AbstractMap<K, V> implements Cloneable, Serializable {
    /**
     * Min capacity (other than zero) for a HashMap. Must be a power of two
     * greater than 1 (and less than 1 << 30).
     */
    private static final int MINIMUM_CAPACITY = 4;

    /**
     * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY.
     */
    private static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * An empty table shared by all zero-capacity maps (typically from default
     * constructor). It is never written to, and replaced on first put. Its size
     * is set to half the minimum, so that the first resize will create a
     * minimum-sized table.
     */
    private static final Entry[] EMPTY_TABLE
            = new HashMapEntry[MINIMUM_CAPACITY >>> 1];

    /**
     * The default load factor. Note that this implementation ignores the
     * load factor, but cannot do away with it entirely because it's
     * mentioned in the API.
     *
     *
Note that this constant has no impact on the behavior of the program,
     * but it is emitted as part of the serialized form. The load factor of
     * .75 is hardwired into the program, which uses cheap shifts in place of
     * expensive division.
     */
    static final float DEFAULT_LOAD_FACTOR = .75F;

    /**
     * The hash table. If this hash map contains a mapping for null, it is
     * not represented this hash table.
     */
    transient HashMapEntry<K, V>[] table;

    /**
     * The entry representing the null key, or null if there's no such mapping.
     */
    transient HashMapEntry<K, V> entryForNullKey;

    /**
     * The number of mappings in this hash map.
     */
    transient int size;

    /**
     * Incremented by "structural modifications" to allow (best effort)
     * detection of concurrent modification.
     */
    transient int modCount;

    /**
     * The table is rehashed when its size exceeds this threshold.
     * The value of this field is generally .75 * capacity, except when
     * the capacity is zero, as described in the EMPTY_TABLE declaration
     * above.
     */
    private transient int threshold;

    // Views - lazily initialized
    private volatile transient WeakReference<Set<K>> keySet = new WeakReference<Set<K>>(null);
    private volatile transient WeakReference<Set<Entry<K, V>>> entrySet = new WeakReference<Set<Entry<K, V>>>(null);
    private volatile transient WeakReference<Collection<V>> values = new WeakReference<Collection<V>>(null);

    /**
     * Constructs a new empty {@code HashMap} instance.
     */
    @SuppressWarnings("unchecked")
    public HashMap() {
        table = (HashMapEntry<K, V>[]) EMPTY_TABLE;
        threshold = -1; // Forces first put invocation to replace EMPTY_TABLE
    }

    /**
     * Constructs a new {@code HashMap} instance with the specified capacity.
     *
     * @param capacity
     *            the initial capacity of this hash map.
     * @throws IllegalArgumentException
     *                when the capacity is less than zero.
     */
    public HashMap(int capacity) {
        if (capacity < 0) {
            throw new IllegalArgumentException("Capacity: " + capacity);
        }

        if (capacity == 0) {
            @SuppressWarnings("unchecked")
            HashMapEntry<K, V>[] tab = (HashMapEntry<K, V>[]) EMPTY_TABLE;
            table = tab;
            threshold = -1; // Forces first put() to replace EMPTY_TABLE
            return;
        }

        if (capacity < MINIMUM_CAPACITY) {
            capacity = MINIMUM_CAPACITY;
        } else if (capacity > MAXIMUM_CAPACITY) {
            capacity = MAXIMUM_CAPACITY;
        } else {
            capacity = Collections.roundUpToPowerOfTwo(capacity);
        }
        makeTable(capacity);
    }

    /**
     * Constructs a new {@code HashMap} instance with the specified capacity and
     * load factor.
     *
     * @param capacity
     *            the initial capacity of this hash map.
     * @param loadFactor
     *            the initial load factor.
     * @throws IllegalArgumentException
     *                when the capacity is less than zero or the load factor is
     *                less or equal to zero or NaN.
     */
    public HashMap(int capacity, float loadFactor) {
        this(capacity);

        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new IllegalArgumentException("Load factor: " + loadFactor);
        }

        /*
         * Note that this implementation ignores loadFactor; it always uses
         * a load factor of 3/4. This simplifies the code and generally
         * improves performance.
         */
    }

    /**
     * Constructs a new {@code HashMap} instance containing the mappings from
     * the specified map.
     *
     * @param map
     *            the mappings to add.
     */
    public HashMap(Map<? extends K, ? extends V> map) {
        this(capacityForInitSize(map.size()));
        constructorPutAll(map);
    }

    /**
     * Inserts all of the elements of map into this HashMap in a manner
     * suitable for use by constructors and pseudo-constructors (i.e., clone,
     * readObject). Also used by LinkedHashMap.
     */
    final void constructorPutAll(Map<? extends K, ? extends V> map) {
        if (table == EMPTY_TABLE) {
            doubleCapacity(); // Don't do unchecked puts to a shared table.
        }
        for (Entry<? extends K, ? extends V> e : map.entrySet()) {
            constructorPut(e.getKey(), e.getValue());
        }
    }

    /**
     * Returns an appropriate capacity for the specified initial size. Does
     * not round the result up to a power of two; the caller must do this!
     * The returned value will be between 0 and MAXIMUM_CAPACITY (inclusive).
     */
    static int capacityForInitSize(int size) {
        int result = (size >> 1) + size; // Multiply by 3/2 to allow for growth

        // boolean expr is equivalent to result >= 0 && result<MAXIMUM_CAPACITY
        return (result & ~(MAXIMUM_CAPACITY-1))==0 ? result : MAXIMUM_CAPACITY;
    }

    /**
     * Returns a shallow copy of this map.
     *
     * @return a shallow copy of this map.
     */
    @SuppressWarnings("unchecked")
    @Override public Object clone() {
        /*
         * This could be made more efficient. It unnecessarily hashes all of
         * the elements in the map.
         */
        HashMap<K, V> result;
        try {
            result = (HashMap<K, V>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError(e);
        }

        // Restore clone to empty state, retaining our capacity and threshold
        result.makeTable(table.length);
        result.entryForNullKey = null;
        result.size = 0;
        result.keySet = null;
        result.entrySet = null;
        result.values = null;

        result.init(); // Give subclass a chance to initialize itself
        result.constructorPutAll(this); // Calls method overridden in subclass!!
        return result;
    }

    /**
     * This method is called from the pseudo-constructors (clone and readObject)
     * prior to invoking constructorPut/constructorPutAll, which invoke the
     * overridden constructorNewEntry method. Normally it is a VERY bad idea to
     * invoke an overridden method from a pseudo-constructor (Effective Java
     * Item 17). In this case it is unavoidable, and the init method provides a
     * workaround.
     */
    void init() { }

    /**
     * Returns whether this map is empty.
     *
     * @return {@code true} if this map has no elements, {@code false}
     *         otherwise.
     * @see #size()
     */
    @Override public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the number of elements in this map.
     *
     * @return the number of elements in this map.
     */
    @Override public int size() {
        return size;
    }

    /**
     * Returns the value of the mapping with the specified key.
     *
     * @param key
     *            the key.
     * @return the value of the mapping with the specified key, or {@code null}
     *         if no mapping for the specified key is found.
     */
    public V get(Object key) {
        if (key == null) {
            HashMapEntry<K, V> e = entryForNullKey;
            return e == null ? null : e.value;
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
                e != null; e = e.next) {
            K eKey = e.key;
            if (eKey == key || (e.hash == hash && key.equals(eKey))) {
                return e.value;
            }
        }
        return null;
    }

    /**
     * Returns whether this map contains the specified key.
     *
     * @param key
     *            the key to search for.
     * @return {@code true} if this map contains the specified key,
     *         {@code false} otherwise.
     */
    @Override public boolean containsKey(Object key) {
        if (key == null) {
            return entryForNullKey != null;
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
                e != null; e = e.next) {
            K eKey = e.key;
            if (eKey == key || (e.hash == hash && key.equals(eKey))) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns whether this map contains the specified value.
     *
     * @param value
     *            the value to search for.
     * @return {@code true} if this map contains the specified value,
     *         {@code false} otherwise.
     */
    @Override public boolean containsValue(Object value) {
        HashMapEntry[] tab = table;
        int len = tab.length;
        if (value == null) {
            for (int i = 0; i < len; i++) {
                for (HashMapEntry e = tab[i]; e != null; e = e.next) {
                    if (e.value == null) {
                        return true;
                    }
                }
            }
            return entryForNullKey != null && entryForNullKey.value == null;
        }

        // value is non-null
        for (int i = 0; i < len; i++) {
            for (HashMapEntry e = tab[i]; e != null; e = e.next) {
                if (value.equals(e.value)) {
                    return true;
                }
            }
        }
        return entryForNullKey != null && value.equals(entryForNullKey.value);
    }

    /**
     * Maps the specified key to the specified value.
     *
     * @param key
     *            the key.
     * @param value
     *            the value.
     * @return the value of any previous mapping with the specified key or
     *         {@code null} if there was no such mapping.
     */
    @Override public V put(K key, V value) {
        if (key == null) {
            return putValueForNullKey(value);
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        int index = hash & (tab.length - 1);
        for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
            if (e.hash == hash && key.equals(e.key)) {
                preModify(e);
                V oldValue = e.value;
                e.value = value;
                return oldValue;
            }
        }

        // No entry for (non-null) key is present; create one
        modCount++;
        if (size++ > threshold) {
            tab = doubleCapacity();
            index = hash & (tab.length - 1);
        }
        addNewEntry(key, value, hash, index);
        return null;
    }

    private V putValueForNullKey(V value) {
        HashMapEntry<K, V> entry = entryForNullKey;
        if (entry == null) {
            addNewEntryForNullKey(value);
            size++;
            modCount++;
            return null;
        } else {
            preModify(entry);
            V oldValue = entry.value;
            entry.value = value;
            return oldValue;
        }
    }

    /**
     * Give LinkedHashMap a chance to take action when we modify an existing
     * entry.
     *
     * @param e the entry we're about to modify.
     */
    void preModify(HashMapEntry<K, V> e) { }

    /**
     * This method is just like put, except that it doesn't do things that
     * are inappropriate or unnecessary for constructors and pseudo-constructors
     * (i.e., clone, readObject). In particular, this method does not check to
     * ensure that capacity is sufficient, and does not increment modCount.
     *
     * Written natively to avoid retain calls on the result of
     * "constructorNewRetainedEntry()" which returns an already retained object.
     */
    private native void constructorPut(K key, V value) /*-[
      if (key == nil) {
        JavaUtilHashMap_HashMapEntry *entry_ = self->entryForNullKey_;
        if (entry_ == nil) {
          self->entryForNullKey_ = [self constructorNewRetainedEntryWithId:nil withId:value
              withInt:0 withJavaUtilHashMap_HashMapEntry:nil];
          self->size__++;
        } else {
          JavaUtilHashMap_HashMapEntry_set_value_(entry_, value);
        }
        return;
      }
      jint hash_ = JavaUtilCollections_secondaryHashWithId_(key);
      IOSObjectArray *tab = self->table_;
      jint index = hash_ & (tab->size_ - 1);
      JavaUtilHashMap_HashMapEntry *first = tab->buffer_[index];
      for (JavaUtilHashMap_HashMapEntry *e = first; e != nil; e = e->next_) {
        if (e->hash__ == hash_ && [key isEqual:e->key_]) {
          JavaUtilHashMap_HashMapEntry_set_value_(e, value);
          return;
        }
      }
      tab->buffer_[index] = [self constructorNewRetainedEntryWithId:key withId:value withInt:hash_
          withJavaUtilHashMap_HashMapEntry:first];
      self->size__++;
    ]-*/;

    /**
     * Creates a new entry for the given key, value, hash, and index and
     * inserts it into the hash table. This method is called by put
     * (and indirectly, putAll), and overridden by LinkedHashMap. The hash
     * must incorporate the secondary hash function.
     *
     * Native code modified to avoid calling retain/autorelease on the displaced
     * entry already in the table.
     */
    native void addNewEntry(K key, V value, int hash, int index) /*-[
      JavaUtilHashMap_HashMapEntry *newEntry = [[JavaUtilHashMap_HashMapEntry alloc]
          initWithId:key withId:value withInt:hash_ withJavaUtilHashMap_HashMapEntry:nil];
      newEntry->next_ = table_->buffer_[index];
      table_->buffer_[index] = newEntry;
    ]-*/;

    /**
     * Creates a new entry for the null key, and the given value and
     * inserts it into the hash table. This method is called by put
     * (and indirectly, putAll), and overridden by LinkedHashMap.
     */
    void addNewEntryForNullKey(V value) {
        entryForNullKey = new HashMapEntry<K, V>(null, value, 0, null);
    }

    /**
     * Like newEntry, but does not perform any activity that would be
     * unnecessary or inappropriate for constructors. In this class, the
     * two methods behave identically; in LinkedHashMap, they differ.
     *
     * This native method has a modified contract from the original version.
     * It must return a retained entry object. And it must avoid retaining the
     * "first" parameter when setting it to the "next" field of the new entry.
     */
    native HashMapEntry<K, V> constructorNewRetainedEntry(
            K key, V value, int hash, HashMapEntry<K, V> first) /*-[
      JavaUtilHashMap_HashMapEntry *entry = [[JavaUtilHashMap_HashMapEntry alloc]
          initWithId:key withId:value withInt:hash_ withJavaUtilHashMap_HashMapEntry:nil];
      entry->next_ = first;
      return entry;
    ]-*/;

    /**
     * Copies all the mappings in the specified map to this map. These mappings
     * will replace all mappings that this map had for any of the keys currently
     * in the given map.
     *
     * @param map
     *            the map to copy mappings from.
     */
    @Override public void putAll(Map<? extends K, ? extends V> map) {
        ensureCapacity(map.size());
        super.putAll(map);
    }

    /**
     * Ensures that the hash table has sufficient capacity to store the
     * specified number of mappings, with room to grow. If not, it increases the
     * capacity as appropriate. Like doubleCapacity, this method moves existing
     * entries to new buckets as appropriate. Unlike doubleCapacity, this method
     * can grow the table by factors of 2^n for n > 1. Hopefully, a single call
     * to this method will be faster than multiple calls to doubleCapacity.
     *
     *
This method is called only by putAll.
     *
     * The native implementation has been modified to avoid retain/autorelease
     * calls on the entry nodes.
     */
    private native void ensureCapacity(int numMappings) /*-[
      jint newCapacity = JavaUtilCollections_roundUpToPowerOfTwoWithInt_(
          JavaUtilHashMap_capacityForInitSizeWithInt_(numMappings));
      IOSObjectArray *oldTable = self->table_;
      jint oldCapacity = oldTable->size_;
      if (newCapacity <= oldCapacity) {
        return;
      }
      if (newCapacity == oldCapacity * 2) {
        JavaUtilHashMap_doubleCapacity(self);
        return;
      }
      IOSObjectArray *newTable = JavaUtilHashMap_makeTableWithInt_(self, newCapacity);
      if (self->size__ != 0) {
        jint newMask = newCapacity - 1;
        for (jint i = 0; i < oldCapacity; i++) {
          for (JavaUtilHashMap_HashMapEntry *e = oldTable->buffer_[i]; e != nil; ) {
            JavaUtilHashMap_HashMapEntry *oldNext = e->next_;
            jint newIndex = e->hash__ & newMask;
            JavaUtilHashMap_HashMapEntry *newNext = newTable->buffer_[newIndex];
            newTable->buffer_[newIndex] = e;
            e->next_ = newNext;
            e = oldNext;
          }
        }
        // We must clear the old table without releasing any of its elements to
        // maintain balanced retain counts for each entry.
        memset(oldTable->buffer_, 0, oldTable->size_ * sizeof(id));
      }
    ]-*/;

    /**
     * Allocate a table of the given capacity and set the threshold accordingly.
     * @param newCapacity must be a power of two
     */
    private HashMapEntry<K, V>[] makeTable(int newCapacity) {
        // By assigning directly to the "table" field, the J2ObjC translator can
        // optimize away a retain/autorelease of the new array.
        table = new HashMapEntry[newCapacity];
        threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity
        return table;
    }

    /**
     * Doubles the capacity of the hash table. Existing entries are placed in
     * the correct bucket on the enlarged table. If the current capacity is,
     * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which
     * will be new unless we were already at MAXIMUM_CAPACITY.
     *
     * The native implementation has been modified to avoid retain/autorelease
     * calls on the entry nodes.
     */
    private native HashMapEntry<K, V>[] doubleCapacity() /*-[
      IOSObjectArray *oldTable = self->table_;
      jint oldCapacity = oldTable->size_;
      if (oldCapacity == JavaUtilHashMap_MAXIMUM_CAPACITY) {
        return oldTable;
      }
      jint newCapacity = oldCapacity * 2;
      IOSObjectArray *newTable = JavaUtilHashMap_makeTableWithInt_(self, newCapacity);
      if (self->size__ == 0) {
        return newTable;
      }
      for (jint j = 0; j < oldCapacity; j++) {
        JavaUtilHashMap_HashMapEntry *e = oldTable->buffer_[j];
        if (e == nil) {
          continue;
        }
        jint highBit = e->hash__ & oldCapacity;
        JavaUtilHashMap_HashMapEntry *broken = nil;
        newTable->buffer_[j | highBit] = e;
        for (JavaUtilHashMap_HashMapEntry *n = e->next_; n != nil; e = n, n = n->next_) {
          jint nextHighBit = n->hash__ & oldCapacity;
          if (nextHighBit != highBit) {
            if (broken == nil)
              newTable->buffer_[j | nextHighBit] = n;
            else
              broken->next_ = n;
            broken = e;
            highBit = nextHighBit;
          }
        }
        if (broken != nil)
          broken->next_ = nil;
      }
      // We must clear the old table without releasing any of its elements to
      // maintain balanced retain counts for each entry.
      memset(oldTable->buffer_, 0, oldTable->size_ * sizeof(id));
      return newTable;
    ]-*/;

    /**
     * Removes the mapping with the specified key from this map.
     *
     * This native version is modified to avoid extra retain/autorelease calls.
     *
     * @param key
     *            the key of the mapping to remove.
     * @return the value of the removed mapping or {@code null} if no mapping
     *         for the specified key was found.
     */
    @Override public native V remove(Object key) /*-[
      if (key == nil) {
        JavaUtilHashMap_HashMapEntry *e = self->entryForNullKey_;
        if (e == nil) {
          return nil;
        }
        JavaUtilHashMap_set_entryForNullKey_(self, nil);
        modCount_++;
        size__--;
        [self postRemoveWithJavaUtilHashMap_HashMapEntry:e];
        return e->value_;
      }
      jint hash_ = JavaUtilCollections_secondaryHashWithId_(key);
      IOSObjectArray *tab = table_;
      jint index = hash_ & (tab->size_ - 1);
      for (JavaUtilHashMap_HashMapEntry *e = tab->buffer_[index], *prev = nil; e != nil;
          prev = e, e = e->next_) {
        if (e->hash__ == hash_ && [key isEqual:e->key_]) {
          if (prev == nil) {
            tab->buffer_[index] = e->next_;
          } else {
            prev->next_ = e->next_;
          }
          e->next_ = nil;  // Balance the missing retain on e.next above.
          [e autorelease];  // Balance the missing release on e above.
          modCount_++;
          size__--;
          [self postRemoveWithJavaUtilHashMap_HashMapEntry:e];
          return e->value_;
        }
      }
      return nil;
    ]-*/;

    /**
     * Subclass overrides this method to unlink entry.
     */
    void postRemove(HashMapEntry<K, V> e) { }

    /**
     * Removes all mappings from this hash map, leaving it empty.
     *
     * @see #isEmpty
     * @see #size
     */
    @Override public void clear() {
        if (size != 0) {
            Arrays.fill(table, null);
            entryForNullKey = null;
            modCount++;
            size = 0;
        }
    }

    /**
     * Returns a set of the keys contained in this map. The set is backed by
     * this map so changes to one are reflected by the other. The set does not
     * support adding.
     *
     * @return a set of the keys.
     */
    @Override public Set<K> keySet() {
        Set<K> ks = keySet.get();
        if (ks == null) {
            ks = new KeySet();
            keySet = new WeakReference<Set<K>>(ks);
        }

        return ks;
    }

    /**
     * Returns a collection of the values contained in this map. The collection
     * is backed by this map so changes to one are reflected by the other. The
     * collection supports remove, removeAll, retainAll and clear operations,
     * and it does not support add or addAll operations.
     *

     * This method returns a collection which is the subclass of
     * AbstractCollection. The iterator method of this subclass returns a
     * "wrapper object" over the iterator of map's entrySet(). The {@code size}
     * method wraps the map's size method and the {@code contains} method wraps
     * the map's containsValue method.
     *

     *

     * The collection is created when this method is called for the first time
     * and returned in response to all subsequent calls. This method may return
     * different collections when multiple concurrent calls occur, since no
     * synchronization is performed.
     *

     *
     * @return a collection of the values contained in this map.
     */
    @Override public Collection<V> values() {
        Collection<V> vs = values.get();
        if (vs == null) {
            vs = new Values();
            values = new WeakReference<Collection<V>>(vs);
        }

        return vs;
    }

    /**
     * Returns a set containing all of the mappings in this map. Each mapping is
     * an instance of {@link Map.Entry}. As the set is backed by this map,
     * changes in one will be reflected in the other.
     *
     * @return a set of the mappings.
     */
    public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> es = entrySet.get();
        if (es == null) {
            es = new EntrySet();
            entrySet = new WeakReference<Set<Entry<K, V>>>(es);
        }

        return es;
    }

    static class HashMapEntry<K, V> implements Entry<K, V> {
        final K key;
        V value;
        final int hash;
        HashMapEntry<K, V> next;

        HashMapEntry(K key, V value, int hash, HashMapEntry<K, V> next) {
            this.key = key;
            this.value = value;
            this.hash = hash;
            this.next = next;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        @Override public final boolean equals(Object o) {
            if (!(o instanceof Entry)) {
                return false;
            }
            Entry<?, ?> e = (Entry<?, ?>) o;
            return Objects.equal(e.getKey(), key)
                    && Objects.equal(e.getValue(), value);
        }

        @Override public final int hashCode() {
            return (key == null ? 0 : key.hashCode()) ^
                    (value == null ? 0 : value.hashCode());
        }

        @Override public final String toString() {
            return key + "=" + value;
        }
    }

    private abstract class HashIterator {
        int nextIndex;
        HashMapEntry<K, V> nextEntry = entryForNullKey;
        HashMapEntry<K, V> lastEntryReturned;
        int expectedModCount = modCount;

        HashIterator() {
            if (nextEntry == null) {
                HashMapEntry<K, V>[] tab = table;
                HashMapEntry<K, V> next = null;
                while (next == null && nextIndex < tab.length) {
                    next = tab[nextIndex++];
                }
                nextEntry = next;
            }
        }

        public boolean hasNext() {
            return nextEntry != null;
        }

        HashMapEntry<K, V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (nextEntry == null)
                throw new NoSuchElementException();

            HashMapEntry<K, V> entryToReturn = nextEntry;
            HashMapEntry<K, V>[] tab = table;
            HashMapEntry<K, V> next = entryToReturn.next;
            while (next == null && nextIndex < tab.length) {
                next = tab[nextIndex++];
            }
            nextEntry = next;
            return lastEntryReturned = entryToReturn;
        }

        public void remove() {
            if (lastEntryReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            HashMap.this.remove(lastEntryReturned.key);
            lastEntryReturned = null;
            expectedModCount = modCount;
        }
    }

    private final class KeyIterator extends HashIterator
            implements Iterator<K> {
        public K next() { return nextEntry().key; }
    }

    private final class ValueIterator extends HashIterator
            implements Iterator<V> {
        public V next() { return nextEntry().value; }
    }

    private final class EntryIterator extends HashIterator
            implements Iterator<Entry<K, V>> {
        public Entry<K, V> next() { return nextEntry(); }
    }

    /**
     * Returns true if this map contains the specified mapping.
     */
    private boolean containsMapping(Object key, Object value) {
        if (key == null) {
            HashMapEntry<K, V> e = entryForNullKey;
            return e != null && Objects.equal(value, e.value);
        }

        int hash = Collections.secondaryHash(key);
        HashMapEntry<K, V>[] tab = table;
        int index = hash & (tab.length - 1);
        for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
            if (e.hash == hash && key.equals(e.key)) {
                return Objects.equal(value, e.value);
            }
        }
        return false; // No entry for key
    }

    /**
     * Removes the mapping from key to value and returns true if this mapping
     * exists; otherwise, returns does nothing and returns false.
     *
     * Modified to avoid extra retain/autorelease calls.
     */
    private native boolean removeMapping(Object key, Object value) /*-[
      if (key == nil) {
        JavaUtilHashMap_HashMapEntry *e = self->entryForNullKey_;
        if (e == nil || !LibcoreUtilObjects_equalWithId_withId_(value, e->value_)) {
          return NO;
        }
        JavaUtilHashMap_set_entryForNullKey_(self, nil);
        self->modCount_++;
        self->size__--;
        [self postRemoveWithJavaUtilHashMap_HashMapEntry:e];
        return YES;
      }
      jint hash_ = JavaUtilCollections_secondaryHashWithId_(key);
      IOSObjectArray *tab = self->table_;
      jint index = hash_ & (tab->size_ - 1);
      for (JavaUtilHashMap_HashMapEntry *e = tab->buffer_[index], *prev = nil; e != nil;
          prev = e, e = e->next_) {
        if (e->hash__ == hash_ && [key isEqual:e->key_]) {
          if (!LibcoreUtilObjects_equalWithId_withId_(value, e->value_)) {
            return NO;
          }
          if (prev == nil) {
            tab->buffer_[index] = e->next_;
          } else {
            prev->next_ = e->next_;
          }
          e->next_ = nil;  // Balance the missing retain on e.next above.
          [e autorelease];  // Balance the missing release on e above.
          self->modCount_++;
          self->size__--;
          [self postRemoveWithJavaUtilHashMap_HashMapEntry:e];
          return YES;
        }
      }
      return NO;
    ]-*/;

    // Subclass (LinkedHashMap) overrides these for correct iteration order
    Iterator<K> newKeyIterator() { return new KeyIterator();   }
    Iterator<V> newValueIterator() { return new ValueIterator(); }
    Iterator<Entry<K, V>> newEntryIterator() { return new EntryIterator(); }

    private final class KeySet extends AbstractSet<K> {
        public Iterator<K> iterator() {
            return newKeyIterator();
        }
        public int size() {
            return size;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public boolean contains(Object o) {
            return containsKey(o);
        }
        public boolean remove(Object o) {
            int oldSize = size;
            HashMap.this.remove(o);
            return size != oldSize;
        }
        public void clear() {
            HashMap.this.clear();
        }

        /*-[
        - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                          objects:(__unsafe_unretained id *)stackbuf
                                            count:(NSUInteger)len {
          NSUInteger objCount =
              [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len];
          for (id *e = state->itemsPtr, *end = e + objCount; e < end; e++) {
            *e = ((JavaUtilHashMap_HashMapEntry *) *e)->key_;
          }
          return objCount;
        }
        ]-*/
    }

    private final class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return newValueIterator();
        }
        public int size() {
            return size;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public boolean contains(Object o) {
            return containsValue(o);
        }
        public void clear() {
            HashMap.this.clear();
        }

        /*-[
        - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                          objects:(__unsafe_unretained id *)stackbuf
                                            count:(NSUInteger)len {
          NSUInteger objCount =
              [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len];
          for (id *e = state->itemsPtr, *end = e + objCount; e < end; e++) {
            *e = ((JavaUtilHashMap_HashMapEntry *) *e)->value_;
          }
          return objCount;
        }
        ]-*/
    }

    private final class EntrySet extends AbstractSet<Entry<K, V>> {
        public Iterator<Entry<K, V>> iterator() {
            return newEntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Entry))
                return false;
            Entry<?, ?> e = (Entry<?, ?>) o;
            return containsMapping(e.getKey(), e.getValue());
        }
        public boolean remove(Object o) {
            if (!(o instanceof Entry))
                return false;
            Entry<?, ?> e = (Entry<?, ?>)o;
            return removeMapping(e.getKey(), e.getValue());
        }
        public int size() {
            return size;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public void clear() {
            HashMap.this.clear();
        }

        /*-[
        - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                          objects:(__unsafe_unretained id *)stackbuf
                                            count:(NSUInteger)len {
          return [this$0_ enumerateEntriesWithState:state objects:stackbuf count:len];
        }
        ]-*/
    }

    private static final long serialVersionUID = 362498820763181265L;

    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("loadFactor", float.class)
    };

    private void writeObject(ObjectOutputStream stream) throws IOException {
        // Emulate loadFactor field for other implementations to read
        ObjectOutputStream.PutField fields = stream.putFields();
        fields.put("loadFactor", DEFAULT_LOAD_FACTOR);
        stream.writeFields();

        stream.writeInt(table.length); // Capacity
        stream.writeInt(size);
        for (Entry<K, V> e : entrySet()) {
            stream.writeObject(e.getKey());
            stream.writeObject(e.getValue());
        }
    }

    private void readObject(ObjectInputStream stream) throws IOException,
            ClassNotFoundException {
        stream.defaultReadObject();
        int capacity = stream.readInt();
        if (capacity < 0) {
            throw new InvalidObjectException("Capacity: " + capacity);
        }
        if (capacity < MINIMUM_CAPACITY) {
            capacity = MINIMUM_CAPACITY;
        } else if (capacity > MAXIMUM_CAPACITY) {
            capacity = MAXIMUM_CAPACITY;
        } else {
            capacity = Collections.roundUpToPowerOfTwo(capacity);
        }
        makeTable(capacity);

        int size = stream.readInt();
        if (size < 0) {
            throw new InvalidObjectException("Size: " + size);
        }

        init(); // Give subclass (LinkedHashMap) a chance to initialize itself
        for (int i = 0; i < size; i++) {
            @SuppressWarnings("unchecked") K key = (K) stream.readObject();
            @SuppressWarnings("unchecked") V val = (V) stream.readObject();
            constructorPut(key, val);
        }
    }

    /*-[
    - (NSUInteger)enumerateEntriesWithState:(NSFastEnumerationState *)state
                                    objects:(__unsafe_unretained id *)stackbuf
                                      count:(NSUInteger)len {
      // Note: Must not use extra[4] because it is set by HashSet.
      if (state->state == 0) {
        state->state = 1;
        state->mutationsPtr = (unsigned long *) &modCount_;
        state->extra[0] = 0;
        state->extra[1] = 0;
      }
      NSUInteger position = state->extra[0];
      JavaUtilHashMap_HashMapEntry *entry = (JavaUtilHashMap_HashMapEntry *) state->extra[1];
      state->itemsPtr = stackbuf;
      NSUInteger objCount = 0;
      if (state->state == 1 && objCount < len) {
        state->state = 2;
        if (entryForNullKey_) {
          *stackbuf++ = entryForNullKey_;
          objCount++;
        }
      }
      while (objCount < len) {
        if (entry) {
          entry = entry->next_;
        }
        while (!entry && position < (NSUInteger) table_->size_) {
          entry = table_->buffer_[position++];
        }
        if (!entry) {
          break;
        }
        *stackbuf++ = entry;
        objCount++;
      }
      state->extra[0] = position;
      state->extra[1] = (unsigned long) entry;
      return objCount;
    }
    ]-*/
}


text:
require "chef/knife/cloud/service"

shared_examples_for Chef::Knife::Cloud::Service do |instance|

  describe "#connection" do
    it "creates a connection to fog service." do
      expect(instance).to receive(:add_api_endpoint)
      expect(Fog::Compute).to receive(:new)
      instance.connection
    end
  end

  describe "#delete_server" do
    it "deletes the server." do
      server = double
      allow(instance).to receive(:puts)
      allow(instance).to receive_message_chain(:connection, :servers, :get).and_return(server)
      expect(server).to receive(:name).ordered
      expect(server).to receive(:id).ordered
      allow(instance).to receive_message_chain(:ui, :confirm)
      expect(server).to receive(:destroy).ordered
      instance.delete_server(:server_name)
    end

    it "throws error message when the server cannot be located." do
      server_name = "invalid_server_name"
      error_message = "Could not locate server '#{server_name}'."
      allow(instance).to receive_message_chain(:connection, :servers, :get).and_return(nil)
      allow(instance).to receive_message_chain(:ui, :error).with(error_message)
      expect { instance.delete_server(server_name) }.to raise_error(Chef::Knife::Cloud::CloudExceptions::ServerDeleteError)
    end
  end

  describe "#create_server" do
    before do
      allow(instance).to receive(:puts)
      allow(instance).to receive(:print)
    end

    it "creates the server." do
      server = double
      allow(instance).to receive_message_chain(:connection, :servers, :create).and_return(server)
      allow(instance).to receive_message_chain(:ui, :color)
      expect(server).to receive(:wait_for)
      instance.create_server({ server_create_timeout: 600 })
    end
  end

  describe "#get_server" do
    it "return server." do
      server = double
      allow(instance).to receive_message_chain(:connection, :servers, :create).and_return(server)
      expect(instance.connection.servers).to receive(:get)
      instance.get_server("instance_id")
    end
  end

  describe "#server_summary" do
    it "show server details." do
      server = double
      instance.ui = double
      expect(instance.ui).to receive(:list)
      expect(server).to receive(:id)
      instance.server_summary(server, [{ label: "Instance ID", key: "id" }])
    end
  end
end


text:
"""
Support to allow pieces of code to request configuration from the user.

Initiate a request by calling the `request_config` method with a callback.
This will return a request id that has to be used for future calls.
A callback has to be provided to `request_config` which will be called when
the user has submitted configuration information.
"""
import logging

from homeassistant.const import EVENT_TIME_CHANGED, ATTR_FRIENDLY_NAME, \
    ATTR_ENTITY_PICTURE
from homeassistant.helpers.entity import generate_entity_id

_INSTANCES = {}
_LOGGER = logging.getLogger(__name__)
_REQUESTS = {}

ATTR_CONFIGURE_ID = 'configure_id'
ATTR_DESCRIPTION = 'description'
ATTR_DESCRIPTION_IMAGE = 'description_image'
ATTR_ERRORS = 'errors'
ATTR_FIELDS = 'fields'
ATTR_LINK_NAME = 'link_name'
ATTR_LINK_URL = 'link_url'
ATTR_SUBMIT_CAPTION = 'submit_caption'

DOMAIN = 'configurator'

ENTITY_ID_FORMAT = DOMAIN + '.{}'

SERVICE_CONFIGURE = 'configure'
STATE_CONFIGURE = 'configure'
STATE_CONFIGURED = 'configured'

def request_config(
        hass, name, callback, description=None, description_image=None,
        submit_caption=None, fields=None, link_name=None, link_url=None,
        entity_picture=None):
    """Create a new request for configuration.

    Will return an ID to be used for sequent calls.
    """
    instance = _get_instance(hass)

    request_id = instance.request_config(
        name, callback,
        description, description_image, submit_caption,
        fields, link_name, link_url, entity_picture)

    _REQUESTS[request_id] = instance

    return request_id

def notify_errors(request_id, error):
    """Add errors to a config request."""
    try:
        _REQUESTS[request_id].notify_errors(request_id, error)
    except KeyError:
        # If request_id does not exist
        pass

def request_done(request_id):
    """Mark a configuration request as done."""
    try:
        _REQUESTS.pop(request_id).request_done(request_id)
    except KeyError:
        # If request_id does not exist
        pass

def setup(hass, config):
    """Setup the configurator component."""
    return True

def _get_instance(hass):
    """Get an instance per hass object."""
    try:
        return _INSTANCES[hass]
    except KeyError:
        _INSTANCES[hass] = Configurator(hass)

        if DOMAIN not in hass.config.components:
            hass.config.components.append(DOMAIN)

        return _INSTANCES[hass]

class Configurator(object):
    """The class to keep track of current configuration requests."""

    def __init__(self, hass):
        """Initialize the configurator."""
        self.hass = hass
        self._cur_id = 0
        self._requests = {}
        hass.services.register(
            DOMAIN, SERVICE_CONFIGURE, self.handle_service_call)

    def request_config(
            self, name, callback,
            description, description_image, submit_caption,
            fields, link_name, link_url, entity_picture):
        """Setup a request for configuration."""
        entity_id = generate_entity_id(ENTITY_ID_FORMAT, name, hass=self.hass)

        if fields is None:
            fields = []

        request_id = self._generate_unique_id()

        self._requests[request_id] = (entity_id, fields, callback)

        data = {
            ATTR_CONFIGURE_ID: request_id,
            ATTR_FIELDS: fields,
            ATTR_FRIENDLY_NAME: name,
            ATTR_ENTITY_PICTURE: entity_picture,
        }

        data.update({
            key: value for key, value in [
                (ATTR_DESCRIPTION, description),
                (ATTR_DESCRIPTION_IMAGE, description_image),
                (ATTR_SUBMIT_CAPTION, submit_caption),
                (ATTR_LINK_NAME, link_name),
                (ATTR_LINK_URL, link_url),
            ] if value is not None
        })

        self.hass.states.set(entity_id, STATE_CONFIGURE, data)

        return request_id

    def notify_errors(self, request_id, error):
        """Update the state with errors."""
        if not self._validate_request_id(request_id):
            return

        entity_id = self._requests[request_id][0]

        state = self.hass.states.get(entity_id)

        new_data = dict(state.attributes)
        new_data[ATTR_ERRORS] = error

        self.hass.states.set(entity_id, STATE_CONFIGURE, new_data)

    def request_done(self, request_id):
        """Remove the configuration request."""
        if not self._validate_request_id(request_id):
            return

        entity_id = self._requests.pop(request_id)[0]

        # If we remove the state right away, it will not be included with
        # the result fo the service call (current design limitation).
        # Instead, we will set it to configured to give as feedback but delete
        # it shortly after so that it is deleted when the client updates.
        self.hass.states.set(entity_id, STATE_CONFIGURED)

        def deferred_remove(event):
            """Remove the request state."""
            self.hass.states.remove(entity_id)

        self.hass.bus.listen_once(EVENT_TIME_CHANGED, deferred_remove)

    def handle_service_call(self, call):
        """Handle a configure service call."""
        request_id = call.data.get(ATTR_CONFIGURE_ID)

        if not self._validate_request_id(request_id):
            return

        # pylint: disable=unused-variable
        entity_id, fields, callback = self._requests[request_id]

        # field validation goes here?

        callback(call.data.get(ATTR_FIELDS, {}))

    def _generate_unique_id(self):
        """Generate a unique configurator ID."""
        self._cur_id += 1
        return "{}-{}".format(id(self), self._cur_id)

    def _validate_request_id(self, request_id):
        """Validate that the request belongs to this instance."""
        return request_id in self._requests


text:
package com.yofc.odn.contract.service.impl;

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

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.yofc.odn.common.model.Fibertype;
import com.yofc.odn.common.model.Staff;
import com.yofc.odn.contract.dao.ContractDao;
import com.yofc.odn.contract.dao.FibertypeDao;
import com.yofc.odn.contract.dao.SegmentnumDao;
import com.yofc.odn.contract.dao.SpecificationnumDao;
import com.yofc.odn.contract.model.Contract;
import com.yofc.odn.contract.model.Segmentnum;
import com.yofc.odn.contract.model.Specificationnum;
import com.yofc.odn.contract.service.ContractService;
import com.yofc.odn.contract.util.GetSegment;
@Component(value="contractContractService")
public class ContractServiceImpl implements ContractService {
	private ContractDao contractDao;
	private FibertypeDao fibertypeDao;
	private SpecificationnumDao specificationnumDao;
	private SegmentnumDao segmentnumDao;
	@Resource(name="contractFibertypeDaoImpl")
	public void setFibertypeDao(FibertypeDao fibertypeDao) {
		this.fibertypeDao = fibertypeDao;
	}
	@Resource(name="contractSpecificationnumDao")
	public void setSpecificationnumDao(SpecificationnumDao specificationnumDao) {
		this.specificationnumDao = specificationnumDao;
	}
	@Resource(name="contractContractDao")
	public void setContractDao(ContractDao contractDao) {
		this.contractDao = contractDao;
	}
	@Resource(name="contractSegmentnumDao")
	public void setSegmentnumDao(SegmentnumDao segmentnumDao) {
		this.segmentnumDao = segmentnumDao;
	}
	@Override
	public Contract get(int id) {

		return 	this.contractDao.get(id);
	}
	@Override
	public Contract getByContractNum(String num) {

		return this.contractDao.getByContractNum(num);
	}
	//保存合同方法,  这个方法属于一个事务,如果中途出错,或者返回false,则事物回滚。待解决
	public boolean addContract(String contractNum, String person, String address,
		String contacter, List<String> supplyNotes, List<Date> dueTime, String contactPhone,
		String companyPhone, List<String> fiberfModel,
		List<Float> perLength, List<Integer> plateNums,
		List<Integer> perTotal, Staff staff, List<String> paths) {
		boolean flag = false;

		// 初始化  合同  contract
		Contract contract = new Contract();
		contract.setContractNum(contractNum);
		contract.setPerson(person);
		contract.setAddress(address);
		contract.setContacter(contacter);
		contract.setContactPhone(contactPhone);
		contract.setCompanyPhone(companyPhone);

		//在这里保存附件
		if(paths.size()>0)
		{
			contract.setContractAttach(paths.get(0));    //  设置附件
		}

		contract.setIsFinished(0);
		contract.setStaff(staff);
		contract.setInputTime(new Date());
		flag = contractDao.save(contract);
		if(flag == false){return false;}
		int num =0;
		int j;
		for(int i = 0; i < perTotal.size(); i++){//遍历规格
			//1、先找到光纤型号 fibertype
			Fibertype fibertype = this.fibertypeDao.findOneByModel(fiberfModel.get(i));
			String typeNameFlag = fibertype.getTypeNameFlag();  //得到规格标识 J  H  D
			System.out.println(typeNameFlag);
			List<Integer> nums = new ArrayList<Integer>();  //得到该规格下的 盘数  例如 2  3  4  等等之类
			float totalLength = 0.0f;
			//2、初始化 specificationnum
			Specificationnum specificationnum = new Specificationnum();
			specificationnum.setContract(contract);
			specificationnum.setIsFinished(0);
			specificationnum.setDeadTime(dueTime.get(i));//设置到期时间
			specificationnum.setSupplyNote(supplyNotes.get(i));//设置描述
			specificationnum.setFibertype(fibertype);//设置光纤型号
			specificationnum.setDeviation(0.1f);    //  TODO   从前台传过来
			//3、解析出  盘数,每盘长,求出总长度
			j = num;
			num += perTotal.get(i);
			for(; j < num; j++){
				//计算总长度
				totalLength = totalLength + perLength.get(j)*plateNums.get(j);
				//顺便解析出该规格下的总盘数
				nums.add(plateNums.get(j));
			}
			specificationnum.setTotalLength(totalLength);
			//4、保存specificationnum
			flag = this.specificationnumDao.save(specificationnum);
			if(flag == false){return false;}
			//5、分配段长号,并且保存
			List<String> segmentNums = GetSegment.generatedSegmentNums(typeNameFlag, nums);//计算出所有的规格号
			//int currentSegNumOffset = 0;	//当前段长号偏移量
			j = num - perTotal.get(i);
			int currentSegNumOffset = 0; //该规格号内当前盘数偏移量
			for(; j < num; j++){
				//得到盘数
				for(int n = 0;n < plateNums.get(j); n++){//这里生成段长号,并且保存
					//初始化段长号
					Segmentnum seg = new Segmentnum();
					seg.setSegmentNum(segmentNums.get(currentSegNumOffset));	//设置段长号码
				    seg.setStatus(0); 				//设置状态    初始化
					seg.setSpecificationnum(specificationnum);			//设置属于哪个规格
					seg.setLength(perLength.get(j));					//设置盘长
					seg.setStepinfo(fibertype.getStepsequence().getStepinfo());	//设置步骤信息
					flag = this.segmentnumDao.save(seg);
					if(flag == false){return false;}
					currentSegNumOffset += 1;
				}
			}
		}
		return true;
	}

	@Override
	/*
	 * 获取合同列表
	 */
	public List<Contract> getContract(){
		return this.contractDao.getContract();
	}
/*	@Override
	public void upDataContract(String contractNum, String filePath,
			String uploadFileType) {
		//1、先拿到contract
		Contract contract = this.contractDao.getByContractNum(contractNum);
		//2、先判断 ,  在调用contract.set...();
		if("contractAttach".equals(uploadFileType)){
			contract.setContractAttach(filePath);
		}
		if("craftAttach".equals(uploadFileType)){
			//3、在更新
			contract.setCraftAttach(filePath);
		}
		// TODO Auto-generated method stub
		this.contractDao.update(contract);
	}	*/
	@Override
	public boolean validContractNumExist(String num) {
		return this.contractDao.validContractNumExist(num);
	}

}


text:
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import input_array_choice_mixin # need this for constants
reload(input_array_choice_mixin)
from input_array_choice_mixin import InputArrayChoiceMixin

class warpPoints(ScriptedConfigModuleMixin, InputArrayChoiceMixin,
                 ModuleBase):

    _defaultVectorsSelectionString = 'Default Active Vectors'
    _userDefinedString = 'User Defined'

    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)
        InputArrayChoiceMixin.__init__(self)

        self._config.scaleFactor = 1

        configList = [
            ('Scale factor:', 'scaleFactor', 'base:float', 'text',
             'The warping will be scaled by this factor'),
            ('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
             'The attribute that will be used as vectors for the warping.',
             (self._defaultVectorsSelectionString, self._userDefinedString))]

        self._warpVector = vtk.vtkWarpVector()

        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkWarpVector' : self._warpVector})

        module_utils.setup_vtk_object_progress(self, self._warpVector,
                                           'Warping points.')

        self.sync_module_logic_with_config()

    def close(self):
        # we play it safe... (the graph_editor/module_manager should have
        # disconnected us by now)
        for input_idx in range(len(self.get_input_descriptions())):
            self.set_input(input_idx, None)

        # this will take care of all display thingies
        ScriptedConfigModuleMixin.close(self)

        # get rid of our reference
        del self._warpVector

    def execute_module(self):
        self._warpVector.Update()

        if self.view_initialised:
            # second element in configuration list
            choice = self._getWidget(1)
            self.iac_execute_module(self._warpVector, choice, 0)

    def get_input_descriptions(self):
        return ('VTK points/polydata with vector attribute',)

    def set_input(self, idx, inputStream):
        if inputStream is None:
            self._warpVector.SetInputConnection(0, None)
        else:
            self._warpVector.SetInput(inputStream)

    def get_output_descriptions(self):
        return ('Warped data',)

    def get_output(self, idx):
        # we only return something if we have something
        if self._warpVector.GetNumberOfInputConnections(0):
            return self._warpVector.GetOutput()
        else:
            return None

    def logic_to_config(self):
        self._config.scaleFactor = self._warpVector.GetScaleFactor()

        # this will extract the possible choices
        self.iac_logic_to_config(self._warpVector, 0)

    def config_to_view(self):
        # first get our parent mixin to do its thing
        ScriptedConfigModuleMixin.config_to_view(self)

        # the vector choice is the second configTuple
        choice = self._getWidget(1)
        self.iac_config_to_view(choice)

    def config_to_logic(self):
        self._warpVector.SetScaleFactor(self._config.scaleFactor)

        self.iac_config_to_logic(self._warpVector, 0)


text:
package org.codingcore.mc.tquest.inventory;

import org.codingcore.mc.tquest.inventory.slots.SlotMachine;
import org.codingcore.mc.tquest.tileentities.TileEntityMachine;

import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;

/**
 * Project: TechQuest

 * File: ContainerTest.java
 *
 * @author  Matthew Rogers
 */
public class ContainerTest extends ContainerMachine {

    public ContainerTest(InventoryPlayer par1Inventory, TileEntityMachine par2TileEntity) {
        super(par1Inventory, par2TileEntity);
    }

    @Override
    protected void addSlots(InventoryPlayer playerInventory, TileEntityMachine tileentity) {
        addSlotToContainer(new Slot(tileentity, INPUTS[0], 56, 20));
        addSlotToContainer(new Slot(tileentity, FUEL, 56, 53));
        addSlotToContainer(new SlotMachine(playerInventory.player, tileentity, OUTPUT, 116, 35));
    }
}