text:
package com.linecorp.armeria.server.http.tomcat;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.catalina.Service;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import com.linecorp.armeria.server.AbstractServerTest;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.logging.LoggingService;

import io.netty.handler.codec.http.HttpHeaderNames;

public class TomcatServiceTest extends AbstractServerTest {

    private static final Pattern CR_OR_LF = Pattern.compile("[\\r\\n]");

    private static final String SERVICE_NAME = "TomcatServiceTest";

    private final List<Service> tomcatServices = new ArrayList<>();

    @Override
    protected void configureServer(ServerBuilder sb) {
        sb.serviceUnder(
                "/tc/",
                TomcatServiceBuilder.forCurrentClassPath("tomcat_service")
                                    .serviceName(SERVICE_NAME)
                                    .configurator(s -> Collections.addAll(tomcatServices, s.findServices()))
                                    .build()
                                    .decorate(LoggingService::new));
    }

    @Test
    public void testJsp() throws Exception {
        try (CloseableHttpClient hc = HttpClients.createMinimal()) {
            try (CloseableHttpResponse res = hc.execute(new HttpGet(uri("/tc/")))) {
                assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
                assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(),
                           startsWith("text/html"));
                final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                                                     .replaceAll("");
                assertThat(actualContent, is(
                        "" +
                        "
Hello, Armerian World!
" +
                        "
Have you heard about the class 'io.netty.buffer.ByteBuf'?
" +
                        "
Context path:
" + // ROOT context path
                        "
Request URI: /
" +
                        ""));
            }
        }
    }

    @Test
    public void testGetQueryString() throws Exception {
        try (CloseableHttpClient hc = HttpClients.createMinimal()) {
            try (CloseableHttpResponse res = hc.execute(
                    new HttpGet(uri("/tc/query_string.jsp?foo=%31&bar=%32")))) {

                assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
                assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(),
                           startsWith("text/html"));
                final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                                                     .replaceAll("");
                assertThat(actualContent, is(
                        "" +
                        "
foo is 1
" +
                        "
bar is 2
" +
                        ""));
            }
        }
    }

    @Test
    public void testPostQueryString() throws Exception {
        try (CloseableHttpClient hc = HttpClients.createMinimal()) {
            final HttpPost post = new HttpPost(uri("/tc/query_string.jsp?foo=3"));
            post.setEntity(new UrlEncodedFormEntity(
                    Collections.singletonList(new BasicNameValuePair("bar", "4")), StandardCharsets.UTF_8));

            try (CloseableHttpResponse res = hc.execute(post)) {
                assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
                assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(),
                           startsWith("text/html"));
                final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                                                     .replaceAll("");
                assertThat(actualContent, is(
                        "" +
                        "
foo is 3
" +
                        "
bar is 4
" +
                        ""));
            }
        }
    }

    @Test
    public void testAddressesAndPorts() throws Exception {
        try (CloseableHttpClient hc = HttpClients.createMinimal()) {
            try (CloseableHttpResponse res = hc.execute(new HttpGet(uri("/tc/addrs_and_ports.jsp")))) {
                assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK"));
                assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(),
                           startsWith("text/html"));
                final String actualContent = CR_OR_LF.matcher(EntityUtils.toString(res.getEntity()))
                                                     .replaceAll("");

                assertTrue(actualContent, actualContent.matches(
                        "" +
                        "
RemoteAddr: 127\\.0\\.0\\.1
" +
                        "
RemoteHost: 127\\.0\\.0\\.1
" +
                        "
RemotePort: [1-9][0-9]+
" +
                        "
LocalAddr: (?!null)[^<]+
" +
                        "
LocalName: localhost
" +
                        "
LocalPort: " + server().activePort().get().localAddress().getPort() + "
" +
                        ""));
            }
        }
    }

    @Test
    public void testConfigurator() throws Exception {
        assertThat(tomcatServices, hasSize(1));
        assertThat(tomcatServices.get(0).getName(), is(SERVICE_NAME));
    }
}


text:
layout: post
title:  "Detectar Mortos-Vivos"
date:   2018-01-01
source: Módulo Básico 167, Módulo Básico Edição Revisada 177.
tags: [nenhum, bardo]
---

**arcana 1, divina 1 (adivinhação)**

**Duração**: concentração, até 3 rodadas

**Alcance**: 9m

**Teste de Resistência**: nenhum.

**Área**: emanação em cone

**Tempo de Execução**: ação padrão

Você detecta a presença, quantidade e poder de mortos-vivos na área, conforme a quantidade de rodadas que gastar se concentrando. Na primeira rodada, você percebe a presença de mortos-vivos; na segunda rodada, a quantidade de mortos-vivos; e na terceira rodada, a localização e poder de cada morto-vivo.
O poder da criatura depende do seu nível. Mortos-vivos de 1º a 6º nível geram uma aura tênue, mortos-vivos de 7º a 12º nível geram uma aura moderada e mortos-vivos de 13º a 20º nível geram uma aura poderosa. Mortos-vivos com mais de 20 níveis geram uma aura avassaladora.
Esta magia não atravessa barreiras que excedam 90cm de terra ou madeira, 30cm de pedra, 2,5cm de metal comum, ou uma folha fina de chumbo.

