text:
import struct

class v_enum: pass

class v_base(object):
    def __init__(self):
        self._vs_meta = {}

    def vsGetMeta(self, name, defval=None):
        return self._vs_meta.get(name, defval)

    def vsSetMeta(self, name, value):
        self._vs_meta[name] = value

    # Sub-classes (primitive base, or VStruct must have these
    def vsParse(self, bytes): return NotImplemented
    def vsGetFormat(self): return NotImplemented
    def vsIsPrim(self): return NotImplemented
    def vsGetTypeName(self): return NotImplemented

class v_prim(v_base):

    def __init__(self):
        v_base.__init__(self)
        # Used by base len(),vsGetFormat, etc...
        self._vs_value = None
        self._vs_length = None
        self._vs_fmt = None

    def vsIsPrim(self):
        return True

    def vsGetTypeName(self):
        return self.__class__.__name__

    def vsParse(self, bytes):
        """
        Parser for primitives which assumes we are
        calling parse directly.
        """
        fmt = "<%s" % self.vsGetFormat()
        val = struct.unpack(fmt, bytes)[0]
        self.vsSetParsedValue(val)

    def vsSetParsedValue(self, value):
        """
        Primitives will be assigned their values by a parser
        which chops data up with struct format strings.  This
        method will be called by parsers to assign the value
        of a primitive from a struct.unpack call.
        """
        self._vs_value = value

    def vsGetFmtValue(self):
        """
        The emit function uses this to ask each primitive for the
        object to be put into the struct pack sequence.
        Most objects just return their value...
        """
        return self._vs_value

    def vsGetValue(self):
        """
        Get the type specific value for this field.
        (Used by the structure dereference method to return
        a python native for the field by name)
        """
        return self._vs_value

    def vsSetValue(self, value):
        """
        Set the type specific value for this field.
        """
        self._vs_value = value

    def vsGetFormat(self):
        return self._vs_fmt

    def __repr__(self):
        return repr(self.vsGetValue())

    def __len__(self):
        return self._vs_length

    def __str__(self):
        return str(self.vsGetValue())

class v_number(v_prim):

    def __init__(self, value=0, swapend=False):
        v_prim.__init__(self)
        self._vs_swapend = swapend
        self._vs_length = struct.calcsize(self.vsGetFormat())
        self.vsSetValue(value)

    def vsSetValue(self, value):
        """
        Assure that the value is long() able for all numeric types.
        """
        self._vs_value = long(value)

    def vsSetParsedValue(self, value):
        # We were parsed N endian.  Switch if needed.
        if self._vs_swapend:
            oval = value
            value = 0
            for i in range(self._vs_length):
                value = value << 8
                value += (oval >> (8*i)) & 0xff
        self.vsSetValue(value)

    def vsGetFormat(self):
        return self.__class__._vs_fmt

    def __int__(self):
        return int(self._vs_value)

    def __long__(self):
        return long(self._vs_value)

    ##################################################################
    # Implement the number API

    def __add__(self, other): return long(self) + long(other)
    def __sub__(self, other): return long(self) - long(other)
    def __mul__(self, other): return long(self) * long(other)
    def __div__(self, other): return long(self) / long(other)
    def __floordiv__(self, other): return long(self) // long(other)
    def __mod__(self, other): return long(self) % long(other)
    def __divmod__(self, other): return divmod(long(self), long(other))
    def __pow__(self, other, modulo=None): return pow(long(self), long(other), modulo)
    def __lshift__(self, other): return long(self) << long(other)
    def __rshift__(self, other): return long(self) >> long(other)
    def __and__(self, other): return long(self) & long(other)
    def __xor__(self, other): return long(self) ^ long(other)
    def __or__(self, other): return long(self) | long(other)

    # Operator swapped variants
    def __radd__(self, other): return long(other) + long(self)
    def __rsub__(self, other): return long(other) - long(self)
    def __rmul__(self, other): return long(other) * long(self)
    def __rdiv__(self, other): return long(other) / long(self)
    def __rfloordiv__(self, other): return long(other) // long(self)
    def __rmod__(self, other): return long(other) % long(self)
    def __rdivmod__(self, other): return divmod(long(other), long(self))
    def __rpow__(self, other, modulo=None): return pow(long(other), long(self), modulo)
    def __rlshift__(self, other): return long(other) << long(self)
    def __rrshift__(self, other): return long(other) >> long(self)
    def __rand__(self, other): return long(other) & long(self)
    def __rxor__(self, other): return long(other) ^ long(self)
    def __ror__(self, other): return long(other) | long(self)

    # Inplace variants
    def __iadd__(self, other): self.vsSetValue(self+other); return self
    def __isub__(self, other): self.vsSetValue(self - other); return self
    def __imul__(self, other): self.vsSetValue(self*other); return self
    def __idiv__(self, other): self.vsSetValue(self/other); return self
    def __ifloordiv__(self, other): self.vsSetValue(self // other); return self
    def __imod__(self, other): self.vsSetValue(self % other); return self
    def __ipow__(self, other, modulo=None): self.vsSetValue(pow(self, other, modulo)); return self
    def __ilshift__(self, other): self.vsSetValue(self << other); return self
    def __irshift__(self, other): self.vsSetValue(self >> other); return self
    def __iand__(self, other): self.vsSetValue(self & other); return self
    def __ixor__(self, other): self.vsSetValue(self ^ other); return self
    def __ior__(self, other): self.vsSetValue(self | other); return self

    # operator helpers
    def __neg__(self): return -(long(self))
    def __pos__(self): return +(long(self))
    def __abs__(self): return abs(long(self))
    def __invert__(self): return ~(long(self))

    # index use helper
    def __index__(self): return long(self)

    def __coerce__(self, other):
        try:
            return long(self),long(other)
        except Exception, e:
            return NotImplemented

    # Print helpers
    def __hex__(self): return hex(long(self))
    def __oct__(self): return oct(long(self))

class v_uint8(v_number):
    _vs_builder = True
    _vs_fmt = "B"

class v_uint16(v_number):
    _vs_builder = True
    _vs_fmt = "H"

class v_uint32(v_number):
    _vs_builder = True
    _vs_fmt = "L"

class v_uint64(v_number):
    _vs_builder = True
    _vs_fmt = "Q"

class v_int8(v_number):
    _vs_builder = True
    _vs_fmt = "b"

class v_int16(v_number):
    _vs_builder = True
    _vs_fmt = "h"

class v_int32(v_number):
    _vs_builder = True
    _vs_fmt = "l"

class v_int64(v_number):
    _vs_builder = True
    _vs_fmt = "q"

pointersize = struct.calcsize("P")

class v_size_t(v_number):
    _vs_builder = True
    if pointersize == 4:
        _vs_fmt = "L"
    else:
        _vs_fmt = "Q"

    def __repr__(self):
        return "0x%.8x" % self._vs_value

class v_ptr(v_size_t):
    pass

class v_ptr32(v_ptr):
    _vs_builder = True
    _vs_fmt = "L"

class v_ptr64(v_ptr):
    _vs_builder = True
    _vs_fmt = "Q"

class v_bytes(v_prim):

    _vs_builder = True

    def __init__(self, size=0, vbytes=None):
        v_prim.__init__(self)
        if vbytes == None:
            vbytes = '\x00' * size
        self._vs_length = len(vbytes)
        self._vs_value = vbytes

    def vsGetFormat(self):
        return "%ds" % len(self)

    def __repr__(self):
        return self._vs_value.encode('hex')

class v_str(v_prim):
    '''
    A string placeholder class which will automagically return
    up to a null terminator (and will keep it's size by null
    padding when assigned to)
    '''

    _vs_builder = True

    def __init__(self, size=4, val=''):
        v_prim.__init__(self)
        self._vs_length = size
        self._vs_value = val.ljust(size, '\x00')

    def vsGetValue(self):
        val = v_prim.vsGetValue(self)
        return val.split("\x00")[0]

    def vsSetValue(self, val):
        realval = val.ljust(len(self), '\x00')
        v_prim.vsSetValue(self, realval)

    def vsGetFormat(self):
        return "%ds" % len(self)

    def __len__(self):
        return len(self._vs_value)

class v_wstr(v_str):
    '''
    Unicode variant of the above string class

    NOTE: the size paramater is in WCHARs!
    '''

    _vs_builder = True

    def __init__(self, size=4, encode='utf-16le', val=''):
        v_prim.__init__(self)
        b = val.ljust(size, '\x00').encode(encode)
        self._vs_length = len(b)
        self._vs_value = b
        self._vs_encode = encode

    def vsGetValue(self):
        val = v_prim.vsGetValue(self)
        val = val.decode(self._vs_encode)
        return val.split("\x00")[0]

    def vsSetValue(self, val):
        rbytes = val.encode(self._vs_encode)
        rbytes = rbytes.ljust(len(self), '\x00')
        v_prim.vsSetValue(self, rbytes)

    def vsGetFormat(self):
        return "%ds" % len(self)

    def __len__(self):
        return len(self._vs_value)

class GUID(v_prim):

    _vs_builder = True

    def __init__(self, guidstr=None):
        """
        Construct a new GUID primitive.  You may specify a GUID string in the
        constructor to populate initial values.
        """
        v_prim.__init__(self)
        self._vs_length = 16
        self._vs_value = "\x00" * 16
        self._vs_fmt = "16s"
        self._guid_fields = (0,0,0,0,0,0,0,0,0,0,0)
        if guidstr != None:
            self._parseGuidStr(guidstr)

    def _parseGuidStr(self, gstr):
        gstr = gstr.replace("{","")
        gstr = gstr.replace("}","")
        gstr = gstr.replace("-","")
        bytes = gstr.decode("hex")
        # Totally cheating... ;)
        self._guid_fields = struct.unpack(">LHH8B", bytes)

    def vsSetValue(self, bytes):
        self._guid_fields = struct.unpack("<LHH8B", bytes)

    def vsGetValue(self):
        return struck.pack("<LHH8B", *self._guid_fields)

    def __repr__(self):
        base = "{%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x}"
        return base  % self._guid_fields


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="利用可能な地域情報" />
<meta content="Territories, supported" name="DC.subject" />
<meta content="Territories, supported" name="keywords" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj75638" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>利用可能な地域情報</title>

利用可能な地域情報

利用可能な地域情報を以下に挙げます。

地域

Derbyの地域設定(derby.territory)

中国語(簡体字)

zh_CN

中国語(繁体字)

zh_TW

チェコ語

cs

フランス語

fr

ドイツ語

de_DE

ハンガリー語

hu

イタリア語

it

日本語

ja_JP

韓国語

ko_KR

ポーランド語

pl

ポルトガル語(ブラジル語)

pt_BR

ロシア語

ru

スペイン語

es

redpajama_set_name: RedPajamaGithub


text:
import click

@click.command()
@click.option('--as-cowboy', '-c', is_flag=True, help='Greet as a cowboy.')
@click.argument('name', default='world', required=False)
def main(name, as_cowboy):
    """A Tool for the Russian National Corpus"""
    greet = 'Howdy' if as_cowboy else 'Hello'
    click.echo('{0}, {1}.'.format(greet, name))


text:
package hooks

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"strings"

	"moul.io/assh/v2/pkg/templates"
)

