text:
package com.blueprint.centromere.ws.controller;

import com.blueprint.centromere.core.exceptions.ModelRegistryException;
import com.blueprint.centromere.core.model.Model;
import com.blueprint.centromere.core.repository.ModelRepository;
import com.blueprint.centromere.core.repository.ModelRepositoryRegistry;
import com.blueprint.centromere.core.repository.QueryCriteria;
import com.blueprint.centromere.ws.config.ApiMediaTypes;
import com.blueprint.centromere.ws.config.ModelResourceRegistry;
import com.blueprint.centromere.ws.exception.InvalidParameterException;
import com.blueprint.centromere.ws.exception.ResourceNotFoundException;
import com.blueprint.centromere.ws.exception.RestError;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Controller methods for generic {@link Model} implementations and their search methods
 *
 * @author woemler
 * @since 0.5.0
 */
@Controller
@RequestMapping("${centromere.web.api.root-url}/aggregation")
@SuppressWarnings({"unchecked", "SpringJavaAutowiringInspection"})
public class ModelAggregationController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ModelAggregationController.class);

    @Autowired
    private ModelResourceRegistry resourceRegistry;

    @Autowired
    private ModelRepositoryRegistry repositoryRegistry;

    @Value("${centromere.web.api.root-url}")
    private String rootUrl;

    /**
     * {@code GET /api/aggregation/{model}/distinct/{field}}
     * Fetches the distinct values of the model attribute, {@code field}, which fulfill the given
     *   query options.
     *
     * @param field Name of the model attribute to retrieve unique values of.
     * @param request {@link HttpServletRequest}
     * @return List of distinct field values.
     */
    @ApiResponses({
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 400, message = "Invalid options", response = RestError.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = RestError.class),
        @ApiResponse(code = 404, message = "Resource not found.", response = RestError.class)
    })
    @RequestMapping(
        value = "/{uri}/distinct/{field}",
        method = RequestMethod.GET,
        produces = { ApiMediaTypes.APPLICATION_HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE,
            ApiMediaTypes.APPLICATION_HAL_XML_VALUE, MediaType.APPLICATION_XML_VALUE,
            MediaType.TEXT_PLAIN_VALUE })
    public <T extends Model<I>, I extends Serializable> ResponseEntity<ResponseEnvelope> findDistinct(
        @PathVariable("field") String field,
        @PathVariable("uri") String uri,
        HttpServletRequest request) {

        Class<T> model;
        try {
            if (!resourceRegistry.isRegisteredResource(uri)) {
                LOGGER.error(String.format("URI does not map to a registered model: %s", uri));
                throw new ResourceNotFoundException();
            }
            model = (Class<T>) resourceRegistry.getModelByUri(uri);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        BeanWrapper wrapper = new BeanWrapperImpl(model);
        if (!wrapper.isReadableProperty(field)) {
            throw new InvalidParameterException(String.format("Requested field is not a valid model property: %s", field));
        }

        ModelRepository<T, I> repository;
        try {
            repository = (ModelRepository<T, I>) repositoryRegistry.getRepositoryByModel(model);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        List<QueryCriteria> queryCriterias = RequestUtils.getQueryCriteriaFromFindDistinctRequest(model, request);
        Set<Object> distinct = repository.distinct(field, queryCriterias);
        ResponseEnvelope envelope = null;

        if (ApiMediaTypes.isHalMediaType(request.getHeader("Accept"))) {

            Link selfLink = new Link(rootUrl + "/aggregation/" + uri + "/distinct/" + field +
                (request.getQueryString() != null ? "?" + request.getQueryString() : ""), "self");
            Resources<Object> resources = new Resources<>(distinct);
            resources.add(selfLink);
            envelope = new ResponseEnvelope(resources);

        } else {

            envelope = new ResponseEnvelope(distinct);

        }

        return new ResponseEntity<>(envelope, HttpStatus.OK);
    }

    /**
     * {@code GET /api/aggregation/{model}/count}
     * Fetches the count of records for the requested model, which fulfill the given
     *   query options.
     *
     * @param request {@link HttpServletRequest}
     * @return The count of records that satisfy the query.
     */
    @ApiResponses({
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 400, message = "Invalid options", response = RestError.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = RestError.class),
        @ApiResponse(code = 404, message = "Resource not found.", response = RestError.class)
    })
    @RequestMapping(
        value = "/{uri}/count",
        method = RequestMethod.GET,
        produces = { ApiMediaTypes.APPLICATION_HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE,
            ApiMediaTypes.APPLICATION_HAL_XML_VALUE, MediaType.APPLICATION_XML_VALUE,
            MediaType.TEXT_PLAIN_VALUE })
    public <T extends Model<I>, I extends Serializable> ResponseEntity<ResponseEnvelope> count(
        @PathVariable("uri") String uri,
        HttpServletRequest request) {

        Class<T> model;

        try {
            if (!resourceRegistry.isRegisteredResource(uri)) {
                LOGGER.error(String.format("URI does not map to a registered model: %s", uri));
                throw new ResourceNotFoundException();
            }
            model = (Class<T>) resourceRegistry.getModelByUri(uri);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        ModelRepository<T, I> repository;
        try {
            repository = (ModelRepository<T, I>) repositoryRegistry.getRepositoryByModel(model);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        List<QueryCriteria> queryCriterias = RequestUtils.getQueryCriteriaFromFindDistinctRequest(model, request);
        Long count = repository.count(queryCriterias);
        Map<String, Object> responseObject = Collections.singletonMap("count", count);
        ResponseEnvelope envelope;

        if (ApiMediaTypes.isHalMediaType(request.getHeader("Accept"))) {
            Link selfLink = new Link(rootUrl + "/aggregation/" + uri + "/count" +
                (request.getQueryString() != null ? "?" + request.getQueryString() : ""), "self");
            Resource<Object> resource = new Resource<>(responseObject);
            resource.add(selfLink);
            envelope = new ResponseEnvelope(resource);
        } else {
            envelope = new ResponseEnvelope(responseObject);
        }

        return new ResponseEntity<>(envelope, HttpStatus.OK);

    }

    /**
     * {@code GET /api/aggregation/{model}/group/{field}}
     * Fetches a collection of records, grouped by the requested field.
     *
     * @param field Name of the model attribute to group records by.
     * @param request {@link HttpServletRequest}
     * @return List of grouped records.
     */
    @ApiResponses({
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 400, message = "Invalid options", response = RestError.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = RestError.class),
        @ApiResponse(code = 404, message = "Resource not found.", response = RestError.class)
    })
    @RequestMapping(
        value = "/{uri}/group/{field}",
        method = RequestMethod.GET,
        produces = { ApiMediaTypes.APPLICATION_HAL_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE,
            ApiMediaTypes.APPLICATION_HAL_XML_VALUE, MediaType.APPLICATION_XML_VALUE,
            MediaType.TEXT_PLAIN_VALUE })
    public <T extends Model<I>, I extends Serializable> ResponseEntity<ResponseEnvelope> groupBy(
        @PathVariable("field") String field,
        @PathVariable("uri") String uri,
        HttpServletRequest request) {

        Class<T> model;
        try {
            if (!resourceRegistry.isRegisteredResource(uri)) {
                LOGGER.error(String.format("URI does not map to a registered model: %s", uri));
                throw new ResourceNotFoundException();
            }
            model = (Class<T>) resourceRegistry.getModelByUri(uri);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        BeanWrapper wrapper = new BeanWrapperImpl(model);
        if (!wrapper.isReadableProperty(field)) {
            throw new InvalidParameterException(String.format("Requested field is not a valid model property: %s", field));
        }

        ModelRepository<T, I> repository;
        try {
            repository = (ModelRepository<T, I>) repositoryRegistry.getRepositoryByModel(model);
        } catch (ModelRegistryException e) {
            e.printStackTrace();
            throw new ResourceNotFoundException();
        }

        List<QueryCriteria> queryCriterias = RequestUtils.getQueryCriteriaFromFindDistinctRequest(model, request);
        Map<Object, List<T>> grouped = new LinkedHashMap<>();
        for (T record: repository.find(queryCriterias)) {
            wrapper = new BeanWrapperImpl(record);
            Object fieldValue = wrapper.getPropertyValue(field);
            List<T> recordList = new ArrayList<>();
            if (grouped.containsKey(fieldValue)) {
                recordList = grouped.get(fieldValue);
            }
            recordList.add(record);
            grouped.put(fieldValue, recordList);
        }

        ResponseEnvelope envelope;

        if (ApiMediaTypes.isHalMediaType(request.getHeader("Accept"))) {

            Link selfLink = new Link(rootUrl + "/aggregation/" + uri + "/group/" + field +
                (request.getQueryString() != null ? "?" + request.getQueryString() : ""), "self");
            Resource<Object> resource = new Resource<>(grouped);
            resource.add(selfLink);
            envelope = new ResponseEnvelope(resource);

        } else {

            envelope = new ResponseEnvelope(grouped);

        }

        return new ResponseEntity<>(envelope, HttpStatus.OK);
    }

}


text:
layout: post
title: Backup raspberry pi image
date: 2014-08-30 10:00:10
published: True
categories: ['raspberry pi']
tags: []
---

Creating a disk image will preserve not only files but also the filesystem structure and when you decide to flash your new SD card, you will be able to just plug it in and it will work.

Mac
Plug in your SD card and find out the disk name by enter diskutil list and then:
{% highlight bash %}
$ sudo dd if=/dev/rdiskx of=/path/to/new_backup_image.img bs=1m
{% endhighlight %}
Where /dev/rdiskx is your SD card.

To restore the image, just type:
{% highlight bash %}
$ diskutil unmount /dev/disk1sx
$ sudo dd if=/path/to/new_backup_image.img of=/dev/rdiskx bs=1m
{% endhighlight %}

[That's all folks](https://www.youtube.com/watch?v=gBzJGckMYO4)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->
<resources>
    <color name="chat_msg">#ff000000</color>
    <color name="chat_msg_presence">#ffad45d6</color>
    <color name="chat_contact">#000</color>
    <color name="nonchat_contact">#fff</color>
    <color name="status_popup_text">#ff000000</color>
    <color name="error">#ffcc5555</color>
</resources>


text:
@extends('layouts.app')

@section('content')

                <profile-work-edit :user="{{$user}}"></profile-work-edit>

@endsection


text:
namespace ash {

WindowSelectorController::WindowSelectorController() {
}

WindowSelectorController::~WindowSelectorController() {
}

// static
bool WindowSelectorController::CanSelect() {
  // Don't allow a window overview if the screen is locked or a modal dialog is
  // open or running in kiosk app session.
  return !Shell::GetInstance()->session_state_delegate()->IsScreenLocked() &&
         !Shell::GetInstance()->IsSystemModalWindowOpen() &&
         Shell::GetInstance()->system_tray_delegate()->GetUserLoginStatus() !=
             user::LOGGED_IN_KIOSK_APP;
}

void WindowSelectorController::ToggleOverview() {
  if (IsSelecting()) {
    OnSelectionCanceled();
  } else {
    // Don't start overview if window selection is not allowed.
    if (!CanSelect())
      return;

    std::vector<aura::Window*> windows = ash::Shell::GetInstance()->
        mru_window_tracker()->BuildMruWindowList();
    // Don't enter overview mode with no windows.
    if (windows.empty())
      return;

    window_selector_.reset(
        new WindowSelector(windows, WindowSelector::OVERVIEW, this));
    OnSelectionStarted();
  }
}

void WindowSelectorController::HandleCycleWindow(
    WindowSelector::Direction direction) {
  if (!CanSelect())
    return;

  if (!IsSelecting()) {
    std::vector<aura::Window*> windows = ash::Shell::GetInstance()->
        mru_window_tracker()->BuildMruWindowList();
    // Don't cycle with no windows.
    if (windows.empty())
      return;

    window_selector_.reset(
        new WindowSelector(windows, WindowSelector::CYCLE, this));
    OnSelectionStarted();
  }
  window_selector_->Step(direction);
}

bool WindowSelectorController::IsSelecting() {
  return window_selector_.get() != NULL;
}

void WindowSelectorController::OnWindowSelected(aura::Window* window) {
  wm::ActivateWindow(window);
  window_selector_.reset();
  last_selection_time_ = base::Time::Now();
  Shell::GetInstance()->mru_window_tracker()->SetIgnoreActivations(false);
}

void WindowSelectorController::OnSelectionCanceled() {
  window_selector_.reset();
  last_selection_time_ = base::Time::Now();
  Shell::GetInstance()->mru_window_tracker()->SetIgnoreActivations(false);
}

void WindowSelectorController::OnSelectionStarted() {
  Shell::GetInstance()->mru_window_tracker()->SetIgnoreActivations(true);
  Shell* shell = Shell::GetInstance();
  shell->metrics()->RecordUserMetricsAction(UMA_WINDOW_SELECTION);
  if (!last_selection_time_.is_null()) {
    UMA_HISTOGRAM_LONG_TIMES(
        "Ash.WindowSelector.TimeBetweenUse",
        base::Time::Now() - last_selection_time_);
  }
}

}  // namespace ash


text:
namespace tzw
{
	class PTMTown;

	class PTMTownGUI: public Singleton<PTMTownGUI>
	{
	public:
		PTMTownGUI();
		void showInspectTown(PTMTown * newTown);
		void updateGraphics();
		void initGUI();
	private:
		GUIWindow * m_townWindow;
		LabelNew * m_name;
		LabelNew * m_ecoLevel;
		LabelNew * m_milLevel;
		Button * m_buildArmy;
		Button * m_investEco;
		Button * m_investMil;
		PTMTown * m_inspectTown;
	};

}


text:
namespace StockQuant.Models
{
    public class ProfitLoss
    {
        public double Ratio { get; set; }

        public double Amount { get; set; }
    }
}


text:
package com.amazonaws.mturk.service.exception;

@SuppressWarnings("serial")
public class ServiceException extends RuntimeException {

    //-------------------------------------------------------------
    // Constructors
    //-------------------------------------------------------------

    public ServiceException() {
    }

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
namespace Server.Commands {
	public interface IAbortableCommand {
		void Abort();
	}
}


text:
package search

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

const (
	// Time allowed to write a message to the peer.
	writeWait = 10 * time.Second

	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second

	// Send pings to peer with this period. Must be less than pongWait.
	pingPeriod = (pongWait * 9) / 10

	// Maximum message size allowed from peer.
	maxMessageSize = 10 << 10
)

var debug, _ = strconv.ParseBool(os.Getenv("CAMLI_DEBUG"))

type wsHub struct {
	sh             *Handler
	register       chan *wsConn
	unregister     chan *wsConn
	watchReq       chan watchReq
	newBlobRecv    chan string // new blob received. string is camliType.
	updatedResults chan *watchedQuery
	statusUpdate   chan json.RawMessage

	// Owned by func run:
	conns map[*wsConn]bool
}

func newWebsocketHub(sh *Handler) *wsHub {
	return &wsHub{
		sh:             sh,
		register:       make(chan *wsConn), // unbuffered; issue 563
		unregister:     make(chan *wsConn), // unbuffered; issue 563
		conns:          make(map[*wsConn]bool),
		watchReq:       make(chan watchReq, buffered),
		newBlobRecv:    make(chan string, buffered),
		updatedResults: make(chan *watchedQuery, buffered),
		statusUpdate:   make(chan json.RawMessage, buffered),
	}
}

func (h *wsHub) run() {
	var lastStatusMsg []byte
	for {
		select {
		case st := <-h.statusUpdate:
			const prefix = `{"tag":"_status","status":`
			lastStatusMsg = make([]byte, 0, len(prefix)+len(st)+1)
			lastStatusMsg = append(lastStatusMsg, prefix...)
			lastStatusMsg = append(lastStatusMsg, st...)
			lastStatusMsg = append(lastStatusMsg, '}')
			for c := range h.conns {
				c.send <- lastStatusMsg
			}
		case c := <-h.register:
			h.conns[c] = true
			c.send <- lastStatusMsg
		case c := <-h.unregister:
			delete(h.conns, c)
			close(c.send)
		case camliType := <-h.newBlobRecv:
			if camliType == "" {
				// TODO: something smarter. some
				// queries might care about all blobs.
				// But for now only re-kick off
				// queries if schema blobs arrive.  We
				// should track per-WatchdQuery which
				// blob types the search cares about.
				continue
			}
			// New blob was received. Kick off standing search queries to see if any changed.
			for conn := range h.conns {
				for _, wq := range conn.queries {
					go h.redoSearch(wq)
				}
			}
		case wr := <-h.watchReq:
			// Unsubscribe
			if wr.q == nil {
				delete(wr.conn.queries, wr.tag)
				log.Printf("Removed subscription for %v, %q", wr.conn, wr.tag)
				continue
			}
			// Very similar type, but semantically
			// different, so separate for now:
			wq := &watchedQuery{
				conn: wr.conn,
				tag:  wr.tag,
				q:    wr.q,
			}
			wr.conn.queries[wr.tag] = wq
			if debug {
				log.Printf("websocket: added/updated search subscription for tag %q", wr.tag)
			}
			go h.doSearch(wq)

		case wq := <-h.updatedResults:
			if !h.conns[wq.conn] || wq.conn.queries[wq.tag] == nil {
				// Client has since disconnected or unsubscribed.
				continue
			}
			wq.mu.Lock()
			lastres := wq.lastres
			wq.mu.Unlock()
			resb, err := json.Marshal(wsUpdateMessage{
				Tag:    wq.tag,
				Result: lastres,
			})
			if err != nil {
				panic(err)
			}
			wq.conn.send <- resb
		}
	}
}

// redoSearch is called (in its own goroutine) when a new schema blob
// arrives to note that wq might now have new results and we should
// re-run it.  But because a search can take awhile, don't run more
// than one refresh at a time.
func (h *wsHub) redoSearch(wq *watchedQuery) {
	wq.mu.Lock()
	defer wq.mu.Unlock()
	wq.dirty = true
	if wq.refreshing {
		// Somebody else is already refreshing.
		// One's enough.
		return
	}
	for wq.dirty {
		wq.refreshing = true
		wq.dirty = false
		wq.mu.Unlock() // release lock while running query; might become dirty meanwhile
		h.doSearch(wq)
		wq.mu.Lock() // before checking wq.dirty
	}
	wq.refreshing = false
}

func (h *wsHub) doSearch(wq *watchedQuery) {
	// Make our own copy, in case
	q := new(SearchQuery)
	*q = *wq.q // shallow copy, since Query will mutate its internal state fields
	if q.Describe != nil {
		q.Describe = new(DescribeRequest)
		*q.Describe = *wq.q.Describe
	}

	res, err := h.sh.Query(context.TODO(), q)
	if err != nil {
		log.Printf("Query error: %v", err)
		return
	}
	resj, _ := json.Marshal(res)

	wq.mu.Lock()
	eq := bytes.Equal(wq.lastresj, resj)
	wq.lastres = res
	wq.lastresj = resj
	wq.mu.Unlock()
	if eq {
		// No change in search. Ignore.
		return
	}
	h.updatedResults <- wq
}

type wsConn struct {
	ws   *websocket.Conn
	send chan []byte // Buffered channel of outbound messages.
	sh   *Handler

	// queries is owned by the wsHub.run goroutine.
	queries map[string]*watchedQuery // tag -> subscription
}

type watchedQuery struct {
	conn *wsConn
	tag  string
	q    *SearchQuery

	mu         sync.Mutex // guards following
	refreshing bool       // search is currently running
	dirty      bool       // new schema blob arrived while refreshing; another refresh due
	lastres    *SearchResult
	lastresj   []byte // as JSON
}

// watchReq is a (un)subscribe request.
type watchReq struct {
	conn *wsConn
	tag  string       // required
	q    *SearchQuery // if nil, subscribe
}

// Client->Server subscription message.
type wsClientMessage struct {
	// Tag is required.
	Tag string `json:"tag"`
	// Query is required to subscribe. If absent, it means unsubscribe.
	Query *SearchQuery `json:"query,omitempty"`
}

type wsUpdateMessage struct {
	Tag    string        `json:"tag"`
	Result *SearchResult `json:"result,omitempty"`
}

// readPump pumps messages from the websocket connection to the hub.
func (c *wsConn) readPump() {
	defer func() {
		c.sh.wsHub.unregister <- c
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(pongWait))
	c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.ws.ReadMessage()
		if err != nil {
			break
		}
		if debug {
			log.Printf("websocket: got message %#q", message)
		}
		cm := new(wsClientMessage)
		if err := json.Unmarshal(message, cm); err != nil {
			log.Printf("Ignoring bogus websocket message. Err: %v", err)
			continue
		}
		c.sh.wsHub.watchReq <- watchReq{
			conn: c,
			tag:  cm.Tag,
			q:    cm.Query,
		}
	}
}

// write writes a message with the given message type and payload.
func (c *wsConn) write(mt int, payload []byte) error {
	c.ws.SetWriteDeadline(time.Now().Add(writeWait))
	return c.ws.WriteMessage(mt, payload)
}

// writePump pumps messages from the hub to the websocket connection.
func (c *wsConn) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.ws.Close()
	}()
	for {
		select {
		case message, ok := <-c.send:
			if !ok {
				c.write(websocket.CloseMessage, []byte{})
				return
			}
			if err := c.write(websocket.TextMessage, message); err != nil {
				return
			}
		case <-ticker.C:
			if err := c.write(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}

// upgrader is used in serveWebSocket to construct websocket connections.
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	// uses a default origin check policy
}

func (sh *Handler) serveWebSocket(rw http.ResponseWriter, req *http.Request) {
	ws, err := upgrader.Upgrade(rw, req, nil)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(rw, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	c := &wsConn{
		ws:      ws,
		send:    make(chan []byte, 256),
		sh:      sh,
		queries: make(map[string]*watchedQuery),
	}
	sh.wsHub.register <- c
	go c.writePump()
	c.readPump()
}


text:
//     Project: angulate2
// Description: Macro base for classes decorated with TypeScript annotations

// Copyright (c) 2016 Johannes.Kastner <jokade@karchedon.de>
//               Distributed under the MIT License (see included LICENSE file)
package angulate2.internal

import angulate2.ext.ClassMode
import de.surfice.smacrotools.{MacroAnnotationHandler}

import scala.language.reflectiveCalls

abstract class ClassDecorator extends MacroAnnotationHandler
  with AngulateWhiteboxMacroTools {

  import c.universe._

  override def supportsClasses: Boolean = true
  override def supportsTraits: Boolean = false
  override def supportsObjects: Boolean = false
  override def createCompanion: Boolean = true

  type Metadata = Map[String,String]
  type MainAnnotationParams = Map[String,Tree]

  case class ClassDecoratorData(objName: String,
                                decorators: Seq[Tree],
                                metadata: Metadata,
                                userDefinedCompanion: Boolean,
                                classMode: ClassMode.Value,
                                annotParams: MainAnnotationParams,
                                sjsxStatic: Seq[(Int,String)] = Nil
                               ) {
    def addSjsxStatic(js: (Int,String)*): ClassDecoratorData =
      copy(sjsxStatic = sjsxStatic ++ js)
    def jsAccessor: String = s"$exports.$objName"
  }
  object ClassDecoratorData {
    def apply(data: Data): ClassDecoratorData = data("decoratorData").asInstanceOf[ClassDecoratorData]
    def update(data: Data, cdd: ClassDecoratorData): Data = data + ("decoratorData" -> cdd)
    def addSjsxStatic(data: Data, js: Seq[(Int,String)]): Data = {
      val cdd = ClassDecoratorData(data)
      update(data,cdd.copy(sjsxStatic = cdd.sjsxStatic++js))
    }
    def updAnnotParam(data: Data, key: String, value: Tree): Data = {
      val cdd = ClassDecoratorData(data)
      update(data,cdd.copy(annotParams = cdd.annotParams + (key->value)))
    }
  }

  // Prefix for accessing the Scala module's exports object from within the sjsx module
  protected val exports = "s"

  def mainAnnotationObject: Tree

  /** Names of the parameters in the last argument list of the main annotation
   * (in the correct order).
   */
  def annotationParamNames: Seq[String]

  /** If the macro annotation has two argument lists,
   * this sequence contains the names of the parameters in the first argument list.
   */
  def firstArglistParamNames: Seq[String] = Nil

  override def analyze: Analysis = super.analyze andThen {
    case (origParts:ClassParts,data) =>
      val decor = initClassDecoratorData(origParts,data)
      (origParts,decor)
    case default => default
  }

  override def transform: Transformation = commonTransform andThen {
    // modify annotations for the class carrying the macro annotation
    case cls: ClassTransformData =>
      val classDecoratorData = ClassDecoratorData(cls.data)
      // assemble JS for class decoration
      val js = (classDecoratorData.sjsxStatic :+ genClassDecoration(cls.modParts,classDecoratorData))
        .sortBy(_._1)
        .map(_._2)
        .mkString("","\n","\n")
      cls.addAnnotations(
        q"new scalajs.js.annotation.JSExportTopLevel(${cls.modParts.fullName})",
        q"new sjsx.SJSXStatic(1000,$js)"
      )
    // update the companion object
    case obj: ObjectTransformData =>
      val classDecoratorData = ClassDecoratorData(obj.data)
      import classDecoratorData._

      val mainAnnotationParams = annotParams.map {
        case (name,value) => q"${Ident(TermName(name))} = $value"
      }
      val mainAnnotation =
//        if(mainAnnotationParams.isEmpty)
//          q"$mainAnnotationObject()"
//        else
          q"$mainAnnotationObject( _annotation )"

      obj
        .addAnnotations( q"new scalajs.js.annotation.JSExportTopLevel($objName)" )
        .addStatements(
          q"""private var _annotationData: scalajs.js.Object = null""",
          q"""def _annotation = {
                if(_annotationData == null)
                  _annotationData = scalajs.js.Dynamic.literal(..$mainAnnotationParams)
                _annotationData
              }
            """,
          q"""def _decorators = scalajs.js.Array( $mainAnnotation, ..$decorators )""" )
    case default => default
  }

  private val typeSeqJsObject = Seq(tq"scalajs.js.Object")

  private val jsObjectType = weakTypeOf[scalajs.js.Object]

  private def commonTransform: Transformation = { tdata =>
    val classDecoratorData = ClassDecoratorData(tdata.data)
    import classDecoratorData._
    tdata
      .addAnnotations( classModeAnnotation(classMode) )
      .updParents(
        if(classMode==ClassMode.JS) tdata.modParts.parents match {
          case Nil => typeSeqJsObject
          case Seq(x) if x.toString == "scala.AnyRef" => typeSeqJsObject
          case parents => parents.map(c.typecheck(_,c.TYPEmode)) map {
            case x if x.tpe <:< jsObjectType => x
            case x => tq"${x.tpe.typeSymbol.companion}.JS[..${x.tpe.typeArgs}]"
          }
        }
        else tdata.modParts.parents )
  }

  private def classModeAnnotation(classMode: ClassMode.Value) = classMode match {
    case ClassMode.Scala => q"new scalajs.js.annotation.JSExportAll"
    case ClassMode.JS => q"new scalajs.js.annotation.ScalaJSDefined"
  }

  private def mainAnnotationParams(parts: ClassParts, annotationParamNames: Seq[String]): MainAnnotationParams = {
    extractAnnotationParameters(c.prefix.tree, annotationParamNames, firstArglistParamNames).collect {
      case (name,Some(value)) => (name,value)
    }
  }

  /**
   * Assemble initial ClassDecoratorData
   */
  private def initClassDecoratorData(parts: ClassParts, data: Data): Data = {
    import parts._

    val objName = fullName + "_"

    val diTypes = getInjectionDependencies(params) map {
      case ScalaDependency(fqn) => s"$exports.$fqn"
      case RequireDependency(module,name) => s"require('$module').$name"
    }

    // determine class mode
    // (default: Scala; with @classModeJS => JS)
    val classMode =
      if(findAnnotation(modifiers.annotations,"classModeScala").isDefined) ClassMode.Scala
      else ClassMode.JS

    val metadata: Metadata =
      if(diTypes.isEmpty) Map.empty[String,String]
      else Map("design:paramtypes"->diTypes.mkString("[",",","]"))

    data + ("decoratorData"->ClassDecoratorData(
      objName,
      Nil,
      metadata,
      companion.isDefined,
      classMode,
      mainAnnotationParams(parts,annotationParamNames)
    ))
  }

  /**
   * Generate the JS string used to decorate the class.
   *
   * @param parts
   * @param data
   * @return
   */
  private def genClassDecoration(parts: ClassParts, data: ClassDecoratorData): (Int,String) = {
    import data._
    import parts._

    val decoration =
      if(metadata.isEmpty) s"$exports.$objName._decorators"
      else s"$exports.$objName._decorators.concat(" + metadata.map(p => s"__metadata('${p._1}',${p._2})").mkString("[",",","]") + ")"
    (1000,s"$exports.$fullName = __decorate($decoration,$exports.$fullName);")
  }

  case class DecorationMetadata(key: String, value: String)
  object DecorationMetadata {
//    def designType(tree: Tree): DecorationMetadata = {
//      DecorationMetadata("design:type","String")
//    }
  }

  case class MethodDecoration(decorator: String, prototype: String, method: String, metadata: Iterable[DecorationMetadata]) {
    def toJS: String = {
      val metajs = metadata.map(s => s"__metadata('${s.key}',${s.value})").mkString(",")
      s"__decorate([$decorator,$metajs],$exports.$prototype.prototype,'$method',null);"
    }
  }
}


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

using Xamarin.Forms;

namespace SecondStepXamarin
{
    public partial class FeedTemplate : ContentView
    {
        public FeedTemplate()
        {
            InitializeComponent();
        }
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="org.hisp.dhis.trackedentity.TrackedEntityDataElementDimension" table="trackedentitydataelementdimension">

    <id name="id" column="trackedentitydataelementdimensionid">
      <generator class="native" />
    </id>

    <many-to-one name="dataElement" class="org.hisp.dhis.dataelement.DataElement"
        column="dataelementid" foreign-key="fk_tedataelementdimension_dataelementid" />

	<many-to-one name="legendSet" class="org.hisp.dhis.legend.LegendSet"
		column="legendsetid" foreign-key="fk_tedataelementdimension_legendsetid" />

    <property name="filter" />

  </class>
</hibernate-mapping>


text:
<?php

namespace Sylius\Bundle\WebBundle\Controller\Frontend\Account;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sylius\Bundle\CoreBundle\Model\Metrika;
use Sylius\Bundle\CoreBundle\Model\ReportMetrika;

class MetrikaController extends Controller
{
    private function uf_getLastDir($sUrl)
    {
        $sPath = parse_url($sUrl, PHP_URL_PATH); // parse URL and return only path component
        $aPath = explode('/', trim($sPath, '/')); // remove surrounding "/" and return parts into array
        return end($aPath); // last element of array
    }

    /**
     * Добавление новой записи.
     */
    public function indexAction(Request $request)
    {
        $url = $request->get('url');

//      Если пользователь залогонился и параметр url не пуст
        if (!is_null($url) && is_object($this->getUser())) {

//          Получаем каталог
            $repository_taxon = $this->container->get('sylius.repository.taxon');
            $taxon = $repository_taxon->findOneBy(array('slug' => $this->uf_getLastDir($url)));

//          Если каталог существует
            if (is_object($taxon)) {

//              Добавляем новую метрику
                $metrika = new Metrika();
                $metrika->setTaxon($taxon);
                $metrika->setUser($this->getUser());
                $metrika->setType(Metrika::TYPE_CATALOG);

                $em = $this->getDoctrine()->getManager();
                $em->persist($metrika);
                $em->flush();

            }

        } else {

            return new Response('', Response::HTTP_INTERNAL_SERVER_ERROR);

        }

        return new Response('', Response::HTTP_OK);
    }

    public function reportAction($type)
    {
        $em = $this->getDoctrine()->getManager();
        $reportMetrika = new ReportMetrika(); //Новая запись об отправленном отчете
        $mailSubject = '';
        $sql_register = '';
        $sql_login = '';
        $sql_order_cancel = '';
        $sql_order = '';
        $params = array();

//      Уведомление о зашедшом пользователе за час
        if ($type == 'hour') {
//          Получили метрики пользователей, которые зашли за последний час
            $date = new \DateTime();
            $date->modify('-1 hour');
            $results = $em
                ->createQuery('
             SELECT m FROM Sylius\Bundle\CoreBundle\Model\Metrika m
             JOIN m.user u
             WHERE u.lastLogin > :datetime
             AND m.datetime > :datetime
             AND m.type = :type
             ')
                ->setParameters(array(
                    'datetime' => $date->format('Y-m-d H:i:s'),
                    'type' => Metrika::TYPE_CATALOG
                ))
                ->getResult();

            $metriks = array();

            foreach($results as $r){
                if(!isset($metriks[$r->getUser()->getId()])){
                    $metriks[$r->getUser()->getId()]['user'] = $r->getUser();
                }

                $flag_taxon = 0; // Флаг, который показывает, есть ли данный каталог в массиве
                if (isset($metriks[$r->getUser()->getId()]['catalogs'])) {
                    foreach ($metriks[$r->getUser()->getId()]['catalogs'] as $catalog) {
                        if ($catalog == $r->getTaxon()->getName()) {
                            $flag_taxon = 1;
                        }
                    }
                }

//              Если такой каталог ещё не добавлен, то добавляем в массив
                if ($flag_taxon == 0) {
                    $metriks[$r->getUser()->getId()]['catalogs'][] = $r->getTaxon()->getName();
                }
            }

//          Рассылаем уведомления
            foreach($metriks as $m){
                $mailer = $this->get('mailer');
                $message = \Swift_Message::newInstance()
                    ->setSubject('Olere')
                    ->setFrom(array('order@olere.ru' => "Olere (Новый вошедший пользователь)"))
                    ->setTo($this->container->getParameter('sylius.email_register'))
                    ->setBody($this->renderView('SyliusWebBundle:Email:user.login.html.twig', array('user' => $m['user'], 'catalogs' => join(', ', $m['catalogs']))), 'text/html');
                $mailer->send($message);
            }

            return new Response('', 200);

        } //      Отчет за текущий день
        elseif ($type == 'day') {
            $reportMetrika->setType(ReportMetrika::TYPE_DAY);
            $mailSubject = 'Отчёт за текущий день';
            $date = new \DateTime();
            $sql_register = '
             WHERE YEAR(u.createdAt) = :year
             AND MONTH(u.createdAt) = :month
             AND DAY(u.createdAt) = :day
            ';
            $sql_login = '
             WHERE YEAR(u.lastLogin) = :year
             AND MONTH(u.lastLogin) = :month
             AND DAY(u.lastLogin) = :day
            ';
            $sql_order_cancel = '
             WHERE YEAR(m.datetime) = :year
             AND MONTH(m.datetime) = :month
             AND DAY(m.datetime) = :day
            ';
            $sql_order = '
             WHERE YEAR(o.completedAt) = :year
             AND MONTH(o.completedAt) = :month
             AND DAY(o.completedAt) = :day
            ';
            $params = array(
                'year' => $date->format('Y'),
                'month' => $date->format('m'),
                'day' => $date->format('d')
            );

//      Отчет за неделю
        } elseif ($type == 'week') {
            $reportMetrika->setType(ReportMetrika::TYPE_WEEK);
            $mailSubject = 'Отчёт за неделю';
            $date = new \DateTime();
            $date->modify('-1 week');
            $sql_register = 'WHERE u.createdAt >= :date';
            $sql_login = 'WHERE u.lastLogin >= :date';
            $sql_order_cancel = 'WHERE m.datetime >= :date';
            $sql_order = 'WHERE o.completedAt >= :date';
            $params = array(
                'date' => $date->format('Y-m-d H:i:s')
            );

//      Отчет за месяц
        } elseif ($type == 'month') {
            $reportMetrika->setType(ReportMetrika::TYPE_MONTH);
            $mailSubject = 'Отчёт за месяц';
            $date = new \DateTime();
            $date->modify('-1 month');
            $sql_register = 'WHERE u.createdAt >= :date';
            $sql_login = 'WHERE u.lastLogin >= :date';
            $sql_order_cancel = 'WHERE m.datetime >= :date';
            $sql_order = 'WHERE o.completedAt >= :date';
            $params = array(
                'date' => $date->format('Y-m-d H:i:s')
            );
        }

//      Получим количество регистраций
        $count_register = $em
            ->createQuery('SELECT count(u.id) FROM Sylius\Bundle\CoreBundle\Model\User u ' . $sql_register)
            ->setParameters($params)
            ->getSingleScalarResult();
//      Получим количество аутентификаций
        $count_login = $em
            ->createQuery('SELECT count(u.id) FROM Sylius\Bundle\CoreBundle\Model\User u ' . $sql_login)
            ->setParameters($params)
            ->getSingleScalarResult();
//      Пользователи, которые не купили
        $users = $em
            ->createQuery('SELECT u FROM Sylius\Bundle\CoreBundle\Model\User u WHERE u IN (SELECT IDENTITY(m.user) FROM Sylius\Bundle\CoreBundle\Model\Metrika m ' . $sql_order_cancel . ' AND m.type = 1 ) ORDER BY u.lastLogin ASC')
            ->setParameters($params)
            ->getResult();
//      Список оформленных заказов
        $orders = $em
            ->createQuery('SELECT o FROM Sylius\Bundle\CoreBundle\Model\Order o LEFT JOIN o.user u ' . $sql_order . ' ORDER BY u.lastLogin ASC')
            ->setParameters($params)
            ->getResult();
//      Все метрики посещения каталогов
        $metriks = $em
            ->createQuery('SELECT m FROM Sylius\Bundle\CoreBundle\Model\Metrika m LEFT JOIN m.user u ' . $sql_order_cancel . ' AND m.type = 0 ORDER BY u.lastLogin ASC')
            ->setParameters($params)
            ->getResult();
//      Группируем заказы по пользователям
        $ordersUser = array();
        foreach ($orders as $o) {
            if (!isset($ordersUser[$o->getUser()->getId()]['user'])) {
                $ordersUser[$o->getUser()->getId()]['user'] = $o->getUser();
            }
            $ordersUser[$o->getUser()->getId()]['orders'][] = $o;
        }

//      Группируем данные по пользователям
        $allData = array();

//      Добавляем информацию о несовершенных покупках
        foreach ($users as $u) {
            if (!isset($allData[$u->getId()])) {
                $allData[$u->getId()]['user'] = $u;
                $allData[$u->getId()]['not_order'] = 1;
            }
        }

//      Добавляем информацию об оформленных заказах
        foreach ($ordersUser as $o) {
            if (!isset($allData[$o['user']->getId()])) {
                $allData[$o['user']->getId()]['user'] = $o['user'];
            }

            $allData[$o['user']->getId()]['orders'] = $o['orders'];
        }

//      Добавляем информацию о посещённых каталогах
        foreach ($metriks as $m) {
            if (!isset($allData[$m->getUser()->getId()])) {
                $allData[$m->getUser()->getId()]['user'] = $m->getUser();
            }

            $flag_taxon = 0; // Флаг, который показывает, есть ли данный каталог в массиве
            if (isset($allData[$m->getUser()->getId()]['catalogs'])) {
                foreach ($allData[$m->getUser()->getId()]['catalogs'] as $catalog) {
                    if ($catalog == $m->getTaxon()->getName()) {
                        $flag_taxon = 1;
                    }
                }
            }

//          Если такой каталог ещё не добавлен, то добавляем в массив
            if ($flag_taxon == 0) {
                $allData[$m->getUser()->getId()]['catalogs'][] = $m->getTaxon()->getName();
            }

        }

        $view = $this->renderView('SyliusWebBundle:Frontend/Metrika:report.html.twig', array('data' => $allData, 'countRegister' => $count_register, 'countLogin' => $count_login));

        $objPHPExcel = $this->get('phpexcel')->createPHPExcelObject();
        $sheet = $objPHPExcel->setActiveSheetIndex(0);

//      Excel отчет для вложения в письмо
        // Дата создания отчета
        $sheet->setCellValue('A1', 'Дата создания отчета');
        $sheet->setCellValue('B1', (new \DateTime())->format('d.m.Y'));

        // Заголовки
        $sheet->setCellValue('A3', 'Имя пользователя');
        $sheet->setCellValue('B3', 'Телефон');
        $sheet->setCellValue('C3', 'Название компании');
        $sheet->setCellValue('D3', 'Город');
        $sheet->setCellValue('E3', 'Когда заходил?');
        $sheet->setCellValue('F3', 'Посетил');
        $sheet->setCellValue('G3', 'Добавил в корзину, но не оформил');
        $sheet->setCellValue('H3', 'Оформил заказ');
        $sheet->setCellValue('I3', 'Суммы заказов');

//      Установка жирного шрифта у заголовков
        $objPHPExcel->getActiveSheet()->getStyle('A3:I3')->getFont()->setBold(true);

        // Начальная строчка для вывода в файл
        $row = 4;

        foreach ($allData as $m) {
            $sheet->setCellValue('A' . $row, $m['user']->getFirstName());
            $sheet->setCellValue('B' . $row, $m['user']->getPhone());
            $sheet->setCellValue('C' . $row, $m['user']->getNameCompany());
            $sheet->setCellValue('D' . $row, $m['user']->getCity());

            if ($type == 'day') {
                $sheet->setCellValue('E' . $row, $m['user']->getLastLogin()->format('H:i'));
            } else {
                $sheet->setCellValue('E' . $row, $m['user']->getLastLogin()->format('d.m.Y H:i'));
            }

            $sheet->setCellValue('F' . $row, join(', ', $m['catalogs']));
            $sheet->setCellValue('G' . $row, isset($m['not_order']) ? 'Да' : 'Нет');
            $sheet->setCellValue('H' . $row, isset($m['orders']) ? 'Да' : 'Нет');

            if (isset($m['orders'])) {
                $totalString = '';
                $i = 0;
                foreach ($m['orders'] as $order) {
                    $totalString = $totalString . $order->getTotal() / 100;
                    $i++;
                    if ($i != count($m['orders'])) {
                        $totalString = $totalString . ', ';
                    }
                }
                $sheet->setCellValue('I' . $row, $totalString);
            }

            $row++;
        }

//      Установка автоширины колонок
        foreach (range('A', 'I') as $columnID) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)
                ->setAutoSize(true);
        }

        $writer = $this->get('phpexcel')->createWriter($objPHPExcel, 'Excel2007');
        $writer->save(getcwd() . '/export/metrika_' . $type . '.xlsx');

//        $reportMetrika->setText($view);
//        $em->persist($reportMetrika);
//        $em->flush();

//      Отправляем отчет на почту
        $mailer = $this->get('mailer');
        $message = \Swift_Message::newInstance()
            ->setSubject('Olere')
            ->setFrom(array('order@olere.ru' => "Olere " . $mailSubject))
            ->setTo($this->container->getParameter('sylius.email_register'))
//            ->setTo('1991oleg22@gmail.com')
            ->setContentType('text/html');

        if ($type == 'day') {
            $message
                ->setBody($view, 'text/html');
        }

        $message
            ->attach(\Swift_Attachment::fromPath(getcwd() . '/export/metrika_' . $type . '.xlsx'));
        $mailer->send($message);

        return new Response($view);
    }

}


text:
<Module>
	<Texture>BulkheadTritanium_3x3</Texture>
	<SizeX>3</SizeX>
	<SizeY>3</SizeY>

	<ProductionCost>54</ProductionCost>
	<AlloyCost>18</AlloyCost>
	<AdvancedAlloyCost>18</AdvancedAlloyCost>
	<SuperiorAlloyCost>9</SuperiorAlloyCost>

	<Health>99000</Health>
	<Mass>27</Mass>
</Module>


text:
<!DOCTYPE html>

    <title>AngularJS</title>
    <meta charset="utf-8">
    <link href="../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../styles/kendo.common.min.css" rel="stylesheet">
    <link href="../../styles/kendo.rtl.min.css" rel="stylesheet">
    <link href="../../styles/kendo.default.min.css" rel="stylesheet">
    <link href="../../styles/kendo.dataviz.min.css" rel="stylesheet">
    <link href="../../styles/kendo.dataviz.default.min.css" rel="stylesheet">

        Back

Color value 1: {{color1}}

Color value 2: {{color2}}

<input kendo-color-picker k-palette="'websafe'" ng-model="color2" />

Color value 3: {{color3}}

<input kendo-color-picker ng-model="color3" k-buttons="false" k-preview="false" k-input="false" />


text:
package burai.app;

import java.io.IOException;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

public abstract class QEFXAppComponent<T extends QEFXAppController> {

    protected Node node;

    protected T controller;

    public QEFXAppComponent(Node node, T controller) {
        if (node == null) {
            throw new IllegalArgumentException("node is null.");
        }

        if (controller == null) {
            throw new IllegalArgumentException("controller is null.");
        }

        this.node = node;
        this.controller = controller;

        this.initializeNode();
    }

    public QEFXAppComponent(String fileFXML, T controller) throws IOException {
        if (fileFXML == null || fileFXML.trim().isEmpty()) {
            throw new IllegalArgumentException("file name of FXML is empty.");
        }

        if (controller == null) {
            throw new IllegalArgumentException("controller is null.");
        }

        this.controller = controller;

        FXMLLoader fxmlLoader = new FXMLLoader(this.getClass().getResource(fileFXML));
        fxmlLoader.setController(this.controller);
        this.node = fxmlLoader.load();

        this.initializeNode();
    }

    private void initializeNode() {
        AnchorPane.setBottomAnchor(this.node, 0.0);
        AnchorPane.setTopAnchor(this.node, 0.0);
        AnchorPane.setLeftAnchor(this.node, 0.0);
        AnchorPane.setRightAnchor(this.node, 0.0);
    }

    public final Node getNode() {
        return this.node;
    }

    public final T getController() {
        return this.controller;
    }
}


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

<title>U-Index</title>
<meta name="date" content="2016-07-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P Q R S T U V W X Y Z

U

unbind() - Method in class graphics.nim.volterra.FrameBuffer

unbind() - Method in class graphics.nim.volterra.Shader

unbind() - Method in class graphics.nim.volterra.Texture

uniform1f(String, float) - Method in class graphics.nim.volterra.Shader

uniform1i(String, int) - Method in class graphics.nim.volterra.Shader

uniform3f(String, float, float, float) - Method in class graphics.nim.volterra.Shader

uniformMatrix4f(String, Matrix4f) - Method in class graphics.nim.volterra.Shader

update() - Method in class graphics.nim.volterra.BaseGame

update() - Method in class graphics.nim.volterra.GameState

update() - Method in class graphics.nim.volterra.Sprite

update() - Method in class graphics.nim.volterra.Window

updateTime - Variable in class graphics.nim.volterra.BaseGame

uploadTexture(ByteBuffer, int, int, int) - Static method in class graphics.nim.volterra.TextureLoader

A B C D E F G H I K L M N O P Q R S T U V W X Y Z

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
yogaguru
========

Guided Yoga suite for a stress free life


text:
SclCurrency
===========

[![Build Status](https://travis-ci.org/SCLInternet/SclCurrency.png?branch=master)](https://travis-ci.org/SCLInternet/SclCurrency)
[![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/SCLInternet/SclCurrency/badges/quality-score.png?s=f4363743635da83f8501f2c9513fb29ef057672e)](https://scrutinizer-ci.com/g/SCLInternet/SclCurrency/)
[![Code Coverage](https://scrutinizer-ci.com/g/SCLInternet/SclCurrency/badges/coverage.png?s=9dc68e44337ee0d7e1aba07e020d5b9224d8450d)](https://scrutinizer-ci.com/g/SCLInternet/SclCurrency/)

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

Currency
--------

Money
-----

TaxedPrice
----------

Comparison
----------

Calculations
------------

Factories
---------

### CurrencyFactory

```php
use SCL\Currency\CurrencyFactory;

$factory = CurrencyFactory::createDefaultInstance();

$sterling = $factory->create('GBP');
```

### MoneyFactory

```php
use SCL\Currency\CurrencyFactory;
use SCL\Currency\MoneyFactory;

$factory = MoneyFactory::createDefaultInstance();

$factory->setDefaultCurrency(CurrencyFactory::createDefaultInstance()->create('GBP'));

$money = $factory->createFromValue(1.00);
```


text:
@class ORTable, OREntity;
@interface ORCache : NSObject

+ (ORTable *)tableWithName:(NSString *)name;

+ (OREntity *)entityWithId:(id)value;
+ (void)addEntity:(OREntity *)entity;
+ (void)removeEntity:(OREntity *)entity;

@end


text:
EXOSIMS.StarCatalog package
===========================

.. automodule:: EXOSIMS.StarCatalog
   :members:
   :undoc-members:
   :show-inheritance:

Submodules
----------

EXOSIMS.StarCatalog.EXOCAT1 module
----------------------------------

.. automodule:: EXOSIMS.StarCatalog.EXOCAT1
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.FakeCatalog module
--------------------------------------

.. automodule:: EXOSIMS.StarCatalog.FakeCatalog
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.FakeCatalog\_UniformAngles module
-----------------------------------------------------

.. automodule:: EXOSIMS.StarCatalog.FakeCatalog_UniformAngles
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.FakeCatalog\_UniformSpacing\_wInput module
--------------------------------------------------------------

.. automodule:: EXOSIMS.StarCatalog.FakeCatalog_UniformSpacing_wInput
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.GaiaCat1 module
-----------------------------------

.. automodule:: EXOSIMS.StarCatalog.GaiaCat1
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.HIPfromSimbad module
----------------------------------------

.. automodule:: EXOSIMS.StarCatalog.HIPfromSimbad
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.SIMBAD300Catalog module
-------------------------------------------

.. automodule:: EXOSIMS.StarCatalog.SIMBAD300Catalog
   :members:
   :undoc-members:
   :show-inheritance:

EXOSIMS.StarCatalog.SIMBADCatalog module
----------------------------------------

.. automodule:: EXOSIMS.StarCatalog.SIMBADCatalog
   :members:
   :undoc-members:
   :show-inheritance:


text:
from Camera import Camera
from Image import Image
from World import World
from py3D import Color, Vector
import time

_default_filename = 'trace.png'

class Tracer:
    _world = World()
    _camera = Camera()
    _image = Image(1,1)

    def __init__(self, world = None, camera = None):
        self._world = world
        self._camera = camera
        self._drawn = False
        self._image = None

    def set_camera(self, camera = Camera()):
        self._camera = camera
        return self

    def set_world(self, world = World()):
        self._world = world
        return self

    def draw(self, passes = 8):
        if self._world == None:
            self.set_world()
        if self._camera == None:
            self.set_camera()
        ppu = self._camera.ppu
        width = int(ppu * self._camera.width)
        height = int(ppu * self._camera.height)
        self._image = Image(width, height)
        c = Color()
        t_0 = time.time()
        for y in range(height):
            lt0 = time.time()
            print 'drawing line', y + 1, 'of', height
            for x in range(width):
                c.set_rgb(0.0,0.0,0.0)
                for p in range(passes):
                    c = c + self._world.sample(self._camera.get_ray(x,y))
                self._image.set_pixel(x,y,c.dim(1.0 / passes))
            lt1 = time.time()
            ltime = lt1 - lt0
            ttime = lt1 - t_0
            lleft = height - 1 - y
            mleft1 = ltime * lleft / 60
            mleft2 = ttime / (y + 1) * lleft / 60
            print 'line took {0:.3} seconds.'.format(ltime),
            print '{0:.5} to {1:.5} minutes left'.format(mleft1, mleft2)
        self._drawn = True
        return self

    def write(self, filename = _default_filename, gamma = None):
        if not self._drawn:
            raise self._image
        if not gamma == None:
            self._image.gamma(gamma)
        print 'encoding as {}...'.format(filename)
        self._image.toPNG().write(filename)
        print '        ALL DONE!'
        return self