redpajama_set_name: RedPajamaGithub


text:
@implementation CTGeneralMessage

- (instancetype)initWithContent:(NSString *)content subContent:(NSString *)subContent
            canJoinOtherMessage:(BOOL)canJoinOtherMessage type:(CTGeneralMessageType)type
{
    self = [super initWithContent:content subContent:subContent duration:0 canJoinOtherMessage:canJoinOtherMessage];
    if (self) {
        _type = type;
    }
    return self;
}

- (BOOL)canJoinMessage:(CTAbstractMessage *)message
{
    BOOL canJoin = [super canJoinMessage:message];
    if (!canJoin) return NO;

    return self.type == ((CTGeneralMessage *)message).type;
}

@end


text:
import collections

PortPair = collections.namedtuple('PortPair', ['local_port', 'remote_port'])
PortSet = collections.namedtuple('PortSet', ['http', 'https', 'dns'])

class PortPairs(collections.namedtuple('PortPairs', ['http', 'https', 'dns'])):
  __slots__ = ()

  @classmethod
  def Zip(cls, local_ports, remote_ports):
    """Zip a pair of PortSet's into a single PortPairs object."""
    with_dns = local_ports.dns is not None and remote_ports.dns is not None
    return cls(
      PortPair(local_ports.http, remote_ports.http),
      PortPair(local_ports.https, remote_ports.https),
      PortPair(local_ports.dns, remote_ports.dns) if with_dns else None)

  @property
  def local_ports(self):
    """Return a tuple of local ports only."""
    return PortSet(*[p.local_port if p is not None else None for p in self])

  @property
  def remote_ports(self):
    """Return a tuple of remote ports only."""
    return PortSet(*[p.remote_port if p is not None else None for p in self])

class ForwarderFactory(object):

  def Create(self, port_pairs):
    """Creates a forwarder that maps remote (device) <-> local (host) ports.

    Args:
      port_pairs: A PortPairs instance that consists of a PortPair mapping
          for each protocol. http is required. https and dns may be None.
    """
    raise NotImplementedError()

  @property
  def host_ip(self):
    return '127.0.0.1'

  @property
  def does_forwarder_override_dns(self):
    return False

class Forwarder(object):

  def __init__(self, port_pairs):
    assert port_pairs.http, 'HTTP port mapping is required.'
    self._port_pairs = PortPairs(*[
        PortPair(p.local_port, p.remote_port or p.local_port)
        if p else None for p in port_pairs])
    self._forwarding = True

  @property
  def host_port(self):
    return self._port_pairs.http.remote_port

  @property
  def host_ip(self):
    return '127.0.0.1'

  @property
  def port_pairs(self):
    return self._port_pairs

  @property
  def url(self):
    assert self.host_ip and self.host_port
    return 'http://%s:%i' % (self.host_ip, self.host_port)

  def Close(self):
    self._port_pairs = None
    self._forwarding = False


text:
import unittest
from unittest.mock import patch
from skygear.transmitter.encoding import deserialize_record

from ..conversation import pubsub_conversation_after_save

class TestHandleConversationAfterSave(unittest.TestCase):

    def setUp(self):
        self.conn = None

    def record(self):
        return deserialize_record({
            '_id': 'conversation/1',
            '_access': None,
            '_ownerID': 'user1',
            'participant_ids': ['user1', 'user2'],
            'admin_ids': ['user1']
        })

    def original_record(self):
        return deserialize_record({
            '_id': 'conversation/1',
            '_access': None,
            '_ownerID': 'user1',
            'participant_ids': ['user2', 'user3'],
            'admin_ids': ['user1']
        })

    @patch('chat.conversation._publish_event')
    def test_pubsub_newly_created_conversation(self, mock_publish_event):
        pubsub_conversation_after_save(self.record(), None, self.conn)
        self.assertIs(mock_publish_event.call_count, 2)

    @patch('chat.conversation._publish_event')
    def test_pubsub_newly_created_conversation_with_original_record(
            self, mock_publish_event):
        pubsub_conversation_after_save(
            self.record(), self.original_record(), self.conn)
        self.assertIs(mock_publish_event.call_count, 3)


text:
module DTK
  module Client
    require_relative('client/util')
    require_relative('client/module_ref')

    # util and module_ref must be loaded first
    require_relative('client/logger')
    require_relative('client/error')
    require_relative('client/config')
    require_relative('client/configurator')
    require_relative('client/response')
    require_relative('client/conn')
    require_relative('client/session')
    require_relative('client/git_repo')
    require_relative('client/operation')
    require_relative('client/operation_args')
    require_relative('client/render')
    require_relative('client/service_and_component_info')
    require_relative('client/load_source')
  end
end


text:
class CreateInputs < ActiveRecord::Migration
  def change
    create_table :inputs do |t|
      t.string :name
      t.decimal :last_value, :precision => 10, :scale => 2
      t.integer :user_id

      t.timestamps
    end
    add_index :inputs, :user_id
  end
end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.08.05 at 03:54:57 PM CEST
//