// ExecDriver is a driver that execs some texts to the terminal
type ExecDriver struct {
	line string
}

// NewExecDriver returns a ExecDriver instance
func NewExecDriver(line string) (ExecDriver, error) {
	return ExecDriver{
		line: line,
	}, nil
}

// Run execs a line to the terminal
func (d ExecDriver) Run(args RunArgs) error {
	var buff bytes.Buffer
	tmpl, err := templates.New(d.line + "\n")
	if err != nil {
		return err
	}

	if err := tmpl.Execute(&buff, args); err != nil {
		return err
	}

	var (
		availableShells = []string{
			"/bin/sh", "/bin/bash", "/bin/zsh",
			"/usr/bin/sh", "/usr/bin/bash", "/usr/bin/zsh",
			"/usr/local/bin/sh", "/usr/local/bin/bash", "/usr/local/bin/zsh",
		}
		selectedShell = ""
	)
	for _, shell := range availableShells {
		info, err := os.Stat(shell)
		if err != nil {
			continue
		}
		if info.Mode()&0111 != 0 {
			selectedShell = shell
			break
		}
	}
	if selectedShell == "" {
		return fmt.Errorf("no available shell found. (tried %s)", strings.Join(availableShells, ", "))
	}

	cmd := exec.Command(selectedShell, "-c", buff.String()) // #nosec
	cmd.Stdout = os.Stderr
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin
	if err := cmd.Start(); err != nil {
		return err
	}
	return cmd.Wait()
}

// Close is mandatory for the interface, here it does nothing
func (d ExecDriver) Close() error { return nil }


text:
from django.conf.urls import url as djurl
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404
from django.utils.encoding import smart_str

class BreadRegexURLPattern(RegexURLPattern):

    verbose_name = None

    def resolve(self, *args, **kwargs):
        rm = super(BreadRegexURLPattern, self).resolve(*args, **kwargs)
        if rm:
            rm.breadcrumb_verbose_name = self.verbose_name
        return rm

class BreadRegexURLResolver(RegexURLResolver):

    def resolve(self, path):
        '''
        this is rewritten from django.core.urlresolvers
        because playing with URL patterns and resolvers in Django<=1.4 is weird.
        Probably because of the recursion.
        Really! Try it yourself.
        FIXME: As of Django 1.4 this shouldn't be necessary!
        '''
        tried = []
        match = self.regex.search(path)
        if match:
            new_path = path[match.end():]
            for pattern in self.url_patterns:
                try:
                    sub_match = pattern.resolve(new_path)
                except Resolver404 as e:
                    sub_tried = e.args[0].get('tried')
                    if sub_tried is not None:
                        tried.extend([[pattern] + t for t in sub_tried])
                    else:
                        tried.append([pattern])
                else:
                    if sub_match:
                        sub_match_dict = dict([(smart_str(k), v) for k, v in match.groupdict().items()])
                        sub_match_dict.update(self.default_kwargs)
                        for k, v in sub_match.kwargs.items():
                            sub_match_dict[smart_str(k)] = v
                        res_match = ResolverMatch(sub_match.func, sub_match.args, sub_match_dict,
                                                  sub_match.url_name,
                                                  self.app_name or sub_match.app_name,
                                                  [self.namespace] + sub_match.namespaces)
                        res_match.breadcrumb_verbose_name = getattr(sub_match,
                                                                    'breadcrumb_verbose_name', None)

                        return res_match
                    tried.append([pattern])
            raise Resolver404({'tried': tried, 'path': new_path})
        raise Resolver404({'path' : path})

def url(*args, **kwargs):

    vn = kwargs.pop("verbose_name", None)

    if not vn:
        if len(args) >= 2:
            # regex, view ...
            vn = getattr(args[1], 'urlbreadcrumbs_verbose_name', None)

    reg = djurl(*args, **kwargs)

    if isinstance(reg, RegexURLPattern):
        reg.__class__ = BreadRegexURLPattern
        reg.verbose_name = vn
    elif isinstance(reg, RegexURLResolver):
        reg.__class__ = BreadRegexURLResolver

    return reg


text:
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace GMapDemo
{
    /// <summary>
    /// GMap.Net 库使用Demo
    /// 日期:2014年10月14日
    /// 作者:于小懒
    ///
    /// 说明:marker宏定义部分为演示默认marker和用户自定marker的使用方法
    ///     刚入门时候先关闭MARKER宏 不影响执行 以便能看到最简单地图加载和操作逻辑。
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        PointLatLng center = new PointLatLng(40, 118);

#if MARKER

        /// <summary>
        /// 放marker的层
        /// </summary>
        GMapOverlay markersOverlay;

        /// <summary>
        /// google marker
        /// </summary>
        GMarkerGoogle marker;

        /// <summary>
        /// 自定义 marker
        /// </summary>
        GMapMarkerRect rectMarker;

        //拖拽rectMarker 时候的补差.
        //rectMarker以中心点为准定坐标 如果没选到中心点拖拽就会产生问题 矩形框中心点会一下跳到鼠标所在位置。
        private PointLatLng _drag_fix_offset = new PointLatLng();
#endif
        private void Form1_Load(object sender, EventArgs e)
        {
            //GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;

            /**
             * 用两个GMapControl创建一大一小两个地图
             * 拖动大地图,影响小地图。
             **/

            InitSmallMap();
            InitBigMap();
        }

        /// <summary>
        /// 初始化小地图
        /// </summary>
        public void InitSmallMap()
        {
            smallMap.MapProvider = GMapProviders.GoogleChinaMap;
            smallMap.MinZoom = 0;
            smallMap.MaxZoom = 18;
            smallMap.Zoom = 10;
            smallMap.Position = center;
        }

        /// <summary>
        /// 初始化大地图
        /// </summary>
        public void InitBigMap()
        {

            bigMap.MapProvider = GMapProviders.GoogleChinaMap;
            bigMap.MinZoom = 0;
            bigMap.MaxZoom = 18;
            bigMap.Zoom = 8;
            bigMap.Position = center;

            bigMap.MouseMove += gmap_MouseMove;
            bigMap.MouseDown += gmap_MouseDown;
            bigMap.MouseUp += bigMap_MouseUp;

#if MARKER
            bigMap.OnMarkerEnter += bigMap_OnMarkerEnter;
            bigMap.OnMarkerLeave += bigMap_OnMarkerLeave;

            markersOverlay = new GMapOverlay("markers");
            marker = new GMarkerGoogle(center, GMarkerGoogleType.green);

            //overlay 上可以有很多 marker
            markersOverlay.Markers.Add(marker);
            markersOverlay.Markers.Add(new GMapMarkerRect(center));
            bigMap.Overlays.Add(markersOverlay);
#endif
        }

#if MARKER
        void bigMap_OnMarkerLeave(GMapMarker item)
        {
            if (item is GMapMarkerRect)
            {
                rectMarker = null;

                GMapMarkerRect rc = item as GMapMarkerRect;
                rc.Pen.Color = Color.Green;

                Debug.WriteLine("OnMarkerLeave: " + item.Position);
            }
        }

        void bigMap_OnMarkerEnter(GMapMarker item)
        {
            if (item is GMapMarkerRect)
            {
                GMapMarkerRect rc = item as GMapMarkerRect;
                rc.Pen.Color = Color.Red;

                rectMarker = rc;

                Debug.WriteLine("OnMarkerEnter: " + item.Position);
            }
        }
#endif

        //鼠标是否按下
        bool isMouseDown = false;

        void gmap_MouseDown(object sender, MouseEventArgs e)
        {
#if MARKER
            PointLatLng pos = bigMap.FromLocalToLatLng(e.X, e.Y);//x,y -> 经纬度

            if (rectMarker != null)
            {
                _drag_fix_offset = new PointLatLng(rectMarker.Position.Lat - pos.Lat, rectMarker.Position.Lng - pos.Lng);
            }
            else {
                marker.Position = pos;
            }
#endif
            if (e.Button == MouseButtons.Left)
            {
                isMouseDown = true;
            }
        }

        void bigMap_MouseUp(object sender, MouseEventArgs e)
        {
#if MARKER
            _drag_fix_offset = new PointLatLng();
#endif
        }

        private void gmap_MouseMove(object sender, MouseEventArgs e)
        {
            bool isDragging = e.Button == MouseButtons.Left && isMouseDown;
            if (isDragging)
            {

                PointLatLng pos = bigMap.FromLocalToLatLng(e.X, e.Y);//x,y -> 经纬度
#if MARKER
                if (rectMarker == null)
                {
                    if (marker.IsVisible)
                    {
                        marker.Position = pos;
                    }
                }
                else
                {

                    smallMap.Position = pos;

                    if (rectMarker.IsVisible)
                    {
                        rectMarker.Position = new PointLatLng(pos.Lat + _drag_fix_offset.Lat, pos.Lng + _drag_fix_offset.Lng);
                    }
                }
#else
                smallMap.Position = pos;
#endif
                //smallMap.Refresh();
                //bigMap.Refresh();
            }
        }
    }
}