package com.ptc.tifworkbench.jaxbbinding;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 *
Java class for FieldsReference complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="FieldsReference">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="field" type="{http://www.ptc.com/integrity-solution}FieldReference" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FieldsReference", propOrder = {
    "field"
})
public class FieldsReference
    implements Equals, HashCode, ToString
{

    @XmlElement(required = true)
    protected List<FieldReference> field;

    /**
     * Gets the value of the field property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the field property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getField().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link FieldReference }
     *
     *
     */
    public List<FieldReference> getField() {
        if (field == null) {
            field = new ArrayList<FieldReference>();
        }
        return this.field;
    }

    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
        if (!(object instanceof FieldsReference)) {
            return false;
        }
        if (this == object) {
            return true;
        }
        final FieldsReference that = ((FieldsReference) object);
        {
            List<FieldReference> lhsField;
            lhsField = this.getField();
            List<FieldReference> rhsField;
            rhsField = that.getField();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "field", lhsField), LocatorUtils.property(thatLocator, "field", rhsField), lhsField, rhsField)) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(Object object) {
        final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
        return equals(null, null, object, strategy);
    }

    public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
        int currentHashCode = 1;
        {
            List<FieldReference> theField;
            theField = this.getField();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "field", theField), currentHashCode, theField);
        }
        return currentHashCode;
    }

    public int hashCode() {
        final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
        return this.hashCode(null, strategy);
    }

    public String toString() {
        final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
        final StringBuilder buffer = new StringBuilder();
        append(null, buffer, strategy);
        return buffer.toString();
    }

    public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
        strategy.appendStart(locator, this, buffer);
        appendFields(locator, buffer, strategy);
        strategy.appendEnd(locator, this, buffer);
        return buffer;
    }

    public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
        {
            List<FieldReference> theField;
            theField = this.getField();
            strategy.appendField(locator, this, "field", buffer, theField);
        }
        return buffer;
    }

}


text:
package jq

/*
#cgo LDFLAGS: -ljq

#include <stdlib.h>

#include <jv.h>
#include <jq.h>
*/
import "C"
import (
	"errors"
	"fmt"
	"reflect"
	"unsafe"
)

// Helper functions for dealing with JV objects. You can't use this from
// another go package as the cgo types are 'unique' per go package

// JvKind represents the type of value that a `Jv` contains.
type JvKind int

// Jv represents a JSON value from libjq.
//
// The go wrapper uses the same memory management semantics as the underlying C
// library, so you should familiarize yourself with
// https://github.com/stedolan/jq/wiki/C-API:-jv#memory-management. In summary
// this package and all JQ functions operate on the assumption that any jv value
// you pass to a function is then owned by that function -- if you do not wish
// this to be the case call Copy() on it first.
type Jv struct {
	jv C.jv
}

const (
	JV_KIND_INVALID JvKind = C.JV_KIND_INVALID
	JV_KIND_NULL    JvKind = C.JV_KIND_NULL
	JV_KIND_FALSE   JvKind = C.JV_KIND_FALSE
	JV_KIND_TRUE    JvKind = C.JV_KIND_TRUE
	JV_KIND_NUMBER  JvKind = C.JV_KIND_NUMBER
	JV_KIND_STRING  JvKind = C.JV_KIND_STRING
	JV_KIND_ARRAY   JvKind = C.JV_KIND_ARRAY
	JV_KIND_OBJECT  JvKind = C.JV_KIND_OBJECT
)

// String returns a string representation of what type this Jv contains
func (kind JvKind) String() string {
	// Rather than rely on converting from a C string to go every time, store our
	// own list
	switch kind {
	case JV_KIND_INVALID:
		return "<invalid>"
	case JV_KIND_NULL:
		return "null"
	case JV_KIND_FALSE:
		return "boolean"
	case JV_KIND_TRUE:
		return "boolean"
	case JV_KIND_NUMBER:
		return "number"
	case JV_KIND_STRING:
		return "string"
	case JV_KIND_ARRAY:
		return "array"
	case JV_KIND_OBJECT:
		return "object"
	default:
		return "<unkown>"
	}
}

// JvNull returns a value representing a JSON null
func JvNull() *Jv {
	return &Jv{C.jv_null()}
}

// JvInvalid returns an invalid jv object without an error property
func JvInvalid() *Jv {
	return &Jv{C.jv_invalid()}
}

// JvInvalidWithMessage creates an "invalid" jv with the given error message.
//
// msg can be a string or an object
//
// Consumes `msg`
func JvInvalidWithMessage(msg *Jv) *Jv {
	return &Jv{C.jv_invalid_with_msg(msg.jv)}
}

// JvFromString returns a new jv string-typed value containing the given go
// string.
func JvFromString(str string) *Jv {
	cs := C.CString(str)
	defer C.free(unsafe.Pointer(cs))
	return &Jv{C.jv_string_sized(cs, C.int(len(str)))}
}

// JvFromFloat returns a new jv number-typed value containing the given float
// value.
func JvFromFloat(n float64) *Jv {
	return &Jv{C.jv_number(C.double(n))}
}

// JvFromBool returns a new jv of "true" or "false" kind depending on the given
// boolean value
func JvFromBool(b bool) *Jv {
	if b {
		return &Jv{C.jv_true()}
	} else {
		return &Jv{C.jv_false()}
	}
}

func jvFromArray(val reflect.Value) (*Jv, error) {
	len := val.Len()
	ret := &Jv{C.jv_array_sized(C.int(len))}
	for i := 0; i < len; i++ {
		newjv, err := JvFromInterface(
			val.Index(i).Interface(),
		)
		if err != nil {
			// TODO: error context
			ret.Free()
			return nil, err
		}
		ret = &Jv{C.jv_array_set(ret.jv, C.int(i), newjv.jv)}
	}
	return ret, nil
}

func jvFromMap(val reflect.Value) (*Jv, error) {
	keys := val.MapKeys()
	ret := JvObject()

	for _, key := range keys {
		keyjv := JvFromString(key.String())
		valjv, err := JvFromInterface(val.MapIndex(key).Interface())
		if err != nil {
			// TODO: error context
			keyjv.Free()
			ret.Free()
			return nil, err
		}
		ret = ret.ObjectSet(keyjv, valjv)
	}

	return ret, nil
}

func JvFromInterface(intf interface{}) (*Jv, error) {
	if intf == nil {
		return JvNull(), nil
	}

	switch x := intf.(type) {
	case float32:
		return JvFromFloat(float64(x)), nil
	case float64:
		return JvFromFloat(x), nil
	case uint:
		return JvFromFloat(float64(x)), nil
	case int:
		return JvFromFloat(float64(x)), nil
	case int8:
		return JvFromFloat(float64(x)), nil
	case uint8:
		return JvFromFloat(float64(x)), nil
	case int16:
		return JvFromFloat(float64(x)), nil
	case uint16:
		return JvFromFloat(float64(x)), nil
	case int32:
		return JvFromFloat(float64(x)), nil
	case uint32:
		return JvFromFloat(float64(x)), nil
	case int64:
		return JvFromFloat(float64(x)), nil
	case uint64:
		return JvFromFloat(float64(x)), nil
	case string:
		return JvFromString(x), nil
	case []byte:
		return JvFromString(string(x)), nil
	case bool:
		return JvFromBool(x), nil
	}

	val := reflect.ValueOf(intf)
	switch val.Kind() {
	case reflect.Array, reflect.Slice:
		return jvFromArray(val)
	case reflect.Map:
		return jvFromMap(val)
	default:
		return nil, errors.New("JvFromInterface can't handle " + val.Kind().String())
	}
}

func _ConvertError(inv C.jv) error {
	// We might want to not call this as it prefixes things with "jq: "
	jv := &Jv{C.jq_format_error(inv)}
	defer jv.Free()

	return errors.New(jv._string())
}

// JvFromJSONString takes a JSON string and returns the jv representation of
// it.
func JvFromJSONString(str string) (*Jv, error) {
	cs := C.CString(str)
	defer C.free(unsafe.Pointer(cs))
	jv := C.jv_parse(cs)

	if C.jv_is_valid(jv) == 0 {
		return nil, _ConvertError(jv)
	}
	return &Jv{jv}, nil
}

// JvFromJSONBytes takes a utf-8 byte sequence containing JSON and returns the
// jv representation of it.
func JvFromJSONBytes(b []byte) (*Jv, error) {
	jv := C.jv_parse((*C.char)(unsafe.Pointer(&b[0])))

	if C.jv_is_valid(jv) == 0 {
		return nil, _ConvertError(jv)
	}
	return &Jv{jv}, nil
}

// Free this reference to a Jv value.
//
// Don't call this more than once per jv - might not actually free the memory
// as libjq uses reference counting. To make this more like the libjq interface
// we return a nil pointer.
func (jv *Jv) Free() *Jv {
	C.jv_free(jv.jv)
	return nil
}

// Kind returns a JvKind saying what type this jv contains.
//
// Does not consume the invocant.
func (jv *Jv) Kind() JvKind {
	return JvKind(C.jv_get_kind(jv.jv))
}

// Copy returns a *Jv so that the original won't get freed.
//
// Does not consume the invocant.
func (jv *Jv) Copy() *Jv {
	C.jv_copy(jv.jv)
	// Becasue jv uses ref counting under the hood we can return the same value
	return jv
}

// IsValid returns true if this Jv represents a valid JSON type, or false if it
// is unitiaizlied or if it represents an error type
//
// Does not consume the invocant.
func (jv *Jv) IsValid() bool {
	return C.jv_is_valid(jv.jv) != 0
}

// GetInvalidMessageAsString gets the error message for this Jv. If there is none it
// will return ("", false). Otherwise it will return the message as a string and true,
// converting non-string values if necessary. If you want the message in it's
// native Jv type use `GetInvalidMessage()`
//
// Consumes the invocant.
func (jv *Jv) GetInvalidMessageAsString() (string, bool) {
	msg := C.jv_invalid_get_msg(jv.jv)
	defer C.jv_free(msg)

	if C.jv_get_kind(msg) == C.JV_KIND_NULL {
		return "", false
	} else if C.jv_get_kind(msg) != C.JV_KIND_STRING {
		msg = C.jv_dump_string(msg, 0)
	}
	return C.GoString(C.jv_string_value(msg)), true
}