text:
import Header from './header'
import React from 'react'

class TrialDetailsView extends React.Component {

    constructor(props) {
        super(props)
        console.log('trial details view', props)

        this.state = {
            trialModel: props.trialModel
        }
    }

    render() {
        return (

                <TrialDetails trialModel = {this.state.trialModel}/>

        )
    }
}

class TrialDetails extends React.Component {

    constructor(props) {
        super(props)

        console.log('trial details', props)

        this.state = {
            trialModel: props.trialModel
        }
        console.log('state', this.state)
    }

    _getJSXArray(contactArray) {
        let newArray = []

        contactArray.forEach( (contact) => {
            newArray.push(<ContactInfo contactModel = {contact} />
            )
        })
        return newArray
    }

    render() {
        return (

Title: {this.state.trialModel.get("official_title")}

Description: {this.state.trialModel.get("detail_description")}

                {this._getJSXArray(this.state.trialModel.get('sites'))}

        )
    }
}

class ContactInfo extends React.Component {

    constructor(props) {
        super(props)
        console.log('contactinfo', props)

        this.state = {
            contactModel: props.contactModel
        }
        console.log('state2', this.state.contactModel)
    }

    render () {
        return (

Contact Name: {this.state.contactModel.contact_name}

Contact Phone: {this.state.contactModel.contact_phone}

 Organization Name: {this.state.contactModel.org_name}

Organization Address: {this.state.contactModel.org_address_line_1}

{this.state.contactModel.org_city}

{this.state.contactModel.org_state_or_province}

{this.state.contactModel.org_postal_code}

{this.state.contactModel.org_phone}

        )
    }
}

export default TrialDetailsView


text:
package main

import (
	"fmt"
	"github.com/aliyun/aliyun-tablestore-go-sdk/timeline"
	"log"
	"time"
)

func main() {
	//set builder config
	storeBuilder := timeline.StoreOption{
		Endpoint:  "<Your instance endpoint>",
		Instance:  "<Your instance name>",
		TableName: "<Your table name>",
		AkId:      "<Your ak id>",
		AkSecret:  "<Your ak secret>",
		TTL:       365 * 24 * 3600, // Data time to alive, eg: almost one year
	}
	syncBuilder := timeline.StoreOption{
		Endpoint:  "<Your instance endpoint>",
		Instance:  "<Your instance name>",
		TableName: "<Your table name>",
		AkId:      "<Your ak id>",
		AkSecret:  "<Your ak secret>",
		TTL:       30 * 24 * 3600, // Data time to alive, eg: almost one month
	}

	// create a feed for user_A
	feedA, err := NewFeed("user_A", storeBuilder, syncBuilder, timeline.DefaultStreamAdapter)
	if err != nil {
		log.Fatal("init feed failed: ", err)
	}

	// create a feed for user_B
	feedB, err := NewFeed("user_B", storeBuilder, syncBuilder, timeline.DefaultStreamAdapter)
	if err != nil {
		log.Fatal("init feed failed: ", err)
	}

	// user_A followed user_B
	feedB.followers = append(feedB.followers, "user_A")

	// user_B post an activity stream
	activity := &timeline.StreamMessage{
		Id:        "client@1",
		Content:   "TableStore is fantastic!",
		Timestamp: time.Now().UnixNano(),
		Attr: map[string]interface{}{
			"Position": "shanghai-ali center",
		},
	}
	failedFollows, err := feedB.Post(activity)
	if err != nil {
		log.Fatal("user_B post new activity failed: ", err)
	}
	if len(failedFollows) != 0 {
		log.Fatal("user_B post new activity to some follower failed, failed user list:", failedFollows)
	}

	// user_A refresh and see user_B's new activity
	lastRead := int64(0)
	entries, err := feedA.Refresh(lastRead)
	if err != nil {
		log.Fatal("user_A refresh activities failed: ", err)
	}
	for _, entry := range entries {
		fmt.Printf("New activity: sequence %d\n", entry.Sequence)
		act := entry.Message.(*timeline.StreamMessage)
		fmt.Printf("Detail: %s\nTime: %v\nPosition: %s\n", act.Content,
			time.Unix(0, act.Timestamp), act.Attr["Position"])
		fmt.Println()
	}

	// user_B check his own history activities
	entries, err = feedB.OwnHistory(100)
	if err != nil {
		log.Fatal("user_B get hisotry activities failed: ", err)
	}
	for _, entry := range entries {
		fmt.Printf("History activity: sequence %d\n", entry.Sequence)
		act := entry.Message.(*timeline.StreamMessage)
		fmt.Printf("Detail: %s\nTime: %v\nPosition: %s\n", act.Content,
			time.Unix(0, act.Timestamp), act.Attr["Position"])
		fmt.Println()
	}
}


text:
#ifndef TNT_UTILS_PANIC_H
#define TNT_UTILS_PANIC_H

#include <string>

#include <utils/CallStack.h>
#include <utils/compiler.h>

#ifdef __EXCEPTIONS
#   define UTILS_EXCEPTIONS 1
#else
#endif