// GetInvalidMessage returns the message associcated
func (jv *Jv) GetInvalidMessage() *Jv {
	return &Jv{C.jv_invalid_get_msg(jv.jv)}
}

func (jv *Jv) _string() string {
	// Raw string value. If called on
	cs := C.jv_string_value(jv.jv)
	// Don't free cs - freed when the jv is
	return C.GoString(cs)
}

// If jv is a string, return its value. Will not stringify other types
//
// Does not consume the invocant.
func (jv *Jv) String() (string, error) {
	// Doing this might be a bad idea as it means we almost implement the Stringer
	// interface but not quite (cos the error type)

	// If we don't do this check JV will assert
	if C.jv_get_kind(jv.jv) != C.JV_KIND_STRING {
		return "", fmt.Errorf("Cannot return String for jv of type %s", jv.Kind())
	}

	return jv._string(), nil
}

// ToGoVal converts a jv into it's closest Go approximation
//
// Does not consume the invocant.
func (jv *Jv) ToGoVal() interface{} {
	switch kind := C.jv_get_kind(jv.jv); kind {
	case C.JV_KIND_NULL:
		return nil
	case C.JV_KIND_FALSE:
		return false
	case C.JV_KIND_TRUE:
		return true
	case C.JV_KIND_NUMBER:
		dbl := C.jv_number_value(jv.jv)

		if C.jv_is_integer(jv.jv) == 0 {
			return float64(dbl)
		}
		return int(dbl)
	case C.JV_KIND_STRING:
		return jv._string()
	case C.JV_KIND_ARRAY:
		len := jv.Copy().ArrayLength()
		ary := make([]interface{}, len)
		for i := 0; i < len; i++ {
			v := jv.Copy().ArrayGet(i)
			ary[i] = v.ToGoVal()
			v.Free()
		}
		return ary
	case C.JV_KIND_OBJECT:
		obj := make(map[string]interface{})
		for iter := C.jv_object_iter(jv.jv); C.jv_object_iter_valid(jv.jv, iter) != 0; iter = C.jv_object_iter_next(jv.jv, iter) {
			k := Jv{C.jv_object_iter_key(jv.jv, iter)}
			v := Jv{C.jv_object_iter_value(jv.jv, iter)}
			// jv_object_iter_key already asserts that the kind is string, so using _string is OK here
			obj[k._string()] = v.ToGoVal()
			k.Free()
			v.Free()
		}
		return obj
	default:
		panic(fmt.Sprintf("Unknown JV kind %d", kind))
	}
}

type JvPrintFlags int

const (
	JvPrintNone     JvPrintFlags = 0                   // None of the below
	JvPrintPretty   JvPrintFlags = C.JV_PRINT_PRETTY   // Print across multiple lines
	JvPrintAscii    JvPrintFlags = C.JV_PRINT_ASCII    // Escape non-ascii printable characters
	JvPrintColour   JvPrintFlags = C.JV_PRINT_COLOUR   // Include ANSI color escapes based on data types
	JvPrintSorted   JvPrintFlags = C.JV_PRINT_SORTED   // Sort output keys
	JvPrintInvalid  JvPrintFlags = C.JV_PRINT_INVALID  // Print invalid as "<invalid>"
	JvPrintRefCount JvPrintFlags = C.JV_PRINT_REFCOUNT // Display refcount of objects in in parenthesis
	JvPrintTab      JvPrintFlags = C.JV_PRINT_TAB      // Indent with tabs,
	JvPrintIsATty   JvPrintFlags = C.JV_PRINT_ISATTY   //
	JvPrintSpace0   JvPrintFlags = C.JV_PRINT_SPACE0   // Indent with zero extra chars beyond the parent bracket
	JvPrintSpace1   JvPrintFlags = C.JV_PRINT_SPACE1   // Indent with zero extra chars beyond the parent bracket
	JvPrintSpace2   JvPrintFlags = C.JV_PRINT_SPACE2   // Indent with zero extra chars beyond the parent bracket
)

// Dump produces a human readable version of the string with the requested formatting.
//
// Consumes the invocant
func (jv *Jv) Dump(flags JvPrintFlags) string {
	jv_str := Jv{C.jv_dump_string(jv.jv, C.int(flags))}
	defer jv_str.Free()
	return jv_str._string()
}

// JvArray creates a new, empty array-typed JV
func JvArray() *Jv {
	return &Jv{C.jv_array()}
}

// ArrayAppend appends a single value to the end of the array.
//
// If jv is not an array this will cause an assertion.
//
// Consumes the invocant
func (jv *Jv) ArrayAppend(val *Jv) *Jv {
	return &Jv{C.jv_array_append(jv.jv, val.jv)}
}

// ArrayLength returns the number of elements in the array.
//
// Consumes the invocant
func (jv *Jv) ArrayLength() int {
	return int(C.jv_array_length(jv.jv))
}

// ArrayGet returns the element at the given array index.
//
// If the index is out of bounds it will return an Invalid Jv object (with no
// error message set).
//
// `idx` cannot be negative.
//
// Consumes the invocant
func (jv *Jv) ArrayGet(idx int) *Jv {
	return &Jv{C.jv_array_get(jv.jv, C.int(idx))}
}

func JvObject() *Jv {
	return &Jv{C.jv_object()}
}

// ObjectSet will add val to the object under the given key.
//
// This is the equivalent of `jv[key] = val`.
//
// Consumes invocant and both key and val
func (jv *Jv) ObjectSet(key *Jv, val *Jv) *Jv {
	return &Jv{C.jv_object_set(jv.jv, key.jv, val.jv)}
}


text:
package org.jboss.pnc.mapper.api;

import org.jboss.pnc.dto.ProductMilestoneRef;
import org.jboss.pnc.dto.ProductRef;
import org.jboss.pnc.dto.ProductVersionRef;
import org.jboss.pnc.mapper.IntIdMapper;
import org.jboss.pnc.model.ProductVersion;
import org.mapstruct.BeanMapping;
import org.mapstruct.InheritConfiguration;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;

/**
 *
 * @author Honza Brázdil <jbrazdil@redhat.com>
 */
public interface ProductVersionMapper
        extends UpdatableEntityMapper<Integer, ProductVersion, org.jboss.pnc.dto.ProductVersion, ProductVersionRef> {

    @Override
    @Mapping(target = "buildConfigurationSets", source = "groupConfigs")
    @Mapping(target = "buildConfigurations", source = "buildConfigs")
    @Mapping(target = "productReleases", ignore = true)
    ProductVersion toEntity(org.jboss.pnc.dto.ProductVersion dtoEntity);

    @Override
    @InheritConfiguration
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "product", ignore = true)
    @Mapping(target = "productMilestones", ignore = true)
    @Mapping(target = "buildConfigurationSets", expression = "java( cm.updateGroupConfigs(dtoEntity, target) )")
    @Mapping(target = "buildConfigurations", expression = "java( cm.updateBuildConfigs(dtoEntity, target) )")
    void updateEntity(org.jboss.pnc.dto.ProductVersion dtoEntity, @MappingTarget ProductVersion target);

    @Override
    @BeanMapping(
            ignoreUnmappedSourceProperties = { "product", "productReleases", "productMilestones",
                    "currentProductMilestone", "buildConfigurationSets", "buildConfigurations" })
    ProductVersionRef toRef(ProductVersion dbEntity);

    @Override
    @Mapping(target = "groupConfigs", source = "buildConfigurationSets")
    @Mapping(target = "product", resultType = ProductRef.class)
    @Mapping(target = "currentProductMilestone", resultType = ProductMilestoneRef.class)
    @Mapping(target = "buildConfigs", source = "buildConfigurations")
    org.jboss.pnc.dto.ProductVersion toDTO(ProductVersion dbEntity);

    @Override
    default IdMapper<Integer, String> getIdMapper() {
        return new IntIdMapper();
    }
}


text:
module MethodsPracticeHelpers

  def image_tag(source, alternate_text)
    %()
  end

  def bootstrap_alert(message, type='info')
    %(

        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          ×
        </button>#{message}
)
  end

  def current_date_and_time
    Time.now.getlocal.strftime('%B %-e, %Y at%l:%M%P')
  end

end


text:
class Human {

    name: string;

    constructor(name: string){
        this.name = name;
    }
}

class Animal {
    name: string;
    age: number;

    constructor(name: string, age: number){
        this.name = name;
        this.age = age;
    }
    eat(quantity: number){
        console.log(this.name + " is a Human and is eating");
    }
}

let d  = {name:"Hello",age:4};

let h: Human = {name:"hello"}; // This is allowed
let h1: Human = d; // Concept of stale object applied here

let isHuman:boolean = h instanceof Human; // Its false, because we have assigned object literal and assignment works because
// of structural typing
console.log(isHuman); // false

let a1: Animal = {name:"Cat",age:4}; // This is not allowed need to add all properties including functions

// This below statement is allowed
// Note there is no parameter in function and it does not give any compilation error but you can not call
// this function without paramter, see the call below
let a2: Animal = {name:"Dog",age:4, eat: function() {
    console.log("Eat in object literal");
}};

a2.eat(); // Not allowed
a2.eat(3); // Works fine


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>YJSoft Opensource Blog</title>
    <meta name="description" content="Blog about open source" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//YJSoft.github.io/themes/Casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//YJSoft.github.io/themes/Casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://YJSoft.github.io" />
    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="YJSoft Opensource Blog" href="https://YJSoft.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

Hub-Press

                    A 2-post collection

        Page 1 of 1

YJSoft Github

YJSoft Github입니다. 여러가지를 올릴 예정. 지금으로썬 딱히 정해둔건 없습니다. »

             on HubPress,  Blog
            <time class="post-date" datetime="2016-03-02">02 March 2016</time>

Hubpress 설치후 실수하기 쉬운 것들

태그에는 한글이 올 수 없다. 한글이 오면 Publish가 안되니 주의해야 한다. 이외 발견하는 대로 추가 예정.(절대 귀찮은게 아님!) »

             on HubPress,  Blog,  Install
            <time class="post-date" datetime="2016-03-02">02 March 2016</time>

        Page 1 of 1

YJSoft Opensource Blog © 2016

Proudly published with HubPress


text:
/*
 * (c) LibriCore
 *
 * Created on Aug 5, 2004
 *
 * BibliographicNoteType.java
 */