/**
 * @defgroup errors Handling Catastrophic Failures (Panics)
 *
 * @brief Failure detection and reporting facilities
 *
 * ## What's a Panic? ##
 *
 * In the context of this document, a _panic_ is a type of error due to a _contract violation_,
 * it shouldn't be confused with a _result_ or _status_ code. The POSIX API for instance,
 * unfortunately often conflates the two.
 * @see <http://en.wikipedia.org/wiki/Design_by_contract>
 *
 *
 * Here we give the following definition of a _panic_:
 *
 *   1. Failures to meet a function's own **postconditions**\n
 *      The function cannot establish one of its own postconditions, such as (but not limited to)
 *      producing a valid return value object.
 *
 *      Often these failures are only detectable at runtime, for instance they can be caused by
 *      arithmetic errors, as it was the case for the Ariane 5 rocket. Ariane 5 crashed because it
 *      reused an inertial module from Ariane 4, which didn't account for the greater horizontal
 *      acceleration of Ariane 5 and caused an overflow in the computations. Ariane 4's module
 *      wasn't per-say buggy, but was improperly used and failed to meet, obviously, certain
 *      postconditions.
 *      @see <http://en.wikipedia.org/wiki/Cluster_(spacecraft)>
 *
 *   2. Failures to meet the **preconditions** of any of a function's callees\n
 *      The function cannot meet a precondition of another function it must call, such as a
 *      restriction on a parameter.
 *
 *      Not to be confused with the case where the preconditions of a function are already
 *      violated upon entry, which indicates a programming error from the caller.
 *
 *      Typically these failures can be avoided and arise because of programming errors.
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * ## Failure reporting vs. handling ##
 *
 * Very often when a panic, as defined above, is detected, the program has little other choice
 * but to terminate.\n
 * Typically these situations can be handled by _assert()_. However, _assert()_ also conflates two
 * very different concepts: detecting and handling failures.\n
 * The place where a failure is detected is rarely the place where there is enough
 * context to decide what to do. _assert()_ terminates the program which, may or may not be
 * appropriate. At the very least the failure must be logged (which _assert()_ does in a crude way),
 * but some other actions might need to happen, such as:\n
 *
 *   - logging the failure in the system-wide logger
 *   - providing enough information in development builds to analyze/debug the problem
 *   - cleanly releasing some resources, such as communication channels with other processes\n
 *     e.g.: to avoid their pre- or postconditions from being violated as well.
 *
 * In some _rare_ cases, the failure might even be ignored altogether because it doesn't matter in
 * the context where it happened. This decision clearly doesn't always lie at the failure-site.
 *
 * It is therefore important to separate failure detection from handling.
 *
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * ## Failure detection and handling facilities ##
 *
 * Clearly, catastrophic failures should be **rare**; in fact they should
 * never happen, except possibly for "failures to meet a function's own postconditions", which
 * may depend on external factors and should still be very rare. Yet, when a failure happens, it
 * must be detected and handled appropriately.\n
 * Since panics are rare, it is desirable that the handling mechanism be as unobtrusive
 * as possible, without allowing such failures to go unnoticed or swallowed by mistake. Ideally, the
 * programmer using an API should have nothing special to do to handle that API's failure
 * conditions.\n\n
 *
 * An important feature of the Panic Handling facilities here is that **panics are not part of
 * the API of a function or method**\n\n
 *
 *
 * The panic handling facility has the following benefits:
 *   - provides an easy way to detect and report failure
 *   - separates failure detection from handling
 *   - makes it hard for detected failures to be ignored (i.e.: not handled)
 *   - doesn't add burden on the API design
 *   - doesn't add overhead (visual or otherwise) at call sites
 *   - has very little performance overhead for failure detection
 *   - has little to no performance impact for failure handling in the common (success) case
 *   - is flexible and extensible
 *
 * Since we have established that failures are **rare**, **exceptional** situations, it would be
 * appropriate to handle them with an _assert_ mechanism and that's what the API below
 * provides. However, under-the-hood it uses C++ exceptions as a means to separate
 * _reporting_ from _handling_.
 *
 *   \note On devices where exceptions are not supported or appropriate, these APIs can be turned
 *   into a regular _std::terminate()_.
 *
 *
 *          ASSERT_PRECONDITION(condition, format, ...)
 *          ASSERT_POSTCONDITION(condition, format, ...)
 *          ASSERT_ARITHMETIC(condition, format, ...)
 *          ASSERT_DESTRUCTOR(condition, format, ...)
 *
 *
 * @see ASSERT_PRECONDITION, ASSERT_POSTCONDITION, ASSERT_ARITHMETIC
 * @see ASSERT_DESTRUCTOR
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * ## Writing code that can assert ##
 *
 * Because we've separated failure reporting from failure handling, there are some considerations
 * that need to be thought about when writing code that calls the macros above (i.e.: the program
 * won't terminate at the point where the failure is detected).\n\n
 *
 *
 * ### Panic guarantees ###
 *
 * After the failure condition is reported by a function, additional guarantees may be provided
 * with regards to the state of the program. The following four levels of guarantee are
 * generally recognized, each of which is a strict superset of its successors:
 *
 *  1. Nothrow exception guarantee\n
 *     The function never asserts. e.g.: This should always be the case with destructors.\n\n
 *
 *  2. Strong exception guarantee\n
 *     If the function asserts, the state of the program is rolled back to the state just before
 *     the function call.\n\n
 *
 *  3. Basic exception guarantee\n
 *     If the function asserts, the program is in a valid state. It may require cleanup,
 *     but all invariants are intact.\n\n
 *
 *  4. No exception guarantee\n
 *     If the function asserts, the program may not be in a valid state: resource leaks, memory
 *     corruption, or other invariant-destroying failures may have occurred.
 *
 * In each function, give the **strongest** safety guarantee that won't penalize callers who
 * don't need it, but **always give at least the basic guarantee**. The RAII (Resource
 * Acquisition Is Initialization) pattern can help with achieving these guarantees.
 *
 * @see [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization)
 *
 * ### Special considerations for Constructors ###
 *
 * Constructors are a bit special because if a failure occurs during their execution, the
 * destructor won't be called (how could it? since the object wasn't constructed!). This can lead
 * to leaked resources allocated in the constructor prior to the failure. Thankfully there is
 * a nice C++ syntax to handle this case:
 *
 * @code
 *          Foo::Foo(size_t s) try : m_size(s), m_buf(new uint32_t[s]) {
 *              ASSERT_POSTCONDITION(s&0xF==0,
 *                  "object size is %u, but must be multiple of 16", s);
 *          } catch (...) {
 *              delete [] m_buf;
 *              // the exception will be automatically re-thrown
 *          }
 * @endcode
 *
 * Unfortunately, this usage leaks the underlying, exception-based, implementation of the
 * panic handling macros. For this reason, it is best to keep constructors simple and guarantee
 * they can't fail. An _init()_ function with a factory can be used for actual initialization.
 *
 *
 * ### Special considerations for Destructors ###
 *
 * In C++ destructors cannot throw exceptions and since the above macros internally use exceptions
 * they cannot be used in destructors. Doing so will result in immediate termination of the
 * program by _std::terminate()_.\n
 * It is therefore best to always guarantee that destructors won't fail. In case of such a
 * failure in a destructor the ASSERT_DESTRUCTOR() macro can be used instead, it
 * will log the failure but won't terminate the program, instead it'll proceed as if nothing
 * happened. Generally this will result in some resource leak which, eventually, will cause
 * another failure (typically a postcondition violation).\n\n
 *
 * Rationale for this behavior: There are fundamentally no way to report a failure from a
 * destructor in C++, violently terminating the process is inadequate because it again conflates
 * failure reporting and failure handling; for instance a failure in glDeleteTextures() shouldn't
 * be necessarily fatal (certainly not without saving the user's data first). The alternative
 * would be for the caller to swallow the failure entirely, but that's not great either because the
 * failure would go unnoticed. The solution retained here is a compromise.
 *
 * @see ASSERT_DESTRUCTOR
 *
 * ### Testing Code that Uses Panics ###
 *
 * Since panics use exceptions for their underlying implementation, you can test code that uses
 * panics with EXPECT_THROW by doing the following things:
 * \li Set panic mode to THROW (default is TERMINATE)
 * \li Pass Panic to EXPECT_THROW as the exception type
 *
 * Example code for your test file:
 *
 * @code
 * #include <MyClass.hpp>  // since your code uses panics, this should include utils/Panic.hpp
 *
 * using utils::Panic;
 *
 * TEST(MyClassTest, value_that_causes_panic) {
 *     EXPECT_THROW(MyClass::function(value_that_causes_panic), Panic);
 * }
 *
 * // ... other tests ...
 *
 * int main(int argc, char** argv) {
 *     ::testing::InitGoogleTest(&argc, argv);
 *     Panic::setMode(Panic::Mode::THROW);
 *     return RUN_ALL_TESTS();
 * }
 * @endcode
 *
 */

namespace utils {

// -----------------------------------------------------------------------------------------------

/**
 * @ingroup errors
 *
 * \brief Base class of all exceptions thrown by all the ASSERT macros
 *
 * The Panic class provides the std::exception protocol, it is the base exception object
 * used for all thrown exceptions.
 */
class UTILS_PUBLIC Panic {
public:
    virtual ~Panic() noexcept;

    /**
     * @return a detailed description of the error
     * @see std::exception
     */
    virtual const char* what() const noexcept = 0;

    /**
     * Get the function name where the panic was detected
     * @return a C string containing the function name where the panic was detected
     */
    virtual const char* getFunction() const noexcept = 0;

    /**
     * Get the file name where the panic was detected
     * @return a C string containing the file name where the panic was detected
     */
    virtual const char* getFile() const noexcept = 0;

    /**
     * Get the line number in the file where the panic was detected
     * @return an integer containing the line number in the file where the panic was detected
     */
    virtual int getLine() const noexcept = 0;

    /**
     * Logs this exception to the system-log
     */
    virtual void log() const noexcept = 0;

    /**
     * Get the CallStack when the panic was detected
     * @return the CallStack when the panic was detected
     */
    virtual const CallStack& getCallStack() const noexcept = 0;
};

// -----------------------------------------------------------------------------------------------

/**
 * @ingroup errors
 *
 * \brief Concrete implementation of the Panic interface.
 *
 * The TPanic<> class implements the std::exception protocol as well as the Panic
 * interface common to all exceptions thrown by the framework.
 */
template <typename T>
class UTILS_PUBLIC TPanic : public Panic {
public:
    // std::exception protocol
    const char* what() const noexcept override;

    // Panic interface
    const char* getFunction() const noexcept override;
    const char* getFile() const noexcept override;
    int getLine() const noexcept override;
    const CallStack& getCallStack() const noexcept override;
    void log() const noexcept override;

    /**
     * Depending on the mode set, either throws an exception of type T with the given reason plus
     * extra information about the error-site, or logs the error and calls std::terminate().
     * This function never returns.
     * @param function the name of the function where the error was detected
     * @param file the file where the above function in implemented
     * @param line the line in the above file where the error was detected
     * @param format printf style string describing the error
     * @see ASSERT_PRECONDITION, ASSERT_POSTCONDITION, ASSERT_ARITHMETIC
     * @see PANIC_PRECONDITION, PANIC_POSTCONDITION, PANIC_ARITHMETIC
     * @see setMode()
     */
    static void panic(char const* function, char const* file, int line, const char* format, ...)
        UTILS_NORETURN;

    /**
     * Depending on the mode set, either throws an exception of type T with the given reason plus
     * extra information about the error-site, or logs the error and calls std::terminate().
     * This function never returns.
     * @param function the name of the function where the error was detected
     * @param file the file where the above function in implemented
     * @param line the line in the above file where the error was detected
     * @param s std::string describing the error
     * @see ASSERT_PRECONDITION, ASSERT_POSTCONDITION, ASSERT_ARITHMETIC
     * @see PANIC_PRECONDITION, PANIC_POSTCONDITION, PANIC_ARITHMETIC
     * @see setMode()
     */
    static inline void panic(char const* function, char const* file, int line, const std::string& s)
        UTILS_NORETURN {
        panic(function, file, line, s.c_str());
    }

protected:
    /**
     * Creates a Panic.
     * @param reason a description of the cause of the error
     */
    explicit TPanic(std::string reason);

    /**
     * Creates a Panic with extra information about the error-site.
     * @param function the name of the function where the error was detected
     * @param file the file where the above function in implemented
     * @param line the line in the above file where the error was detected
     * @param reason a description of the cause of the error
     */
    TPanic(char const* function, char const* file, int line, std::string reason);

    ~TPanic() override;

private:
    void buildMessage();