package org.folio.marccat.dao.persistence;

/**
 * @author paulm
 * @version %I%, %G%
 */
public class T_STD_NTE_TYP extends T_SINGLE {

}


text:
package com.siemens.scr.avt.ad.dicom;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.Tag;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.siemens.scr.avt.ad.io.DicomIO;
import com.siemens.scr.avt.ad.util.DicomComparator;
import com.siemens.scr.avt.ad.util.DicomParser;

/**
 * DICOM roundtrip test.
 *
 * @author Xiang Li
 *
 */
@RunWith(Parameterized.class)
public class DicomPersistenceTest {
	public static Logger logger = Logger.getLogger(DicomPersistenceTest.class);

	private  String file ;

	private DicomObject dob;

	public DicomPersistenceTest(String sourceFile){
		this.file = sourceFile;
	}

	@Parameters
	 public static Collection sourceFiles() {
	  return Arrays.asList(new Object[][] {
			  {"/RECIST_Data_rv_12/1.3.6.1.4.1.9328.50.1.10704.dcm"},
	   });
	 }

	@Before
	public  void setup(){
		dob = DicomParser.read(this.getClass(), file);
	}

	@Test
	public void roundtripTest() throws IOException{
		String SOPInstanceUID = dob.getString(Tag.SOPInstanceUID);
		DicomIO.saveOrUpdateDicom(dob);

		// dump a new copy from DB
		DicomObject loadedDcm = DicomIO.dumpDicom(SOPInstanceUID);

		// verify contents
		DicomComparator.compare(dob, loadedDcm);

	}

}


text:
package tccpnoutputs

import "github.com/giantswarm/microerror"

var invalidConfigError = &microerror.Error{
	Kind: "invalidConfigError",
}

// IsInsserts invalidConfigError.
func IsInvalidConfig(err error) bool {
	return microerror.Cause(err) == invalidConfigError
}


text:
class LinePersistentReactor : public AcDbObject
{
public:
	ACRX_DECLARE_MEMBERS(LinePersistentReactor);
	LinePersistentReactor();
	LinePersistentReactor(AcDbObjectId objId);
	virtual ~LinePersistentReactor(void);

public:
	virtual Acad::ErrorStatus dwgInFields(AcDbDwgFiler* pFiler);
	virtual Acad::ErrorStatus dwgOutFields(AcDbDwgFiler* pFiler) const;

	virtual void modified(const ZcDbObject* dbObj);

private:
	AcDbObjectId m_objId;
};


text:
"""
    rtbtc
    ~~~~~

    rtbtc: a real time bitcoin analytics app
"""

from . import factory

def create_app(**kwargs):
    return factory.create_app(__name__, **kwargs)


text:
.navbar, .search-container, .jumbotron, footer, hr,.d-print-none { display: none; }