    CallStack m_callstack;
    std::string m_reason;
    char const* const m_function = nullptr;
    char const* const m_file = nullptr;
    const int m_line = -1;
    mutable std::string m_msg;
};

namespace details {
// these are private, don't use
void panicLog(
        char const* function, char const* file, int line, const char* format, ...) noexcept;
}  // namespace details

// -----------------------------------------------------------------------------------------------

/**
 * @ingroup errors
 *
 * ASSERT_PRECONDITION uses this Panic to report a precondition failure.
 * @see ASSERT_PRECONDITION
 */
class UTILS_PUBLIC PreconditionPanic : public TPanic<PreconditionPanic> {
    // Programming error, can be avoided
    // e.g.: invalid arguments
    using TPanic<PreconditionPanic>::TPanic;
    friend class TPanic<PreconditionPanic>;
};

/**
 * @ingroup errors
 *
 * ASSERT_POSTCONDITION uses this Panic to report a postcondition failure.
 * @see ASSERT_POSTCONDITION
 */
class UTILS_PUBLIC PostconditionPanic : public TPanic<PostconditionPanic> {
    // Usually only detectable at runtime
    // e.g.: dead-lock would occur, arithmetic errors
    using TPanic<PostconditionPanic>::TPanic;
    friend class TPanic<PostconditionPanic>;
};

/**
 * @ingroup errors
 *
 * ASSERT_ARITHMETIC uses this Panic to report an arithmetic (postcondition) failure.
 * @see ASSERT_ARITHMETIC
 */
class UTILS_PUBLIC ArithmeticPanic : public TPanic<ArithmeticPanic> {
    // A common case of post-condition error
    // e.g.: underflow, overflow, internal computations errors
    using TPanic<ArithmeticPanic>::TPanic;
    friend class TPanic<ArithmeticPanic>;
};

// -----------------------------------------------------------------------------------------------
}  // namespace utils

#ifndef NDEBUG
#   define PANIC_FILE(F) (F)
#   define PANIC_FUNCTION __PRETTY_FUNCTION__
#else
#   define PANIC_FILE(F) ""
#   define PANIC_FUNCTION __func__
#endif

/**
 * PANIC_PRECONDITION is a macro that reports a PreconditionPanic
 * @param format printf-style string describing the error in more details
 */
#define PANIC_PRECONDITION(format, ...)                                                            \
    ::utils::PreconditionPanic::panic(PANIC_FUNCTION,                                              \
            PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)

/**
 * PANIC_POSTCONDITION is a macro that reports a PostconditionPanic
 * @param format printf-style string describing the error in more details
 */
#define PANIC_POSTCONDITION(format, ...)                                                           \
    ::utils::PostconditionPanic::panic(PANIC_FUNCTION,                                             \
            PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)

/**
 * PANIC_ARITHMETIC is a macro that reports a ArithmeticPanic
 * @param format printf-style string describing the error in more details
 */
#define PANIC_ARITHMETIC(format, ...)                                                              \
    ::utils::ArithmeticPanic::panic(PANIC_FUNCTION,                                                \
            PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)

/**
 * PANIC_LOG is a macro that logs a Panic, and continues as usual.
 * @param format printf-style string describing the error in more details
 */
#define PANIC_LOG(format, ...)                                                                     \
    ::utils::details::panicLog(PANIC_FUNCTION,                                                     \
            PANIC_FILE(__FILE__), __LINE__, format, ##__VA_ARGS__)

/**
 * @ingroup errors
 *
 * ASSERT_PRECONDITION is a macro that checks the given condition and reports a PreconditionPanic
 * if it evaluates to false.
 * @param cond a boolean expression
 * @param format printf-style string describing the error in more details
 */
#define ASSERT_PRECONDITION(cond, format, ...)                                                     \
    (!UTILS_LIKELY(cond) ? PANIC_PRECONDITION(format, ##__VA_ARGS__) : (void)0)

#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
#define ASSERT_PRECONDITION_NON_FATAL(cond, format, ...)                                           \
    (!UTILS_LIKELY(cond) ? PANIC_PRECONDITION(format, ##__VA_ARGS__), false : true)
#else
#define ASSERT_PRECONDITION_NON_FATAL(cond, format, ...)                                           \
    (!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
#endif

/**
 * @ingroup errors
 *
 * ASSERT_POSTCONDITION is a macro that checks the given condition and reports a PostconditionPanic
 * if it evaluates to false.
 * @param cond a boolean expression
 * @param format printf-style string describing the error in more details
 *
 * Example:
 * @code
 *     int& Foo::operator[](size_t index) {
 *         ASSERT_POSTCONDITION(index<m_size, "cannot produce a valid return value");
 *         return m_array[index];
 *     }
 * @endcode
 */
#define ASSERT_POSTCONDITION(cond, format, ...)                                                    \
    (!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION(format, ##__VA_ARGS__) : (void)0)

#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
#define ASSERT_POSTCONDITION_NON_FATAL(cond, format, ...)                                          \
    (!UTILS_LIKELY(cond) ? PANIC_POSTCONDITION(format, ##__VA_ARGS__), false : true)
#else
#define ASSERT_POSTCONDITION_NON_FATAL(cond, format, ...)                                          \
    (!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
#endif

/**
 * @ingroup errors
 *
 * ASSERT_ARITHMETIC is a macro that checks the given condition and reports a ArithmeticPanic
 * if it evaluates to false.
 * @param cond a boolean expression
 * @param format printf-style string describing the error in more details
 *
 * Example:
 * @code
 *     unt32_t floatToUInt1616(float v) {
 *         v *= 65536;
 *         ASSERT_ARITHMETIC(v>=0 && v<65536, "overflow occurred");
 *         return uint32_t(v);
 *     }
 * @endcode
 */
#define ASSERT_ARITHMETIC(cond, format, ...)                                                       \
    (!(cond) ? PANIC_ARITHMETIC(format, ##__VA_ARGS__) : (void)0)

#if defined(UTILS_EXCEPTIONS) || !defined(NDEBUG)
#define ASSERT_ARITHMETIC_NON_FATAL(cond, format, ...)                                             \
    (!UTILS_LIKELY(cond) ? PANIC_ARITHMETIC(format, ##__VA_ARGS__), false : true)
#else
#define ASSERT_ARITHMETIC_NON_FATAL(cond, format, ...)                                             \
    (!UTILS_LIKELY(cond) ? PANIC_LOG(format, ##__VA_ARGS__), false : true)
#endif

/**
 * @ingroup errors
 *
 * ASSERT_DESTRUCTOR is a macro that checks the given condition and logs an error
 * if it evaluates to false.
 * @param cond a boolean expression
 * @param format printf-style string describing the error in more details
 *
 * @warning Use this macro if a destructor can fail, which should be avoided at all costs.
 * Unlike the other ASSERT macros, this will never result in the process termination. Instead,
 * the error will be logged and the program will continue as if nothing happened.
 *
 * Example:
 * @code
 *     Foo::~Foo() {
 *        glDeleteTextures(1, &m_texture);
 *        GLint err = glGetError();
 *        ASSERT_DESTRUCTOR(err == GL_NO_ERROR, "cannot free GL resource!");
 *     }
 * @endcode
 */
#define ASSERT_DESTRUCTOR(cond, format, ...) (!(cond) ? PANIC_LOG(format, ##__VA_ARGS__) : (void)0)

#endif  // TNT_UTILS_PANIC_H


text:
var args = arguments[0] || {};

$.winDetail.setTitleControl(Alloy.createController('titleControl', {
	title : 'Product Detail'
}).getView());

var Views = [];
for (var i = 0; i < args.ProductItem.pictures.length; i++) {
	var picture = args.ProductItem.pictures[i];

	var view = Ti.UI.createView({
		backgroundColor : 'transparent',
		height : Ti.UI.SIZE
	});

	// Create an ImageView.
	var anImageView = Ti.UI.createImageView({
		image : picture,
		height : Alloy.Globals.ThemeStyles.product_slider.height,
		preventDefaultImage : true,
		hires : true
	});
	view.add(anImageView);

	Views.push(view);
};
$.scrollableView.views = Views;

$.lblName.text = args.ProductItem.title;

for (var i = 0; i < args.ProductItem.tags.length; i++) {
	var lblTag = Ti.UI.createLabel({
		color : Alloy.Globals.ThemeStyles.detail_tags.color,
		font : Alloy.Globals.ThemeStyles.detail_tags.font,
		left : 0
	});
	if ((i + 1) == args.ProductItem.tags.length) {
		lblTag.text = args.ProductItem.tags[i];
	} else {
		lblTag.text = args.ProductItem.tags[i] + ', ';
	}

	$.tagView.add(lblTag);
};

$.lblDetail.text = args.ProductItem.body;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra;
using RTLib.Render;
using RTLib.Scene;
using RTLib.Util;

namespace RTLib.Material
{
    public class ReflectionShader : IShader
    {
        public ReflectionShader(double reflectivity, IShader subshader)
        {
            Reflectivity = reflectivity;
            Subshader = subshader;
        }

        public double Reflectivity { get; set; }

        public IShader Subshader { get; set; }

        public RenderColor RunShader(Spatial spatial, Context context, TraceResult trace)
        {
            SceneObject obj = spatial as SceneObject;
            if (obj == null)
                throw new InvalidCastException("ReflectionShader can only be applied to SceneObjects");

            Vector<double> normal = obj.GetNormal(trace.Intersection);

            Vector<double> r = trace.Raycast.Direction - 2d*trace.Raycast.Direction.DotProduct(normal)*normal;
            r /= r.Norm(2d);

            Ray ray = trace.Raytracer.CreateRay(trace.Intersection, r, trace.Raycast);
            TraceResult? tr = trace.Raytracer.Trace(ray);

            RenderColor rcol;
            if (tr == null)
            {
                rcol = context.BackgroundColor;
            }
            else
            {
                rcol = tr.Value.HitObject.Shade(context, tr.Value);
            }

            RenderColor lcol = Subshader.RunShader(obj, context, trace);

            return Reflectivity*lcol*rcol + (1 - Reflectivity)*lcol;
        }
    }
}


text:
import {Resultset} from "./resultset.js";
import {Node} from "./node.js";
import {Tree} from "./tree.js";
import {postJSON} from "../utils.js";

const TAXA_URL = "/private_api/taxa";

/**
 * Class that represents a single dataset containing a list of peptides.
 *
 *
 *
 */
class Dataset {
    /**
     * Creates a Dataset object based on a list of peptides
     *
     * @param  {string[]}  [peptides=[]] A list of peptides (strings)
     */
    constructor(peptides = []) {
        this.originalPeptides = Dataset.cleanPeptides(peptides);

        /** @type {Tree} */
        this.tree = null;
        this._fa = null;
        this.baseFa = null;

        /** @type {Map<number,TaxonInfo>} */
        this.taxonMap = new Map();
        this.taxonMap.set(1, {id: 1, rank: "no rank", name: "root"});
    }

    /**
     * Processes the list of peptides set in the dataset and returns a
     * taxonomic tree.
     *
     * @param  {MPAConfig}  mpaConfig
     * @return {Promise<Tree>} Taxonomic tree
     */
    async search(mpaConfig) {
        this.resultset = new Resultset(this, mpaConfig);
        await this.resultset.process();
        const tree = this.buildTree(this.resultset.processedPeptides.values());
        const taxonInfo = Dataset.getTaxonInfo(tree.getTaxa());
        tree.setCounts();
        tree.setTaxonNames(await taxonInfo);
        tree.sortTree();
        this.tree = tree;
        this._fa = null;
        this.addTaxonInfo(await taxonInfo);
        return tree;
    }

    /**
     * Reprocesses functional analysis data with other cutoff
     * @param {number} cutoff as percent (0-100)
     * @param {string[]} sequences array of peptides to take into account
    */
    async reprocessFA(cutoff = 50, sequences = null) {
        await this.resultset.proccessFA(cutoff, sequences);
        this._fa = this.resultset.fa;
    }

    /**
     * Sets the surrent FA summary as base, accesible trough baseFa.
     */
    setBaseFA() {
        this.baseFa = this.fa.clone();
    }

    /**
     * Creates a hierarchic tree structure based on the input peptides. This is
     * also set as the tree property of the Dataset object.
     *
     * @param  {Iterable<PeptideInfo>} peptides A list of peptides to build the tree
     *   from
     * @return {Tree} A taxon tree containing all peptides
     */
    buildTree(peptides) {
        const tree = new Tree();
        for (const peptide of peptides) {
            let currentNode = tree.getRoot();
            for (const taxid of peptide.lineage) {
                if (taxid !== null) {
                    let newNode = currentNode.getChild(taxid);
                    if (newNode === null) {
                        newNode = new Node(taxid);
                        tree.addChild(currentNode, newNode);
                    }
                    currentNode = newNode;
                }
            }
            currentNode.addValue(peptide);
        }
        return tree;
    }

    /**
     * Creates a tree like structure, that is this.tree where each node has an
     * `included` property. This property indicaes if this node or any of its
     * childs contain the saught for functional annlotation (code).
     *
     * @param  {string} code The FA term to look for
     *   from
     * @return {Promise<Object>} A taxon tree-like object annotated with `included`
     */
    async getFATree(code) {
        const pepts = (await this.getPeptidesByFA(code)).map(pept => pept.sequence);
        return this.tree.getRoot().callRecursivelyPostOder((t, c) => {
            const included = c.some(x => x.included) || t.values.some(pept => pepts.includes(pept.sequence));
            return Object.assign(Object.assign({}, t), {included: included, children: c});
        });
    }

    /**
     * Adds new taxon info to the global taxon map
     *
     * @param {TaxonInfo[]} taxonInfo A list of new taxon info
     */
    addTaxonInfo(taxonInfo) {
        for (const t of taxonInfo) {
            this.taxonMap.set(t.id, t);
        }
    }

    /**
     * Converts the current analysis to the csv format. Each row contains a
     * peptide and its lineage, with each column being a level in the taxonomy
     *
     * @return {Promise<string>} The analysis result in csv format
     */
    toCSV() {
        return this.resultset.toCSV();
    }

    /**
     * Returns the number of matched peptides, taking the deduplication setting
     * into account.
     *
     * @return {number} The number of matched peptides
     */
    getNumberOfMatchedPeptides() {
        return this.tree.root.data.count;
    }

    /**
     * Returns the number of searched for peptides, taking the deduplication
     * setting into account.
     *
     * @return {number} The number of searched for peptides
     */
    getNumberOfSearchedForPeptides() {
        return this.resultset.getNumberOfSearchedForPeptides();
    }

    /**
     * Returns the list of unmached peptides for the current resultset
     *
     * @return {string[]} An array of peptides without match
     */
    getMissedPeptides() {
        return this.resultset.missedPeptides;
    }

    /**
     * Returns a list of sequences that have the specified FA term
     * @param {String} faName The name of the FA term (GO:000112, EC:1.5.4.1)
     * @param {String[]} sequences List of sequences to limit to
     * @return {Promise<{sequence, hits, type, annotatedCount,allCount,relativeCount,count,lca,lcaName}[]>} A list of objects representing
     *                                                   the matches
     */
    getPeptidesByFA(faName, sequences) {
        return this.resultset.getPeptidesByFA(faName, sequences);
    }

    /**
     * Fetches the taxon info from the Unipept API for a list of taxon id's and
     * returns an Array of objects containing the id, name and rank for each
     * result.
     *
     * @param {number[]} taxids Array containing taxon id integers
     * @return {Promise.<TaxonInfo[]>} containing an array of result objects
     * with id, name and rank fields
     */
    static getTaxonInfo(taxids) {
        return postJSON(TAXA_URL, JSON.stringify({taxids: taxids}));
    }

    /**
     * Converts a list of peptides to uppercase
     *
     * @param  {string[]} peptides a list of peptides
     * @return {string[]} The converted list
     */
    static cleanPeptides(peptides) {
        return peptides.map(p => p.toUpperCase());
    }

    /**
     * The URL to fetch taxon info
     */
    static get TAXA_URL() {
        return TAXA_URL;
    }

    /**
     *
     * @return {GroupedFA} Functional annotaions
     */
    get fa() {
        return this._fa;
    }
}

export {Dataset};


text:
@interface ComposeEventViewController : UIViewController <UITextViewDelegate, UITabBarControllerDelegate, UIAlertViewDelegate>

@end


text:
package is.hail.rvd

import is.hail.annotations._
import is.hail.expr.ir.ExecuteContext
import is.hail.types.physical.PStruct
import is.hail.types.virtual.TInterval
import is.hail.sparkextras._
import is.hail.utils._

import scala.collection.generic.Growable

class KeyedRVD(val rvd: RVD, val key: Int) {
  require(key <= rvd.typ.key.length && key >= 0)
  val realType: RVDType = rvd.typ
  val virtType = RVDType(realType.rowType, realType.key.take(key))
  val (kType, _) = rvd.rowType.select(virtType.key)

  private def checkJoinCompatability(right: KeyedRVD) {
    if (!(kType isIsomorphicTo right.kType))
      fatal(
        s"""Incompatible join keys. Keys must have same length and types, in order:
           | Left join key type: ${ kType.toString }
           | Right join key type: ${ right.kType.toString }
         """.stripMargin)
  }

  private def checkLeftIntervalJoinCompatability(right: KeyedRVD) {
    if (!(kType.size == 1 && right.kType.size == 1
      && kType.types(0) == right.kType.types(0).asInstanceOf[TInterval].pointType))
      fatal(
        s"""Incompatible join keys in left interval join:
           | Left join key type: ${ kType.toString }
           | Right join key type: ${ right.kType.toString }
         """.stripMargin)
  }

  // 'joinedType.key' must be the join key, followed by the remaining left key,
  // followed by the (possibly renamed) remaining right key. 'joiner' must copy
  // these 'joinedType.key' fields from the corresponding fields in the
  // JoinedRegionValue.
  def orderedJoin(
    right: KeyedRVD,
    joinType: String,
    joiner: (RVDContext, Iterator[JoinedRegionValue]) => Iterator[RegionValue],
    joinedType: RVDType,
    ctx: ExecuteContext
  ): RVD = {
    checkJoinCompatability(right)

    val newPartitioner = {
      def leftPart = this.rvd.partitioner.strictify
      def rightPart = right.rvd.partitioner.coarsen(key).extendKey(realType.kType.virtualType)
      (joinType: @unchecked) match {
        case "left" => leftPart
        case "right" => rightPart
        case "inner" => leftPart.intersect(rightPart)
        case "outer" => RVDPartitioner.generate(
          kType.fieldNames,
          realType.kType.virtualType,
          leftPart.rangeBounds ++ rightPart.rangeBounds)
      }
    }
    val repartitionedLeft = rvd.repartition(ctx, newPartitioner)
    val compute: (OrderedRVIterator, OrderedRVIterator, Iterable[RegionValue] with Growable[RegionValue]) => Iterator[JoinedRegionValue] =
      (joinType: @unchecked) match {
        case "inner" => _.innerJoin(_, _)
        case "left" => _.leftJoin(_, _)
        case "right" => _.rightJoin(_, _)
        case "outer" => _.outerJoin(_, _)
      }
    val lTyp = virtType
    val rTyp = right.virtType
    val rRowPType = right.realType.rowType

    repartitionedLeft.alignAndZipPartitions(
      joinedType.copy(key = joinedType.key.take(realType.key.length)),
      right.rvd,
      key
    ) { (ctx, leftIt, rightIt) =>
      val sideBuffer = ctx.freshRegion()
      joiner(
        ctx,
        compute(
          OrderedRVIterator(lTyp, leftIt, ctx),
          OrderedRVIterator(rTyp, rightIt, ctx),
          new RegionValueArrayBuffer(rRowPType, sideBuffer)))
    }.extendKeyPreservesPartitioning(ctx, joinedType.key)
  }

  def orderedLeftIntervalJoin(
    ctx: ExecuteContext,
    right: KeyedRVD,
    joiner: PStruct => (RVDType, (RVDContext, Iterator[Muple[RegionValue, Iterable[RegionValue]]]) => Iterator[RegionValue])
  ): RVD = {
    checkLeftIntervalJoinCompatability(right)

    val lTyp = virtType
    val rTyp = right.virtType

    rvd.intervalAlignAndZipPartitions(ctx, right.rvd) {
      t: PStruct => {
        val (newTyp, f) = joiner(t)

        (newTyp, (ctx: RVDContext, it: Iterator[RegionValue], intervals: Iterator[RegionValue]) =>
          f(
            ctx,
            OrderedRVIterator(lTyp, it, ctx)
              .leftIntervalJoin(OrderedRVIterator(rTyp, intervals, ctx))))
      }
    }
  }

  def orderedLeftIntervalJoinDistinct(
    ctx: ExecuteContext,
    right: KeyedRVD,
    joiner: PStruct => (RVDType, (RVDContext, Iterator[JoinedRegionValue]) => Iterator[RegionValue])
  ): RVD = {
    checkLeftIntervalJoinCompatability(right)

    val lTyp = virtType
    val rTyp = right.virtType

    rvd.intervalAlignAndZipPartitions(ctx, right.rvd) {
      t: PStruct => {
        val (newTyp, f) = joiner(t)

        (newTyp, (ctx: RVDContext, it: Iterator[RegionValue], intervals: Iterator[RegionValue]) =>
          f(
            ctx,
            OrderedRVIterator(lTyp, it, ctx)
              .leftIntervalJoinDistinct(OrderedRVIterator(rTyp, intervals, ctx))))
      }
    }
  }

  def orderedLeftJoinDistinct(
    right: KeyedRVD,
    joiner: (RVDContext, Iterator[JoinedRegionValue]) => Iterator[RegionValue],
    joinedType: RVDType
  ): RVD = {
    checkJoinCompatability(right)
    val lTyp = virtType
    val rTyp = right.virtType

    rvd.alignAndZipPartitions(
      joinedType,
      right.rvd,
      key
    ) { (ctx, leftIt, rightIt) =>
      joiner(
        ctx,
        OrderedRVIterator(lTyp, leftIt, ctx).leftJoinDistinct(OrderedRVIterator(rTyp, rightIt, ctx)))
    }
  }

  def orderedMerge(
    right: KeyedRVD,
    ctx: ExecuteContext
  ): RVD = {
    checkJoinCompatability(right)
    require(this.realType.rowType == right.realType.rowType)

    if (key == 0)
      return RVD.unkeyed(
        this.realType.rowType,
        ContextRDD.union(
          rvd.sparkContext,
          Seq(this.rvd.crdd, right.rvd.crdd)))

    val ranges = this.rvd.partitioner.coarsenedRangeBounds(key) ++
      right.rvd.partitioner.coarsenedRangeBounds(key)
    val newPartitioner = RVDPartitioner.generate(virtType.key, kType, ranges)

    val repartitionedLeft = this.rvd.repartition(ctx, newPartitioner)
    val lType = this.virtType
    val rType = right.virtType

    repartitionedLeft.alignAndZipPartitions(
      this.virtType,
      right.rvd,
      key
    ) { (ctx, leftIt, rightIt) =>
      OrderedRVIterator(lType, leftIt, ctx)
        .merge(OrderedRVIterator(rType, rightIt, ctx))
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimaryDark">#0080ff</color>
    <color name="colorPrimary">#0080ff</color>
    <color name="colorAccent">#ff9fbf</color>
    <color name="colorAccent2">#333333</color>
</resources>


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateServersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('servers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('dns');
            $table->integer('port')->unsigned();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
         Schema::dropIfExists('servers');
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ChooserActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:paddingTop="30dp"
        android:src="@drawable/aspose_words_android_logo" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:paddingTop="40dp"
        android:text="@string/app_name"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/msg_choose_source" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:paddingTop="30dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:contentDescription="@string/choose_from_storage"
            android:onClick="chooseFromStorage"
            android:padding="5dp"
            android:src="@drawable/choose_from_storage"
            android:text="@string/choose_from_storage" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:contentDescription="@string/choose_from_dropbox"
            android:onClick="chooseFromDropbox"
            android:padding="5dp"
            android:src="@drawable/choose_from_dropbox" />

    </LinearLayout>

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Albatross.Expression.Tokens;
using System.Xml;

namespace Albatross.Expression.Operations {
	[ParserOperation]
	public class Negative : PrefixOperationToken {

		public override string Name { get { return "-"; } }
		public override int MinOperandCount { get { return 1; } }
		public override int MaxOperandCount { get { return 1; } }
		public override bool Symbolic { get { return true; } }

		public override object EvalValue(Func<string, object> context) {
			object a = GetOperands(context).First();

			if (a is double){
				return (double)a * -1;
			}
			throw new FormatException();
		}
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Xunit.Abstractions;
using Xunit.Sdk;

namespace Roslyn.Test.Utilities
{
    public class WpfTheoryTestCaseRunner : XunitTheoryTestCaseRunner
    {
        public WpfTestSharedData SharedData { get; }

        public WpfTheoryTestCaseRunner(
            WpfTestSharedData sharedData,
            IXunitTestCase testCase,
            string displayName,
            string skipReason,
            object[] constructorArguments,
            IMessageSink diagnosticMessageSink,
            IMessageBus messageBus,
            ExceptionAggregator aggregator,
            CancellationTokenSource cancellationTokenSource)
        : base(testCase, displayName, skipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource)
        {
            SharedData = sharedData;
        }

        protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource)
        {
            var runner = new WpfTestRunner(SharedData, test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource);
            return runner;
        }
    }
}


text:
using Autofac;
using Jabberwocky.Glass.Autofac.Extensions;
using Jabberwocky.Glass.Factory;
using Jabberwocky.Glass.Factory.Configuration;
using NSubstitute;
using NUnit.Framework;

namespace Jabberwocky.Glass.Autofac.Tests.Extensions
{
	[TestFixture]
	public class FactoryRegistrationExtensionsTests
	{
		private ContainerBuilder _builder;

		[SetUp]
		public void TestSetup()
		{
			_builder = new ContainerBuilder();
		}

		[Test]
		public void RegisterGlassFactory_NoAssemblies_ReturnsFactory()
		{
			_builder.RegisterGlassFactory();
			var container = _builder.Build();
			container.RegisterContainer();

			var factory = container.Resolve<IGlassInterfaceFactory>();
			Assert.IsNotNull(factory);
		}

		[Test]
		public void RegisterGlassFactory_OptionsWithNoAssemblies_ReturnsFactory()
		{
			_builder.RegisterGlassFactory(new ConfigurationOptions());
			var container = _builder.Build();
			container.RegisterContainer();

			var factory = container.Resolve<IGlassInterfaceFactory>();
			Assert.IsNotNull(factory);
		}

		[Test]
		public void RegisterGlassFactory_WithDebuggingAndNoAssemblies_ReturnsFactory()
		{
			_builder.RegisterGlassFactory(new ConfigurationOptions(true));
			var container = _builder.Build();
			container.RegisterContainer();

			var factory = container.Resolve<IGlassInterfaceFactory>();
			Assert.IsNotNull(factory);
		}

	}
}


text:
/**
 * @class CDATASection
 *      CDATA sections are used to escape blocks of text containing
 *      characters that would otherwise be regarded as markup.
 *      The only delimiter that is recognized in a CDATA section is
 *      the "\]\]\>" string that ends the CDATA section
 * @extends Text
 * @param  ownerDocument : The Document object associated with this node.
 */
CDATASection = function(ownerDocument) {
    Text.apply(this, arguments);
    this.nodeName = '#cdata-section';
};
CDATASection.prototype = new Text();
__extend__(CDATASection.prototype,{
    get nodeType(){
        return Node.CDATA_SECTION_NODE;
    },
    get xml(){
        return "<![CDATA[" + this.nodeValue + "]]>";
    },
    toString : function(){
        return "[object CDATASection]";
    }
});


text:
This repository contains a simple generic Service Response using .NET Standard.

## NuGet

[Link to the NuGet package](https://www.nuget.org/packages/Spherus.ServiceResponse)

**Package Manager: PM>** Install-Package Spherus.ServiceResponse -Version 1.0.7 <br />
**.NET CLI: >** dotnet add package Spherus.ServiceResponse --version 1.0.7

### How to use:

```csharp

//Generic use
ServiceResponse<string> HelloWorld()
{
	ServiceResponse<string> result = new ServiceResponse<string>();

	try
	{
		result.ObjectResult = "Hello World";
		result.Status.Code = 0;
		result.Status.Message = "Success";
	}
	catch (System.Exception ex)
	{
		result.ObjectResult = null;
		result.Status.Code = 1;
		result.Status.Message = ex.Message;
	}

	return result;
}

//Nongeneric use
ServiceResponse HelloWorld()
{
	ServiceResponse result = new ServiceResponse();

	try
	{
		result.Status.Code = 0;
		result.Status.Message = "Success";
	}
	catch (System.Exception ex)
	{
		result.Status.Code = 1;
		result.Status.Message = ex.Message;
	}

	return result;
}

```


text:
<?php

Route::get('/meta', ['as' => 'api.v1.meta', 'uses' => 'MetaController@meta']);
Route::get('/catalog', ['as' => 'api.v1.catalog', 'uses' => 'MetaController@catalog']);
Route::post('/verify', ['as' => 'api.v1.verify', 'uses' => 'MetaController@verify', 'middleware' => 'authdata:present']);

Route::group(['middleware' => 'authdata:valid'], function () {
    Route::resource('/keys', 'KeyController', ['only' => ['store', 'show', 'destroy']]);
    Route::patch('/servers/{servers}/reboot', ['as' => 'api.v1.servers.reboot', 'uses' => 'ServerController@reboot']);
    Route::patch('/servers/{servers}/rename', ['as' => 'api.v1.servers.rename', 'uses' => 'ServerController@rename']);
    Route::resource('/servers', 'ServerController', ['only' => ['store', 'show', 'destroy']]);
});


text:
Currently Dashboard implements [metrics-server](https://github.com/kubernetes-sigs/metrics-server) and [Heapster](https://github.com/kubernetes/heapster) integrations. They are using [integration framework](../../src/app/backend/integration/manager.go) that allows to support and integrate more metric providers as well as additional applications such as [Weave Scope](https://github.com/weaveworks/scope) or [Grafana](https://github.com/grafana/grafana).

## Metric integrations

Metric integrations allow Dashboard to show cpu/memory usage graphs and sparklines of resources running inside the cluster. In order to make Dashboard resilient to metric provider crashes there was `--metric-client-check-period` flag introduced. By default every 30 seconds health of the metric provider will be checked and in case it crashes metrics will be disabled.

### metrics-server

For the sparklines and graphs to be shown in Dashboard you need to have [metrics-server](https://github.com/kubernetes-sigs/metrics-server) running in your cluster. It now uses [dashboard-metrics-scraper](https://github.com/kubernetes-sigs/dashboard-metrics-scraper) that is deployed by default with Kubernetes Dashboard. It uses the Metrics API to gather metrics.
The easiest way to check if `metrics-server` is installed and working properly is to run `kubectl top pod` or `kubectl top node`.

### Heapster

Starting from Kubernetes Dashboard v2.0.0 Heapster is no longer maintained. Use [metrics-server](#metrics-server) integration to enable metrics.

----
_Copyright 2019 [The Kubernetes Dashboard Authors](https://github.com/kubernetes/dashboard/graphs/contributors)_


text:
'use strict';

angular.module('ng-webpack').service('testService', function() {

    this.sayHello = function () {
        console.info("Hello, world!");
    };

});


text:
<?php

declare(strict_types=1);

namespace Vonage\SMS\Message;

class Vcard extends OutboundMessage
{
    /**
     * @var string
     */
    protected $card;

    /**
     * @var string
     */
    protected $type = 'vcard';

    public function __construct(string $to, string $from, string $card)
    {
        parent::__construct($to, $from);

        $this->card = $card;
    }

    /**
     * @return mixed
     */
    public function toArray(): array
    {
        $data = ['vcard' => $this->getCard()];
        $data = $this->appendUniversalOptions($data);

        return $data;
    }

    public function getCard(): string
    {
        return $this->card;
    }
}


text:
<!DOCTYPE html>

     <title>Shriyan's Blog</title>
     <link rel="stylesheet" type="text/css" href="../stylesheets/default.css" >
     <link rel="stylesheet" type="text/css" href="../stylesheets/newblogtemp.css" >

            Shriyan C. Gunasekera

             Blog

Blog Entries

Git, Guthub Explained!

 Chef's Kitchen

HTML/CSS Classes vs. ID's

 Ruby Arrays & Hashes

 Thinking Style: DBC Struggles

 The Gender Gap

 Enumerable Methods: Map

 Pair Programming

 Ruby Classes

 Stereotype Threat

 Ruby Variables

 My Values

 JavaScript vs. Ruby: Methods

 Breaking Down Conflicts

 What the Heck is Rails?

 Asking Good Questions

 Updating My Site

 Other Posts

 GPS - Week 3

 Git Cheat Sheet

 15 February 2015

HTML/CSS Classes vs. ID's

              Hi there! Hope you're well. It's been an incredibly busy week for me, as this week we were tasked with learning both HTML and CSS in order to build our own personal websites! Fortunately, I managed to get it all done, and as a result, you're now able to read this very blog post in a brand new, constantly-improving website!

              As I was learning HTML/CSS one feature I found especially interesting was the ability to use "ID's" and "classes" to style HTML elements. When used properly, classes and ID's allow you to streamline the styling process, by targeting specific elements (including paragraphs, headers, div's, tables, etc.).

              So what's the difference between the two? Well, a "class" should be used when you have several different elements that you want to give a particular styling and only those elements. For instance, if you wanted several "important" paragraphs in different sections of a large body of text to have a different font color, you could accomplish that using classes.

              In HTML, you could start each paragraph with a (p class="important") tag.

              Then in CSS, you could apply a font color of red to those important paragraphs, like so:  .important{ color:red; }

              And just like that, those important paragraphs would have red text, while all the other paragraphs would remain their original color! Using classes is like checking an imaginary box next to each element saying that you want them to get the same styling.

              ID's on the other hand are unique. Just like your own ID, they can only be used by one element. If you wanted just one paragraph to have red font, but you wanted all the other paragraphs to remain the same color, you could target that paragraph using an ID.

              Here's what that would look like:

              In HTML, (p id="redparagraph")

              And then in CSS: #redparagraph { color:red; }

              Note: in CSS, classes are identified using a "." and ID's are identified using a "#"
              As always it's best to try these out for yourself! Below you can find an example of the classes and ID's I used to make the homepage of this very site!

- S.G.

              Prev

              Next


text:
package com.amazonaws.services.wafv2.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The collection of tagging definitions for an Amazon Web Services resource. Tags are key:value pairs that you can use
 * to categorize and manage your resources, for purposes like billing or other management. Typically, the tag key
 * represents a category, such as "environment", and the tag value represents a specific value within that category,
 * such as "test," "development," or "production". Or you might set the tag key to "customer" and the value to the
 * customer name or ID. You can specify one or more tags to add to each Amazon Web Services resource, up to 50 tags for
 * a resource.
 *

 *

 * You can tag the Amazon Web Services resources that you manage through WAF: web ACLs, rule groups, IP sets, and regex
 * pattern sets. You can't manage or view tags through the WAF console.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TagInfoForResource implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The Amazon Resource Name (ARN) of the resource.
     *

     */
    private String resourceARN;
    /**
     *

     * The array of Tag objects defined for the resource.
     *

     */
    private java.util.List<Tag> tagList;

    /**
     *

     * The Amazon Resource Name (ARN) of the resource.
     *

     *
     * @param resourceARN
     *        The Amazon Resource Name (ARN) of the resource.
     */

    public void setResourceARN(String resourceARN) {
        this.resourceARN = resourceARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the resource.
     *

     *
     * @return The Amazon Resource Name (ARN) of the resource.
     */

    public String getResourceARN() {
        return this.resourceARN;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the resource.
     *

     *
     * @param resourceARN
     *        The Amazon Resource Name (ARN) of the resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagInfoForResource withResourceARN(String resourceARN) {
        setResourceARN(resourceARN);
        return this;
    }

    /**
     *

     * The array of Tag objects defined for the resource.
     *

     *
     * @return The array of Tag objects defined for the resource.
     */

    public java.util.List<Tag> getTagList() {
        return tagList;
    }

    /**
     *

     * The array of Tag objects defined for the resource.
     *

     *
     * @param tagList
     *        The array of Tag objects defined for the resource.
     */

    public void setTagList(java.util.Collection<Tag> tagList) {
        if (tagList == null) {
            this.tagList = null;
            return;
        }

        this.tagList = new java.util.ArrayList<Tag>(tagList);
    }

    /**
     *

     * The array of Tag objects defined for the resource.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setTagList(java.util.Collection)} or {@link #withTagList(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param tagList
     *        The array of Tag objects defined for the resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagInfoForResource withTagList(Tag... tagList) {
        if (this.tagList == null) {
            setTagList(new java.util.ArrayList<Tag>(tagList.length));
        }
        for (Tag ele : tagList) {
            this.tagList.add(ele);
        }
        return this;
    }

    /**
     *

     * The array of Tag objects defined for the resource.
     *

     *
     * @param tagList
     *        The array of Tag objects defined for the resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public TagInfoForResource withTagList(java.util.Collection<Tag> tagList) {
        setTagList(tagList);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getResourceARN() != null)
            sb.append("ResourceARN: ").append(getResourceARN()).append(",");
        if (getTagList() != null)
            sb.append("TagList: ").append(getTagList());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof TagInfoForResource == false)
            return false;
        TagInfoForResource other = (TagInfoForResource) obj;
        if (other.getResourceARN() == null ^ this.getResourceARN() == null)
            return false;
        if (other.getResourceARN() != null && other.getResourceARN().equals(this.getResourceARN()) == false)
            return false;
        if (other.getTagList() == null ^ this.getTagList() == null)
            return false;
        if (other.getTagList() != null && other.getTagList().equals(this.getTagList()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getResourceARN() == null) ? 0 : getResourceARN().hashCode());
        hashCode = prime * hashCode + ((getTagList() == null) ? 0 : getTagList().hashCode());
        return hashCode;
    }

    @Override
    public TagInfoForResource clone() {
        try {
            return (TagInfoForResource) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.wafv2.model.transform.TagInfoForResourceMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
<?php

namespace DgwebBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DgwebBundle extends Bundle
{
}