.card { border: 0px; }
html,body { font-family: arial; font-size: 10px }
table { width: 100%; border:1px solid #ccc; margin-bottom: 5px;}
th { text-align: left;}
td{ padding: 3px; }
tr:nth-child(even) { background-color:#eee;}

.col-md-6 { display:inline-block; }
.text-muted {
    color: #868e96!important; font-size: 14px; margin: 10px 0px;
}
.h5, h5 {
    font-size: 18px;
    margin:0px;
}
.h3, h3 {
    font-size: 25px; margin-bottom: 5px;
}

.alert { color: #856404; text-align: center; background-color: #fff3cd; border-color: #ffeeba; padding: .75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: .25rem;}
.page-break {page-break-after: always;}
.page-break-counter:nth-of-type(4) {page-break-after: always;}


text:
package de.iweinzierl.easyprofiles.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;

import java.util.Collections;
import java.util.List;

import de.iweinzierl.easyprofiles.R;
import de.iweinzierl.easyprofiles.persistence.Location;

public class LocationsCardAdapter extends RecyclerView.Adapter<LocationsCardAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {

        protected MapView mapView;

        protected TextView nameView;
        protected TextView latView;
        protected TextView lonView;

        protected Location location;
        protected GoogleMap map;

        public ViewHolder(View itemView) {
            super(itemView);
            this.mapView = (MapView) itemView.findViewById(R.id.map);
            this.nameView = (TextView) itemView.findViewById(R.id.name);
            this.latView = (TextView) itemView.findViewById(R.id.lat);
            this.lonView = (TextView) itemView.findViewById(R.id.lon);

            mapView.onCreate(null);
            mapView.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            map = googleMap;

            mapView.onResume();
            setLocation();
        }

        public Location getLocation() {
            return location;
        }

        public void setLocation(Location location) {
            this.location = location;

            updateViews();
            setLocation();
        }

        private void updateViews() {
            nameView.setText(String.format(
                    "%s (%s%s)",
                    location.getName(),
                    location.getRadius(),
                    context.getResources().getString(R.string.activity_locationlist_radius_in_title)));
            latView.setText(String.valueOf(location.getLat()));
            lonView.setText(String.valueOf(location.getLon()));
        }

        private void setLocation() {
            if (location != null && map != null) {
                LatLng latLng = new LatLng(location.getLat(), location.getLon());

                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);

                CircleOptions circleOptions = new CircleOptions();
                circleOptions.center(latLng);
                circleOptions.radius(location.getRadius());
                circleOptions.fillColor(R.color.ColorSecondary);

                map.moveCamera(update);
                map.addCircle(circleOptions);
            }
        }
    }

    protected final Context context;

    private List<Location> locations;

    @SuppressWarnings("unchecked")
    public LocationsCardAdapter(Context context) {
        this.context = context;
        this.locations = (List<Location>) Collections.EMPTY_LIST;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View itemView = layoutInflater.inflate(R.layout.card_item_location, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.setLocation(locations.get(position));
    }

    @Override
    public int getItemCount() {
        return locations.size();
    }

    public void setItems(List<Location> items) {
        this.locations = items;
        notifyDataSetChanged();
    }
}


text:
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@

/* -*-java-*-
 * Filename    : SQLMXConnection.java
 * Description :
 *
 */

 package org.apache.trafodion.jdbc.t2;

 import java.sql.*;
 import java.util.MissingResourceException;
 import java.util.Locale;
 import java.util.ResourceBundle;
 import java.util.PropertyResourceBundle;
 import java.text.MessageFormat;

 public class SQLMXMessages
 {
 	static SQLException createSQLException(Locale msgLocale, String messageId, Object[] messageArguments)
 	{
 		Locale currentLocale;
 		int sqlcode;

 		if (msgLocale == null)
 			currentLocale = Locale.getDefault();
 		else
 			currentLocale = msgLocale;
 		try
		{
			PropertyResourceBundle messageBundle =
			    (PropertyResourceBundle) ResourceBundle.getBundle("SQLMXT2Messages", currentLocale); //R321 changed property file name to SQLMXT2Messages_en.properties
			MessageFormat formatter = new MessageFormat("");
            formatter.setLocale(currentLocale);
            formatter.applyPattern(messageBundle.getString(messageId+"_msg"));
            String message = formatter.format(messageArguments);
            String sqlState = messageBundle.getString(messageId+"_sqlstate");
			String sqlcodeStr = messageBundle.getString(messageId+"_sqlcode");
			if (sqlcodeStr != null)
			{
				try
				{
					sqlcode = Integer.parseInt(sqlcodeStr);
					sqlcode = -sqlcode;
				}
				catch (NumberFormatException e1)
				{
					sqlcode = -1;
				}
			}
			else
				sqlcode = -1;
			return new SQLException(message, sqlState, sqlcode);
		}
		catch (MissingResourceException e)
		{
			// If the resource bundle is not found, concatenate the messageId and the parameters
			String message;
			int i = 0;

			message = "The message id: " + messageId;
			if (messageArguments != null)
			{
				message = message.concat(" With parameters: ");
				while (true)
				{
					message = message.concat(messageArguments[i++].toString());
					if (i >= messageArguments.length)
						break;
					else
						message = message.concat(",");
			    }
			}
			return new SQLException(message, "HY000", -1);
		}
 	}

 	static SQLWarning createSQLWarning(Locale msgLocale, String messageId, Object[] messageArguments)
 	{
 		Locale currentLocale;
		int sqlcode;

 		if (msgLocale == null)
 			currentLocale = Locale.getDefault();
 		else
 			currentLocale = msgLocale;
 		try
		{
			PropertyResourceBundle messageBundle =
			 (PropertyResourceBundle) ResourceBundle.getBundle("SQLMXT2Messages", currentLocale); //R321 changed property file name to SQLMXT2Messages_en.properties
			MessageFormat formatter = new MessageFormat("");
            formatter.setLocale(currentLocale);
            formatter.applyPattern(messageBundle.getString(messageId+"_msg"));
            String message = formatter.format(messageArguments);
            String sqlState = messageBundle.getString(messageId+"_sqlstate");
			String sqlcodeStr = messageBundle.getString(messageId+"_sqlcode");
			if (sqlcodeStr != null)
			{
				try
				{
					sqlcode = Integer.parseInt(sqlcodeStr);
				}
				catch (NumberFormatException e1)
				{
					sqlcode = 1;
				}
			}
			else
				sqlcode = 1;
            return new SQLWarning(message, sqlState, sqlcode);
		}
		catch (MissingResourceException e)
		{
			// If the resource bundle is not found, concatenate the messageId and the parameters
			String message;
			int i = 0;

			message = "The message id: " + messageId;
			if (messageArguments != null)
			{
				message = message.concat(" With parameters: ");
				while (true)
				{
					message = message.concat(messageArguments[i++].toString());
					if (i >= messageArguments.length)
						break;
					else
						message = message.concat(",");
				}
			}
			return new SQLWarning(message, "01000", 1);
		}
 	}
 	static void throwUnsupportedFeatureException(Locale locale, String s) throws SQLException
    {
        Object[] messageArguments = new Object[1];
		messageArguments[0] = s;
        throw SQLMXMessages.createSQLException(locale, "unsupported_feature", messageArguments);
    }
    static void throwDeprecatedMethodException(Locale locale, String s) throws SQLException
    {
        Object[] messageArguments = new Object[1];
		messageArguments[0] = s;
        throw SQLMXMessages.createSQLException(locale, "deprecated_method", messageArguments);
    }

 }