text:
 # Copyright 2004 Apache Software Foundation
 #
 # Licensed 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.
 #
 # Originally developed by Gregory Trubetskoy.
 #
 # This was donated by Nicolas Lehuen, and also posted to the Python Cookbook
 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302997
 #
 # $Id$

from os import stat
from time import time, mktime
from rfc822 import parsedate
from calendar import timegm
import urllib2
import re
import weakref
import new

try:
    from threading import Lock
except ImportError:
    from dummy_threading import Lock

NOT_INITIALIZED = object()

class Entry(object):
    """ A cache entry, mostly an internal object. """
    def __init__(self, key):
        object.__init__(self)
        self._key=key
        self._value=NOT_INITIALIZED
        self._lock=Lock()

class Cache(object):
    """ An abstract, multi-threaded cache object. """

    def __init__(self, max_size=0):
        """ Builds a cache with a limit of max_size entries.
            If this limit is exceeded, the Least Recently Used entry is discarded.
            if max_size==0, the cache is unbounded (no LRU rule is applied).
        """
        object.__init__(self)
        self._maxsize=max_size
        self._dict={}
        self._lock=Lock()

        # Header of the access list
        if self._maxsize:
            self._head=Entry(None)
            self._head._previous=self._head
            self._head._next=self._head

    def __setitem__(self, name, value):
        """ Populates the cache with a given name and value. """
        key = self.key(name)

        entry = self._get_entry(key)

        entry._lock.acquire()
        try:
            self._pack(entry,value)
            self.commit()
        finally:
            entry._lock.release()

    def __getitem__(self, name):
        """ Gets a value from the cache, builds it if required.
        """
        return self._checkitem(name)[2]

    def __delitem__(self, name):
        self._lock.acquire()
        try:
            key = self.key(name)
            del self._dict[key]
        finally:
            self._lock.release()

    def _get_entry(self,key):
        self._lock.acquire()
        try:
            entry = self._dict.get(key)
            if not entry:
                entry = Entry(key)
                self._dict[key]=entry
                if self._maxsize:
                    entry._next = entry._previous = None
                    self._access(entry)
                    self._checklru()
            elif self._maxsize:
                self._access(entry)
            return entry
        finally:
            self._lock.release()

    def _checkitem(self, name):
        """ Gets a value from the cache, builds it if required.
            Returns a tuple is_new, key, value, entry.
            If is_new is True, the result had to be rebuilt.
        """
        key = self.key(name)

        entry = self._get_entry(key)

        entry._lock.acquire()
        try:
            value = self._unpack(entry)
            is_new = False
            if value is NOT_INITIALIZED:
                opened = self.check(key, name, entry)
                value = self.build(key, name, opened, entry)
                is_new = True
                self._pack(entry, value)
                self.commit()
            else:
                opened = self.check(key, name, entry)
                if opened is not None:
                    value = self.build(key, name, opened, entry)
                    is_new = True
                    self._pack(entry, value)
                    self.commit()
            return is_new, key, value, entry
        finally:
            entry._lock.release()

    def mru(self):
        """ Returns the Most Recently Used key """
        if self._maxsize:
            self._lock.acquire()
            try:
                return self._head._previous._key
            finally:
                self._lock.release()
        else:
            return None

    def lru(self):
        """ Returns the Least Recently Used key """
        if self._maxsize:
            self._lock.acquire()
            try:
                return self._head._next._key
            finally:
                self._lock.release()
        else:
            return None

    def key(self, name):
        """ Override this method to extract a key from the name passed to the [] operator """
        return name

    def commit(self):
        """ Override this method if you want to do something each time the underlying dictionary is modified (e.g. make it persistent). """
        pass

    def clear(self):
        """ Clears the cache """
        self._lock.acquire()
        try:
            self._dict.clear()
            if self._maxsize:
                self._head._next=self._head
                self._head._previous=self._head
        finally:
            self._lock.release()

    def check(self, key, name, entry):
        """ Override this method to check whether the entry with the given name is stale. Return None if it is fresh
            or an opened resource if it is stale. The object returned will be passed to the 'build' method as the 'opened' parameter.
            Use the 'entry' parameter to store meta-data if required. Don't worry about multiple threads accessing the same name,
            as this method is properly isolated.
        """
        return None

    def build(self, key, name, opened, entry):
        """ Build the cached value with the given name from the given opened resource. Use entry to obtain or store meta-data if needed.
             Don't worry about multiple threads accessing the same name, as this method is properly isolated.
        """
        raise NotImplementedError()

    def _access(self, entry):
        " Internal use only, must be invoked within a cache lock. Updates the access list. """
        if entry._next is not self._head:
            if entry._previous is not None:
                # remove the entry from the access list
                entry._previous._next=entry._next
                entry._next._previous=entry._previous
            # insert the entry at the end of the access list
            entry._previous=self._head._previous
            entry._previous._next=entry
            entry._next=self._head
            entry._next._previous=entry
            if self._head._next is self._head:
                self._head._next=entry

    def _checklru(self):
        " Internal use only, must be invoked within a cache lock. Removes the LRU entry if needed. """
        if len(self._dict)>self._maxsize:
            lru=self._head._next
            lru._previous._next=lru._next
            lru._next._previous=lru._previous
            del self._dict[lru._key]

    def _pack(self, entry, value):
        """ Store the value in the entry. """
        entry._value=value

    def _unpack(self, entry):
        """ Recover the value from the entry, returns NOT_INITIALIZED if it is not OK. """
        return entry._value

class WeakCache(Cache):
    """ This cache holds weak references to the values it stores. Whenever a value is not longer
        normally referenced, it is removed from the cache. Useful for sharing the result of long
        computations but letting them go as soon as they are not needed by anybody.
    """

    def _pack(self, entry, value):
        entry._value=weakref.ref(value, lambda ref: self.__delitem__(entry._key))

    def _unpack(self, entry):
        if entry._value is NOT_INITIALIZED:
            return NOT_INITIALIZED

        value = entry._value()
        if value is None:
            return NOT_INITIALIZED
        else:
            return value

class FileCache(Cache):
    """ A file cache. Returns the content of the files as a string, given their filename.
        Whenever the files are modified (according to their modification time) the cache is updated.
        Override the build method to obtain more interesting behaviour.
    """
    def __init__(self, max_size=0, mode='rb'):
        Cache.__init__(self, max_size)
        self.mode=mode

    def check(self, key, name, entry):
        timestamp = stat(key).st_mtime

        if entry._value is NOT_INITIALIZED:
            entry._timestamp = timestamp
            return file(key, self.mode)
        else:
            if entry._timestamp != timestamp:
                entry._timestamp = timestamp
                return file(key, self.mode)
            else:
                return None

    def build(self, key, name, opened, entry):
        """ Return the content of the file as a string. Override this for better behaviour. """
        try:
            return opened.read()
        finally:
            opened.close()

def parseRFC822Time(t):
    return mktime(parsedate(t))

re_max_age=re.compile('max-age\s*=\s*(\d+)', re.I)

class HTTPEntity(object):
    def __init__(self, entity, metadata):
        self.entity=entity
        self.metadata=metadata

    def __repr__(self):
        return 'HTTPEntity(%s, %s)'%(repr(self.entity), self.metadata)

    def __str__(self):
        return self.entity

class HTTPCache(Cache):
    """ An HTTP cache. Returns the entity found at the given URL.
        Uses Expires, ETag and Last-Modified headers to minimize bandwidth usage.
        Partial Cache-Control support (only max-age is supported).
    """
    def check(self, key, name, entry):
        request = urllib2.Request(key)

        try:
            if time()<entry._expires:
                return None
        except AttributeError:
            pass
        try:
            header, value = entry._validator
            request.headers[header]=value
        except AttributeError:
            pass
        opened = None
        try:
            opened = urllib2.urlopen(request)
            headers = opened.info()

            # expiration handling
            expiration = False
            try:
                match = re_max_age.match(headers['cache-control'])
                if match:
                    entry._expires=time()+int(match.group(1))
                    expiration = True
            except (KeyError, ValueError):
                pass
            if not expiration:
                try:
                    date = parseRFC822Time(headers['date'])
                    expires = parseRFC822Time(headers['expires'])
                    entry._expires = time()+(expires-date)
                    expiration = True
                except KeyError:
                    pass

            # validator handling
            validation = False
            try:
                entry._validator='If-None-Match', headers['etag']
                validation = True
            except KeyError:
                pass
            if not validation:
                try:
                    entry._validator='If-Modified-Since', headers['last-modified']
                except KeyError:
                    pass

            return opened
        except urllib2.HTTPError, error:
            if opened: opened.close()
            if error.code==304:
                return None
            else:
                raise error

    def build(self, key, name, opened, entry):
        try:
            return HTTPEntity(opened.read(), dict(opened.info()))
        finally:
            opened.close()

re_not_word = re.compile(r'\W+')

class ModuleCache(FileCache):
    """ A module cache. Give it a file name, it returns a module
        which results from the execution of the Python script it contains.
        This module is not inserted into sys.modules.
    """
    def __init__(self, max_size=0):
        FileCache.__init__(self, max_size, 'r')

    def build(self, key, name, opened, entry):
        try:
            module = new.module(re_not_word.sub('_',key))
            module.__file__ = key
            exec opened in module.__dict__
            return module
        finally:
            opened.close()

class HttpModuleCache(HTTPCache):
    """ A module cache. Give it an HTTP URL, it returns a module
        which results from the execution of the Python script it contains.
        This module is not inserted into sys.modules.
    """
    def __init__(self, max_size=0):
        HTTPCache.__init__(self, max_size)

    def build(self, key, name, opened, entry):
        try:
            module = new.module(re_not_word.sub('_',key))
            module.__file__ = key
            text = opened.read().replace('\r\n', '\n')
            code = compile(text, name, 'exec')
            exec code in module.__dict__
            return module
        finally:
            opened.close()

class FunctionCache(Cache):
    def __init__(self, function, max_size=0):
        Cache.__init__(self, max_size)
        self.function=function

    def __call__(self, *args, **kw):
        if kw:
            # a dict is not hashable so we build a tuple of (key, value) pairs
            kw = tuple(kw.iteritems())
            return self[args, kw]
        else:
            return self[args, ()]

    def build(self, key, name, opened, entry):
        args, kw = key
        return self.function(*args, **dict(kw))


text:
// AppLog - Application logger class

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "applog.h"

// Constructor
AppLog::AppLog()
{
	_filename = APPLOG_DEFAULT_FILE;
	_trace = false;
}

// Log message to console and log file
void AppLog::Log(const char *format, ...)
{
	va_list args;
	va_start(args, format);

	// log message to console
	vprintf(format, args);

	// QT tools seem to get delayed output
	fflush(stdout);

        va_end(args);
        va_start(args, format);

	// log message to file
	LogFileVaList(format, args);

	va_end(args);
}

// Log messages to file if trace mode is set
void AppLog::Trace(const char *format, ...)
{
	if(_trace == false)
		return;

	va_list args;
	va_start(args, format);

	// log message into the file
	LogFileVaList(format, args);

	va_end(args);
}

// Write to console only
void AppLog::LogConsole(const char *format, ...)
{
	va_list args;
	va_start(args, format);

	// log message to console
	vprintf(format, args);

	fflush(stdout);

	va_end(args);
}

// Write to log file only
void AppLog::LogFile(const char *format, ...)
{
	va_list args;
	va_start(args, format);

	// log message into the file
	LogFileVaList(format, args);

	va_end(args);
}

// Write to log file
void AppLog::LogFileVaList(const char *format, va_list args)
{
	static bool firstCall = true;
	const char *openMode = "a";

	// During the first call destroy the log file content that may exists from the previous runs
	if(firstCall)
		openMode = "w";

	FILE *file = fopen(_filename.c_str(), openMode);

	// Log message to file
	if(file != NULL)
	{
		vfprintf(file, format, args);
		fclose(file);
	}
	else
	{
		// Show error message during the first call only
		if(firstCall)
			printf("\n\nError:\n Opening log file %s - %s", _filename.c_str(), strerror(errno));
	}

	firstCall = false;
}

redpajama_set_name: RedPajamaGithub


text:
package com.lict.feedback.dao;

import com.lict.feedback.entity.AdmUser;
import java.util.List;

public interface UserDao {

    AdmUser findById(int id);

    AdmUser findBySSO(String sso);

    AdmUser save(AdmUser user);

    void deleteBySSO(String sso);

    List<AdmUser> findAllUsers();

}


text:
// Package connrotation implements a connection dialer that tracks and can close
// all created connections.
//
// This is used for credential rotation of long-lived connections, when there's
// no way to re-authenticate on a live connection.
package connrotation

import (
	"context"
	"net"
	"sync"
)

// DialFunc is a shorthand for signature of net.DialContext.
type DialFunc func(ctx context.Context, network, address string) (net.Conn, error)

// Dialer opens connections through Dial and tracks them.
type Dialer struct {
	dial DialFunc
	*ConnectionTracker
}

// NewDialer creates a new Dialer instance.
// Equivalent to NewDialerWithTracker(dial, nil).
func NewDialer(dial DialFunc) *Dialer {
	return NewDialerWithTracker(dial, nil)
}

// NewDialerWithTracker creates a new Dialer instance.
//
// If dial is not nil, it will be used to create new underlying connections.
// Otherwise net.DialContext is used.
// If tracker is not nil, it will be used to track new underlying connections.
// Otherwise NewConnectionTracker() is used.
func NewDialerWithTracker(dial DialFunc, tracker *ConnectionTracker) *Dialer {
	if tracker == nil {
		tracker = NewConnectionTracker()
	}
	return &Dialer{
		dial:              dial,
		ConnectionTracker: tracker,
	}
}

// ConnectionTracker keeps track of opened connections
type ConnectionTracker struct {
	mu    sync.Mutex
	conns map[*closableConn]struct{}
}

// NewConnectionTracker returns a connection tracker for use with NewDialerWithTracker
func NewConnectionTracker() *ConnectionTracker {
	return &ConnectionTracker{
		conns: make(map[*closableConn]struct{}),
	}
}

// CloseAll forcibly closes all tracked connections.
//
// Note: new connections may get created before CloseAll returns.
func (c *ConnectionTracker) CloseAll() {
	c.mu.Lock()
	conns := c.conns
	c.conns = make(map[*closableConn]struct{})
	c.mu.Unlock()

	for conn := range conns {
		conn.Close()
	}
}

// Track adds the connection to the list of tracked connections,
// and returns a wrapped copy of the connection that stops tracking the connection
// when it is closed.
func (c *ConnectionTracker) Track(conn net.Conn) net.Conn {
	closable := &closableConn{Conn: conn}

	// When the connection is closed, remove it from the map. This will
	// be no-op if the connection isn't in the map, e.g. if CloseAll()
	// is called.
	closable.onClose = func() {
		c.mu.Lock()
		delete(c.conns, closable)
		c.mu.Unlock()
	}

	// Start tracking the connection
	c.mu.Lock()
	c.conns[closable] = struct{}{}
	c.mu.Unlock()

	return closable
}

// Dial creates a new tracked connection.
func (d *Dialer) Dial(network, address string) (net.Conn, error) {
	return d.DialContext(context.Background(), network, address)
}

// DialContext creates a new tracked connection.
func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
	conn, err := d.dial(ctx, network, address)
	if err != nil {
		return nil, err
	}
	return d.ConnectionTracker.Track(conn), nil
}

type closableConn struct {
	onClose func()
	net.Conn
}

func (c *closableConn) Close() error {
	go c.onClose()
	return c.Conn.Close()
}


text:
package org.apache.helix.monitoring;

import org.testng.AssertJUnit;
import org.testng.annotations.Test;

public class TestStatCollector {
  @Test(groups = {
    "unitTest"
  })
  public void TestCollectData() {
    StatCollector collector = new StatCollector();

    int nPoints = 100;
    for (int i = 0; i < nPoints; i++) {
      collector.addData(i * 1000);
    }
    AssertJUnit.assertEquals(collector.getNumDataPoints(), nPoints);
    AssertJUnit.assertEquals((long) collector.getMax(), 99000);
    AssertJUnit.assertEquals((long) collector.getTotalSum(), 4950000);
    AssertJUnit.assertEquals((long) collector.getPercentile(40), 39400);
    AssertJUnit.assertEquals((long) collector.getMean(), 49500);
    AssertJUnit.assertEquals((long) collector.getMin(), 0);

    collector.reset();

    AssertJUnit.assertEquals(collector.getNumDataPoints(), 0);
    AssertJUnit.assertEquals((long) collector.getMax(), 0);
    AssertJUnit.assertEquals((long) collector.getTotalSum(), 0);
    AssertJUnit.assertEquals((long) collector.getPercentile(40), 0);
    AssertJUnit.assertEquals((long) collector.getMean(), 0);
    AssertJUnit.assertEquals((long) collector.getMin(), 0);

  }
}


text:
 A simple authoring tool to keep track of changes to a model.

## Usage
Install the migration adding the 'Edits' table to your database:
```ruby
    rake whodunnit:install:migrations
```
Then start to keep track of changes:
```ruby
create_edit_entry(item, action = :unknown, custom = nil, by = nil)
```
Where action can be one of the following: `a_unkown`, `a_show`, `a_create`, `a_update`, or `a_destroy`
The gem assumes you have a current_user method which contains the logged in user (a la Devise), this can be overridden by passing the `by` option.

I.e. when an update to an article `@article` has been made:
```ruby
create_edit_entry @article, :a_update
```
Or when you need to save additional data, for say, legal reasons:
```ruby
create_edit_entry @document, :a_update, @document.to_s
```

After creating entries, you can obtain them by a number of helper methods:

- `created_by <object>`, returns the user which initally created the object.
- `last_edit_by <object>`, returns the user which made the last Edit entry on the object.
- `last_edit_at <object>`, returns the timestamp the last Edit entry was created.
- `total_edits_on <object>`, returns the amount of Edit entries on an object.

If the results are empty it will return the translation for `not_found` (`t('not_found')'`)

##Pull requests
Are always welcome :)


text:
package org.hisp.dhis.system.util;

import com.google.common.collect.ImmutableMap;
import org.hisp.dhis.calendar.DateTimeUnit;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Lars Helge Overland
 */
public class DateUtils
{
    private static DateTimeFormatter ISO8601 = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" );

    private static DateTimeFormatter ISO8601_NO_TZ = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSS" );

    private static final DateTimeParser[] SUPPORTED_DATE_FORMAT_PARSERS = {
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSS" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mmZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HHZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ssZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM" ).getParser(),
        DateTimeFormat.forPattern( "yyyy" ).getParser()
    };

    private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
        .append( null, SUPPORTED_DATE_FORMAT_PARSERS ).toFormatter();

    private static final DateTimeParser[] SUPPORTED_DATE_TIME_FORMAT_PARSERS = {
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mmZ" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm" ).getParser()
    };

    private static final DateTimeFormatter DATE_TIME_FORMAT = (new DateTimeFormatterBuilder())
        .append( null, SUPPORTED_DATE_TIME_FORMAT_PARSERS ).toFormatter();

    public static final PeriodFormatter DAY_SECOND_FORMAT = new PeriodFormatterBuilder()
        .appendDays().appendSuffix( " d" ).appendSeparator( ", " )
        .appendHours().appendSuffix( " h" ).appendSeparator( ", " )
        .appendMinutes().appendSuffix( " m" ).appendSeparator( ", " )
        .appendSeconds().appendSuffix( " s" ).appendSeparator( ", " ).toFormatter();

    private static final DateTimeFormatter MEDIUM_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd" );
    private static final DateTimeFormatter LONG_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" );
    private static final DateTimeFormatter HTTP_DATE_FORMAT = DateTimeFormat.forPattern( "EEE, dd MMM yyyy HH:mm:ss 'GMT'" ).withLocale( Locale.ENGLISH );
    private static final DateTimeFormatter TIMESTAMP_UTC_TZ_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).withZoneUTC();

    private static final double DAYS_IN_YEAR = 365.0;
    private static final long MS_PER_DAY = 86400000;
    private static final long MS_PER_S = 1000;

    private static final Pattern DURATION_PATTERN = Pattern.compile( "^(\\d+)(d|h|m|s)$" );

    private static final Map<String, ChronoUnit> TEMPORAL_MAP = ImmutableMap.of(
        "d", ChronoUnit.DAYS, "h", ChronoUnit.HOURS, "m", ChronoUnit.MINUTES, "s", ChronoUnit.SECONDS );

    /**
     * Returns date formatted as ISO 8601
     */
    public static String getIso8601( Date date )
    {
        return date != null ? ISO8601.print( new DateTime( date ) ) : null;
    }

    /**
     * Returns date formatted as ISO 8601, without any TZ info
     */
    public static String getIso8601NoTz( Date date )
    {
        return date != null ? ISO8601_NO_TZ.print( new DateTime( date ) ) : null;
    }

    /**
     * Converts a Date to the GMT timezone and formats it to the format yyyy-MM-dd HH:mm:ssZ.
     *
     * @param date the Date to parse.
     * @return A formatted date string.
     */
    public static String getLongGmtDateString( Date date )
    {
        return date != null ? TIMESTAMP_UTC_TZ_FORMAT.print( new DateTime( date ) ) : null;
    }

    /**
     * Formats a Date to the format yyyy-MM-dd HH:mm:ss.
     *
     * @param date the Date to parse.
     * @return A formatted date string.
     */
    public static String getLongDateString( Date date )
    {
        return date != null ? LONG_DATE_FORMAT.print( new DateTime( date ) ) : null;
    }

    /**
     * Formats a Date to the format yyyy-MM-dd HH:mm:ss.
     *
     * @return A formatted date string.
     */
    public static String getLongDateString()
    {
        return getLongDateString( Calendar.getInstance().getTime() );
    }

    /**
     * Formats a Date to the format yyyy-MM-dd.
     *
     * @param date the Date to parse.
     * @return A formatted date string. Null if argument is null.
     */
    public static String getMediumDateString( Date date )
    {
        return date != null ? MEDIUM_DATE_FORMAT.print( new DateTime( date ) ) : null;
    }

    /**
     * Formats the current Date to the format YYYY-MM-DD.
     *
     * @return A formatted date string.
     */
    public static String getMediumDateString()
    {
        return getMediumDateString( Calendar.getInstance().getTime() );
    }

    /**
     * Formats a Date according to the HTTP specification standard date format.
     *
     * @param date the Date to format.
     * @return a formatted string.
     */
    public static String getHttpDateString( Date date )
    {
        return date != null ? (HTTP_DATE_FORMAT.print( new DateTime( date ) )) : null;
    }

    /**
     * Returns the latest of the two given dates.
     *
     * @param date1 the first date, can be null.
     * @param date2 the second date, can be null.
     * @return the latest of the two given dates.
     */
    public static Date max( Date date1, Date date2 )
    {
        if ( date1 == null )
        {
            return date2;
        }

        return date2 != null ? (date1.after( date2 ) ? date1 : date2) : date1;
    }

    /**
     * Returns the latest of the given dates.
     *
     * @param date the collection of dates.
     * @return the latest of the given dates.
     */
    public static Date max( Collection<Date> dates )
    {
        Date latest = null;

        for ( Date d : dates )
        {
            latest = max( d, latest );
        }

        return latest;
    }

    /**
     * Returns the earliest of the two given dates.
     *
     * @param date1 the first date, can be null.
     * @param date2 the second date, can be null.
     * @return the latest of the two given dates.
     */
    public static Date min( Date date1, Date date2 )
    {
        if ( date1 == null )
        {
            return date2;
        }

        return date2 != null ? (date1.before( date2 ) ? date1 : date2) : date1;
    }

    /**
     * Returns the earliest of the given dates.
     *
     * @param date the collection of dates.
     * @return the earliest of the given dates.
     */
    public static Date min( Collection<Date> dates )
    {
        Date earliest = null;

        for ( Date d : dates )
        {
            earliest = min( d, earliest );
        }

        return earliest;
    }

    /**
     * Parses a date from a String on the format YYYY-MM-DD. Returns null if the
     * given string is null.
     *
     * @param dateString the String to parse.
     * @return a Date based on the given String.
     * @throws IllegalArgumentException if the given string is invalid.
     */
    public static Date getMediumDate( String string )
    {
        return string != null ? MEDIUM_DATE_FORMAT.parseDateTime( string ).toDate() : null;
    }

    /**
     * Tests if the given base date is between the given start date and end
     * date, including the dates themselves.
     *
     * @param baseDate  the date used as base for the test.
     * @param startDate the start date.
     * @param endDate   the end date.
     * @return true if the base date is between the start date
     * and end date, false otherwise.
     */
    public static boolean between( Date baseDate, Date startDate, Date endDate )
    {
        if ( startDate.equals( endDate ) || endDate.before( startDate ) )
        {
            return false;
        }

        if ( (startDate.before( baseDate ) || startDate.equals( baseDate ))
            && (endDate.after( baseDate ) || endDate.equals( baseDate )) )
        {
            return true;
        }

        return false;
    }

    /**
     * Tests if the given base date is strictly between the given start date and
     * end date.
     *
     * @param baseDate  the date used as base for the test.
     * @param startDate the start date.
     * @param endDate   the end date.
     * @return true if the base date is between the start date
     * and end date, false otherwise.
     */
    public static boolean strictlyBetween( Date baseDate, Date startDate, Date endDate )
    {
        if ( startDate.equals( endDate ) || endDate.before( startDate ) )
        {
            return false;
        }

        if ( startDate.before( baseDate ) && endDate.after( baseDate ) )
        {
            return true;
        }

        return false;
    }

    /**
     * Returns the number of days since 01/01/1970. The value is rounded off to
     * the floor value and does not take daylight saving time into account.
     *
     * @param date the date.
     * @return number of days since Epoch.
     */
    public static long getDays( Date date )
    {
        return date.getTime() / MS_PER_DAY;
    }

    /**
     * Returns the number of days between the start date (inclusive) and end
     * date (exclusive). The value is rounded off to the floor value and does
     * not take daylight saving time into account.
     *
     * @param startDate the start-date.
     * @param endDate   the end-date.
     * @return the number of days between the start and end-date.
     */
    public static long getDays( Date startDate, Date endDate )
    {
        return (endDate.getTime() - startDate.getTime()) / MS_PER_DAY;
    }

    /**
     * Returns the number of days between the start date (inclusive) and end
     * date (inclusive). The value is rounded off to the floor value and does
     * not take daylight saving time into account.
     *
     * @param startDate the start-date.
     * @param endDate   the end-date.
     * @return the number of days between the start and end-date.
     */
    public static long getDaysInclusive( Date startDate, Date endDate )
    {
        return getDays( startDate, endDate ) + 1;
    }

    /**
     * Calculates the number of days between the start and end-date. Note this
     * method is taking daylight saving time into account and has a performance
     * overhead.
     *
     * @param startDate the start date.
     * @param endDate   the end date.
     * @return the number of days between the start and end date.
     */
    public static int daysBetween( Date startDate, Date endDate )
    {
        final Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );

        return days.getDays();
    }

    /**
     * Checks if the date provided in argument is today's date.
     *
     * @param date to check
     * @return true if date is representing today's date false otherwise
     */
    public static boolean isToday( Date date )
    {
        int days = Days.daysBetween( new LocalDate( date ), new LocalDate() ).getDays();

        return days == 0;
    }

    /**
     * Calculates the number of months between the start and end-date. Note this
     * method is taking daylight saving time into account and has a performance
     * overhead.
     *
     * @param startDate the start date.
     * @param endDate   the end date.
     * @return the number of months between the start and end date.
     */
    public static int monthsBetween( Date startDate, Date endDate )
    {
        final Months days = Months.monthsBetween( new DateTime( startDate ), new DateTime( endDate ) );

        return days.getMonths();
    }

    /**
     * Calculates the number of days between Epoch and the given date.
     *
     * @param date the date.
     * @return the number of days between Epoch and the given date.
     */
    public static int daysSince1900( Date date )
    {
        final Calendar calendar = Calendar.getInstance();

        calendar.clear();
        calendar.set( 1900, 0, 1 );

        return daysBetween( calendar.getTime(), date );
    }

    /**
     * Returns Epoch date, ie. 01/01/1970.
     *
     * @return Epoch date, ie. 01/01/1970.
     */
    public static Date getEpoch()
    {
        final Calendar calendar = Calendar.getInstance();

        calendar.clear();
        calendar.set( 1970, 0, 1 );

        return calendar.getTime();
    }

    /**
     * Returns a date formatted in ANSI SQL.
     *
     * @param date the Date.
     * @return a date String.
     */
    public static String getSqlDateString( Date date )
    {
        Calendar cal = Calendar.getInstance();

        cal.setTime( date );

        int year = cal.get( Calendar.YEAR );
        int month = cal.get( Calendar.MONTH ) + 1;
        int day = cal.get( Calendar.DAY_OF_MONTH );

        String yearString = String.valueOf( year );
        String monthString = month < 10 ? "0" + month : String.valueOf( month );
        String dayString = day < 10 ? "0" + day : String.valueOf( day );

        return yearString + "-" + monthString + "-" + dayString;
    }

    private static final String DEFAULT_DATE_REGEX = "\\b(?<year>\\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[1-2][0-9]|3[0-2])\\b";

    private static final Pattern DEFAULT_DATE_REGEX_PATTERN = Pattern.compile( DEFAULT_DATE_REGEX );

    /**
     * This method checks whether the String inDate is a valid date following
     * the format "yyyy-MM-dd".
     *
     * @param dateString the string to be checked.
     * @return true/false depending on whether the string is a date according to the format "yyyy-MM-dd".
     */
    public static boolean dateIsValid( String dateString )
    {
        return dateIsValid( PeriodType.getCalendar(), dateString );
    }

    /**
     * This method checks whether the String inDate is a valid date following
     * the format "yyyy-MM-dd".
     *
     * @param calendar   Calendar to be used
     * @param dateString the string to be checked.
     * @return true/false depending on whether the string is a date according to the format "yyyy-MM-dd".
     */
    public static boolean dateIsValid( org.hisp.dhis.calendar.Calendar calendar, String dateString )
    {
        Matcher matcher = DEFAULT_DATE_REGEX_PATTERN.matcher( dateString );

        if ( !matcher.matches() )
        {
            return false;
        }

        DateTimeUnit dateTime = new DateTimeUnit(
            Integer.valueOf( matcher.group( "year" ) ),
            Integer.valueOf( matcher.group( "month" ) ),
            Integer.valueOf( matcher.group( "day" ) )
        );

        return calendar.isValid( dateTime );
    }

    /**
     * This method checks whether the String dateTimeString is a valid datetime following
     * the format "yyyy-MM-dd".
     *
     * @param dateTimeString the string to be checked.
     * @return true/false depending on whether the string is a valid datetime according to the format "yyyy-MM-dd".
     */
    public static boolean dateTimeIsValid( final String dateTimeString )
    {
        try
        {
            DATE_TIME_FORMAT.parseDateTime( dateTimeString );
            return true;
        }
        catch ( IllegalArgumentException ex )
        {
            return false;
        }
    }

    /**
     * Returns the number of seconds until the next day at the given hour.
     *
     * @param hour the hour.
     * @return number of seconds.
     */
    public static long getSecondsUntilTomorrow( int hour )
    {
        Date date = getDateForTomorrow( hour );
        return (date.getTime() - new Date().getTime()) / MS_PER_S;
    }

    /**
     * Returns a date set to tomorrow at the given hour.
     *
     * @param hour the hour.
     * @return a date.
     */
    public static Date getDateForTomorrow( int hour )
    {
        Calendar cal = PeriodType.createCalendarInstance();
        cal.add( Calendar.DAY_OF_YEAR, 1 );
        cal.set( Calendar.HOUR_OF_DAY, hour );
        return cal.getTime();
    }

    /**
     * This method adds days to a date
     *
     * @param date the date.
     * @param days the number of days to add.
     */
    public static Date getDateAfterAddition( Date date, int days )
    {
        Calendar cal = Calendar.getInstance();

        cal.setTime( date );
        cal.add( Calendar.DATE, days );

        return cal.getTime();
    }

    /**
     * Returns the annualization factor for the given indicator and start-end date interval.
     */
    public static double getAnnualizationFactor( Indicator indicator, Date startDate, Date endDate )
    {
        double factor = 1.0;

        if ( indicator.isAnnualized() )
        {
            final int daysInPeriod = DateUtils.daysBetween( startDate, endDate ) + 1;

            factor = DAYS_IN_YEAR / daysInPeriod;
        }

        return factor;
    }

    /**
     * Sets the name property of each period based on the given I18nFormat.
     */
    public static List<Period> setNames( List<Period> periods, I18nFormat format )
    {
        for ( Period period : periods )
        {
            if ( period != null )
            {
                period.setName( format.formatPeriod( period ) );
            }
        }

        return periods;
    }

    /**
     * Returns a pretty string representing the interval between the given
     * start and end dates using a day, month, second format.
     *
     * @param start the start date.
     * @param end   the end date.
     * @return a string, or null if the given start or end date is null.
     */
    public static String getPrettyInterval( Date start, Date end )
    {
        if ( start == null || end == null )
        {
            return null;
        }

        long diff = end.getTime() - start.getTime();

        return DAY_SECOND_FORMAT.print( new org.joda.time.Period( diff ) );
    }

    /**
     * Returns a pretty string representing the interval between the given
     * start and end dates using a day, month, second format.
     *
     * @param ms the number of milliseconds in the interval.
     * @return a string, or null if the given start or end date is null.
     */
    public static String getPrettyInterval( long ms )
    {
        return DAY_SECOND_FORMAT.print( new org.joda.time.Period( ms ) );
    }

    /**
     * Parses the given string into a Date using the supported date formats.
     * Returns null if the string cannot be parsed.
     *
     * @param dateString the date string.
     * @return a date.
     */
    public static Date parseDate( final String dateString )
    {
        if ( StringUtils.isEmpty( dateString ) )
        {
            return null;
        }

        return DATE_FORMATTER.parseDateTime( dateString ).toDate();
    }

    /**
     * Creates a {@link java.util.Date} from the given {@link java.time.LocalDateTime}
     * based on the UTC time zone.
     *
     * @param time the LocalDateTime.
     * @return a Date.
     */
    public static Date getDate( LocalDateTime time )
    {
        Instant instant = time.toInstant( ZoneOffset.UTC );

        return Date.from( instant );
    }

    /**
     * Return the current date minus the duration specified by the given string.
     *
     * @param duration the duration string, see {@link DateUtils.getDuration}.
     * @return a Date.
     */
    public static Date nowMinusDuration( String duration )
    {
        Duration dr = DateUtils.getDuration( duration );

        LocalDateTime time = LocalDateTime.now().minus( dr );

        return DateUtils.getDate( time );
    }

    /**
     * Parses the given string into a {@link java.time.Duration} object. The
     * string syntax is [amount][unit]. The supported units are:
     *

     *

     *
"d": Days

     *
"h": Hours

     *
"m": Minutes

     *
"s": Seconds

     *

     *
     * @param duration the duration string, an example describing 12 days is "12d".
     * @return a Duration object, or null if the duration string is invalid.
     */
    public static Duration getDuration( String duration )
    {
        Matcher matcher = DURATION_PATTERN.matcher( duration );

        if ( !matcher.find() )
        {
            return null;
        }

        long amount = Long.valueOf( matcher.group( 1 ) );
        String unit = matcher.group( 2 );

        ChronoUnit chronoUnit = TEMPORAL_MAP.get( unit );

        if ( chronoUnit == null )
        {
            return null;
        }

        return Duration.of( amount, chronoUnit );
    }

    /**
     * Converts the given {@link Date} to a {@link Timestamp}.
     *
     * @param date the date to convert.
     * @return a time stamp.
     */
    public static Timestamp asTimestamp( Date date )
    {
        return new Timestamp( date.getTime() );
    }

    /**
     * Converts the given {@link Date} to a {@link java.sql.Date}.
     *
     * @param date the date to convert.
     * @return a date.
     */
    public static java.sql.Date asSqlDate( Date date )
    {
        return new java.sql.Date( date.getTime() );
    }
}


text:
<switchyard xmlns="urn:switchyard-config:switchyard:1.0" xmlns:camel="urn:switchyard-component-camel:config:1.0" xmlns:sca="http://docs.oasis-open.org/ns/opencsa/sca/200912">
    <sca:composite name="camel-service" targetNamespace="urn:switchyard-quickstart:camel-service:0.1.0">
        <sca:service name="JavaDSL" promote="JavaDSLBuilder/JavaDSL">
            <sca:binding.sca/>
        </sca:service>
        <sca:component name="JavaDSLBuilder">
            <camel:implementation.camel>
                <camel:java class="org.wildfly.camel.test.switchyard.subA.JavaDSLBuilder"/>
            </camel:implementation.camel>
            <sca:service name="JavaDSL">
                <sca:interface.java interface="org.wildfly.camel.test.switchyard.subA.JavaDSL"/>
            </sca:service>
            <sca:reference name="XMLService">
                <interface.esb inputType="java:java.lang.String"/>
            </sca:reference>
        </sca:component>
        <sca:component name="XMLComponent">
            <camel:implementation.camel>
                <camel:xml path="META-INF/route.xml"/>
            </camel:implementation.camel>
            <sca:service name="XMLService">
                <interface.esb inputType="java:java.lang.String"/>
            </sca:service>
        </sca:component>
    </sca:composite>
</switchyard>


text:
/*************************************************************************/
/*  abstract_polygon_2d_editor.h                                         */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#ifndef ABSTRACT_POLYGON_2D_EDITOR_H
#define ABSTRACT_POLYGON_2D_EDITOR_H

#include "editor/editor_node.h"
#include "editor/editor_plugin.h"
#include "scene/2d/polygon_2d.h"
#include "scene/gui/tool_button.h"

/**
	@author Juan Linietsky <reduzio@gmail.com>
*/
class CanvasItemEditor;

class AbstractPolygon2DEditor : public HBoxContainer {

	GDCLASS(AbstractPolygon2DEditor, HBoxContainer);

	ToolButton *button_create;
	ToolButton *button_edit;

	int edited_polygon;
	int edited_point;
	Vector2 edited_point_pos;
	Vector<Vector2> pre_move_edit;
	Vector<Vector2> wip;
	bool wip_active;
	bool wip_destructive;

	CanvasItemEditor *canvas_item_editor;
	EditorNode *editor;
	Panel *panel;
	ConfirmationDialog *create_resource;

protected:
	enum {

		MODE_CREATE,
		MODE_EDIT,
		MODE_CONT,

	};

	int mode;

	UndoRedo *undo_redo;

	virtual void _menu_option(int p_option);
	void _wip_close();
	void _canvas_draw();

	void _notification(int p_what);
	void _node_removed(Node *p_node);
	static void _bind_methods();

	bool _is_empty() const;
	void _commit_action();

protected:
	virtual Node2D *_get_node() const = 0;
	virtual void _set_node(Node *p_polygon) = 0;

	virtual int _get_polygon_count() const;
	virtual Vector2 _get_offset(int p_idx) const;
	virtual Variant _get_polygon(int p_idx) const;
	virtual void _set_polygon(int p_idx, const Variant &p_polygon) const;

	virtual void _action_add_polygon(const Variant &p_polygon);
	virtual void _action_remove_polygon(int p_idx);
	virtual void _action_set_polygon(int p_idx, const Variant &p_polygon);
	virtual void _action_set_polygon(int p_idx, const Variant &p_previous, const Variant &p_polygon);

	virtual bool _has_resource() const;
	virtual void _create_resource();

public:
	bool forward_gui_input(const Ref<InputEvent> &p_event);
	void edit(Node *p_polygon);
	AbstractPolygon2DEditor(EditorNode *p_editor, bool p_wip_destructive = true);
};

class AbstractPolygon2DEditorPlugin : public EditorPlugin {

	GDCLASS(AbstractPolygon2DEditorPlugin, EditorPlugin);

	AbstractPolygon2DEditor *polygon_editor;
	EditorNode *editor;
	String klass;

public:
	virtual bool forward_canvas_gui_input(const Transform2D &p_canvas_xform, const Ref<InputEvent> &p_event) { return polygon_editor->forward_gui_input(p_event); }

	bool has_main_screen() const { return false; }
	virtual String get_name() const { return klass; }
	virtual void edit(Object *p_object);
	virtual bool handles(Object *p_object) const;
	virtual void make_visible(bool p_visible);

	AbstractPolygon2DEditorPlugin(EditorNode *p_node, AbstractPolygon2DEditor *p_polygon_editor, String p_class);
	~AbstractPolygon2DEditorPlugin();
};

#endif // ABSTRACT_POLYGON_2D_EDITOR_H


text:
package me.itszooti.geojson;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.notNullValue;

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

import org.junit.Before;
import org.junit.Test;

public class GeoMultiPolygonTest {

	private GeoMultiPolygon multiPolygon;

	@Before
	public void before() {
		List<List<GeoPosition>> exteriors = new ArrayList<List<GeoPosition>>();
		exteriors.add(Arrays.asList(new GeoPosition[] {
			new GeoPosition(100.0, 0.0),
			new GeoPosition(101.0, 0.0),
			new GeoPosition(101.0, 1.0),
			new GeoPosition(100.0, 1.0),
			new GeoPosition(100.0, 0.0)
		}));
		exteriors.add(Arrays.asList(new GeoPosition[] {
			new GeoPosition(100.0, 0.0),
			new GeoPosition(101.0, 0.0),
			new GeoPosition(101.0, 1.0),
			new GeoPosition(100.0, 1.0),
			new GeoPosition(100.0, 0.0)
		}));

		List<List<List<GeoPosition>>> interiors = new ArrayList<List<List<GeoPosition>>>();
		interiors.add(new ArrayList<List<GeoPosition>>());
		List<List<GeoPosition>> interior = new ArrayList<List<GeoPosition>>();
		interior.add(Arrays.asList(new GeoPosition[] {
			new GeoPosition(100.2, 0.2),
			new GeoPosition(100.8, 0.2),
			new GeoPosition(100.8, 0.8),
			new GeoPosition(100.2, 0.8),
			new GeoPosition(100.2, 0.2)
		}));
		interiors.add(interior);
		multiPolygon = new GeoMultiPolygon(exteriors, interiors);
	}

	@Test
	public void getNumPolygons() {
		assertThat(multiPolygon.getNumPolygons(), equalTo(2));
	}

	@Test
	public void getPolygon() {
		// check no holes polygon
		GeoPolygon polygonNoHoles = multiPolygon.getPolygon(0);
		assertThat(polygonNoHoles.getNumInteriors(), equalTo(0));
		GeoPosition[] noHolesexterior = polygonNoHoles.getExterior();
		assertThat(noHolesexterior, notNullValue());
		assertThat(noHolesexterior.length, equalTo(5));
		assertThat(noHolesexterior[2], equalTo(new GeoPosition(101.0, 1.0)));

		// check with holes polygon
		GeoPolygon polygonWithHoles = multiPolygon.getPolygon(1);
		assertThat(polygonWithHoles.getNumInteriors(), equalTo(1));
		GeoPosition[] withHolesInterior = polygonWithHoles.getInterior(0);
		assertThat(withHolesInterior, notNullValue());
		assertThat(withHolesInterior.length, equalTo(5));
		assertThat(withHolesInterior[0], equalTo(new GeoPosition(100.2, 0.2)));
	}

	@Test
	public void isGeoGeometry() {
		assertThat(multiPolygon, instanceOf(GeoGeometry.class));
	}

}


text: Rails.application.config.session_store :cookie_store, key: '_mirrorkat_session'


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
            <solid android:color="@color/vk_color_800" />
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
            <solid android:color="@color/vk_color_800" />
        </shape>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
            <solid android:color="@color/vk_color_500" />
        </shape>
    </item>
</selector>


text:
namespace cppcoro
{
	class inline_scheduler
	{
	public:

		inline_scheduler() noexcept = default;

		std::experimental::suspend_never schedule() const noexcept
		{
			return {};
		}
	};
}

#endif


text:
@interface MGOTextField : UITextField

@end


text:
Login

            <form class="form-horizontal">

                    Email

                        <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

                    Password

                        <input type="password" class="form-control" id="inputPassword3" placeholder="Password">

                                <input type="checkbox"> Remember me

                        <button type="submit" class="btn btn-default" data-dojo-attach-point="loginNode">Sign in</button>

            </form>


text:
package rubberneck_test

import (
	"fmt"

	. "github.com/relistan/rubberneck"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Rubberneck", func() {
	Describe("NewDefaultPrinter()", func() {
		It("returns a properly configured Printer", func() {
			printer := NewDefaultPrinter()
			Expect(printer.Show).NotTo(BeNil())
			Expect(printer.Mask).To(BeNil())
		})
	})

	Describe("NewPrinter()", func() {
		var didRun bool
		var didAddLineFeed bool

		var printFunc func(format string, v ...interface{})
		var printable struct{ Content string }
		var receivedFormat string

		// This ridiculous line is required to get Go to compile tests.
		// Without it, it says receivedFormat is not used. If I remove
		// receivedFormat it complains about it in the BeforeEach block,
		// because it's _obviously_ not defined.
		if receivedFormat == "" { receivedFormat = "" }

		BeforeEach(func() {
			didRun = false
			didAddLineFeed = false

			printFunc = func(format string, v ...interface{}) {
				didRun = true
				if format[len(format)-1] == '\n' {
					didAddLineFeed = true
				}
				receivedFormat = format
			}

			printable = struct{ Content string }{"grendel"}
		})

		It("returns a properly configured Printer without line feed", func() {
			printer := NewPrinter(printFunc, NoAddLineFeed)
			Expect(printer.Show).NotTo(BeNil())

			printer.Print(printable)
			Expect(didRun).To(BeTrue())
			Expect(didAddLineFeed).To(BeFalse())
		})

		It("returns a properly configured Printer with line feed", func() {
			printer := NewPrinter(printFunc, AddLineFeed)
			Expect(printer.Show).NotTo(BeNil())

			printer.Print(printable)
			Expect(didRun).To(BeTrue())
			Expect(didAddLineFeed).To(BeTrue())
		})
	})

	Describe("NewPrinterWithKeyMasking()", func() {
		var didPrint bool
		var didMask bool

		var printFunc func(format string, v ...interface{})
		var maskFunc func(argument string) *string
		var printable struct{ Content string }
		var printedValue = ""

		BeforeEach(func() {
			didPrint = false
			didMask = false

			printFunc = func(format string, v ...interface{}) {
				didPrint = true
				printedValue += fmt.Sprintf(format, v...)
			}
			maskFunc = func(argument string) *string {
				if argument == "Content" {
					didMask = true
					mask := "MASKED"
					return &mask
				}
				return nil
			}

			printable = struct{ Content string }{"grendel"}
		})

		It("returns a properly configured Printer", func() {
			printer := NewPrinterWithKeyMasking(printFunc, maskFunc, AddLineFeed)
			Expect(printer.Show).NotTo(BeNil())
			Expect(printer.Mask).NotTo(BeNil())

			printer.Print(printable)
			Expect(didPrint).To(BeTrue())
			Expect(didMask).To(BeTrue())
			Expect(printedValue).NotTo(HaveLen(0))
			Expect(printedValue).To(ContainSubstring("MASKED"))
		})
	})

	Describe("when printing with", func() {
		var printFunc func(format string, v ...interface{})
		var printable struct {
			Content []string
			Another struct{ Included string }
			private bool
		}
		var output string
		var printer *Printer

		BeforeEach(func() {
			output = ""

			printFunc = func(format string, v ...interface{}) {
				output += fmt.Sprintf(format, v...)
			}

			printable = struct {
				Content []string
				Another struct{ Included string }
				private bool
			}{
				[]string{"njal", "groenlendinga"},
				struct{ Included string }{"leif"},
				true,
			}

			printer = NewPrinter(printFunc, AddLineFeed)
		})

		Describe("PrintWithLabel()", func() {
			It("generates correct output", func() {
				printer.PrintWithLabel("saga", printable)
				Expect(output).To(ContainSubstring("saga ----"))
				Expect(output).To(ContainSubstring("Content: [njal groenlendinga]"))
				Expect(output).To(MatchRegexp("\\* Another:\n\\s+\\* Included: leif"))
			})

			It("generates correct output when passed a pointer", func() {
				printer.PrintWithLabel("saga", &printable)
				Expect(output).To(ContainSubstring("saga ----"))
				Expect(output).To(ContainSubstring("Content: [njal groenlendinga]"))
				Expect(output).To(MatchRegexp("\\* Another:\n\\s+\\* Included: leif"))
			})

			It("excludes private struct members", func() {
				printer.PrintWithLabel("saga", &printable)
				Expect(output).NotTo(ContainSubstring("private"))
			})

			It("handles labels longer than 50", func() {
				printer.PrintWithLabel("0123456789012345678901234567890123456789012345678901234567891234", &printable)
				Expect(output).To(ContainSubstring("------------------------------------------------------"))
			})
		})

		Describe("Print()", func() {
			It("complains when passed a string", func() {
				printer.Print("saga", printable)
				Expect(output).To(ContainSubstring("Expected to print a struct"))
				Expect(output).NotTo(ContainSubstring("Content: [njal groenlendinga]"))
				Expect(output).NotTo(MatchRegexp("\\* Another:\n\\s+\\* Included: leif"))
			})
		})
	})

	Describe("handling values", func() {
		var printFunc func(format string, v ...interface{})
		var printable struct {
			Bad *int
		}
		var output string
		var printer *Printer

		BeforeEach(func() {
			output = ""

			printFunc = func(format string, v ...interface{}) {
				output += fmt.Sprintf(format, v...)
			}

			printable = struct {
				Bad *int
			}{}

			printer = NewPrinter(printFunc, AddLineFeed)
		})

		It("handles nil pointers", func() {
			test := func() { printer.Print(printable) }

			Expect(test).NotTo(Panic())
		})
	})
})


text:
FPUTC — Write a single character in stream mode

Description

Write a single character in stream mode by bypassing normal formatted
output. Stream I/O should not be mixed with normal record-oriented
(formatted or unformatted) I/O on the same unit; the results are unpredictable.

This intrinsic is provided in both subroutine and function forms; however,
only one form can be used in any given program unit.

Note that the FGET intrinsic is provided for backwards compatibility with
<samp>g77</samp>.  GNU Fortran provides the Fortran 2003 Stream facility.
Programmers should consider the use of new stream IO feature in new code
for future portability. See also Fortran 2003 status.

Syntax

CALL FPUTC(UNIT, C [, STATUS])

STATUS = FPUTC(UNIT, C)

Arguments

<var>UNIT</var>   	The type shall be INTEGER.

<var>C</var>      	The type shall be CHARACTER and of default
kind.

<var>STATUS</var> 	(Optional) status flag of type INTEGER.
Returns 0 on success, -1 on end-of-file and a system specific positive
error code otherwise.

Example

PROGRAM test_fputc

  CHARACTER(len=10) :: str = "gfortran"

  INTEGER :: fd = 42, i

  OPEN(UNIT = fd, FILE = "out", ACTION = "WRITE", STATUS="NEW")

  DO i = 1, len_trim(str)

    CALL fputc(fd, str(i:i))

  END DO

  CLOSE(fd)

END PROGRAM

Standard

GNU extension

Class

Subroutine, function

See also

FPUT, FGET, FGETC


text:
title: 'Moving Slackware to kernel 3.10: NVIDIA and Broadcom drivers fixes'
date: 2013-08-11 05:03
published: true
taxonomy:
    category: Tecnologia
    tag: [development, network, software, update, -current, broadcom, slackware, nvidia, build, macbook pro, linux, kernel, 3.10.5, slackbuild, driver]
slug: moving-slackware-to-kernel-310-fixes-to
body_classes: 'single single-post'
---

Last Tuesday, the 6th Aug, Pat (Patrick Volkerding, Slackware's
[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life))
released Linux kernel 3.10.5 in the -current tree. Bellow you can read
Mr. Pat statement for this move:

===

> Looks like 3.10.x got LTS status, but more importantly fixes the power
> issue on resume with some Intel machines. So, we're bumping the kernel
> to 3.10.5, and will stick with that series for the release. A few more
> things to look at before calling this a beta, but it's pretty close.
> Enjoy!
>
> -- Patrick Volkerding

Well done, Pat. But the move, at least for me, owner of a MacBook Pro
7,1, was far from what I can name an enjoyable task. Not your fault
tough. The one to blame is always those crappy proprietary hardware and
its drivers.

NVIDIA and Broadcom drivers, at least as they are distributed at
[SlackBuilds.org](http://slackbuilds.org/) just don't compile under the
new 3.10 series kernel. Both is going to miserably fail when you try to
compile them either using slackbuild's scripts or straight from the
vendors tarballs.

So, let's troubleshoot it.

## NVIDIA

NVIDIA was an easy fix. LinuxQuestion's user WhiteWolf1776 reported on a
[post](http://www.linuxquestions.org/questions/slackware-14/new-nvidia-drivers-325-15-support-3-10-kernel-4175472319/#post5003987)
that "like it was planned, -current moves to 3.10 series and nVidia
releases a new driver 325.15." So you can build NVIDIA driver
successfully on your brand new 3.10.5 kernel, you can use the slackbuild
[provided](https://github.com/WhiteWolf1776/Bumblebee-SlackBuilds)
by WhiteWolf1776 or you can just copy (what I've done) your
SlackBuild.org's scripts
([nvidia-kernel](http://slackbuilds.org/repository/14.0/system/nvidia-kernel/)
and
[nvidia-driver](http://slackbuilds.org/repository/14.0/system/nvidia-driver/)),
edit .info to change version, download URL's and md5 checksum, edit
.SlackBuild to change versions and then build. They are going to build
and install with no errors.

## Broadcom

Unlike NVIDIA drivers, Broadcom was a pain in the ass. Broadcom is lazy
enough to don't upgrade their proprietary Linux drivers since 2011. So,
after each major change on kernel's API or some core code used by the
WiFi card drivers, good developers out there must do their work and fix
that shit on Broadcom's side so it can compile and run on newer Linuxes.
Of course that somewhere in the future this trick will not work anymore.
But at least for now we, the poor Broadcom enabled hardware owners, are
in a safe place! Kudos to the Arch Linux [broadcom-wl
package](https://aur.archlinux.org/packages/broadcom-wl/)
maintainer, Krejzi. He managed to patch the driver for that distribution
and I've put it together for Slackware.

So, to cut the crap talk out, all you have to do is to clone my GitHub
[repository](https://github.com/denydias/slackbuilds/tree/master/broadcom-sta)
for that driver, download the Broadcom's driver tarball from the vendor
[website](http://www.broadcom.com/support/802.11/linux_sta.php) in the
same directory as the slackbuild lives and run the slackbuild script. It
should build with success and place a package ready to install under
your /temp. Install it and you should be good to go with no cables.

Now, just as Pat said before, enjoy!


text:
New Auction

        <form ng-submit="createItem()">

                    Product Name
                    <input type="text" ng-model="item.name" class="form-control" required>

                    Select Categories
                    <select class="form-control" ng-change="addCategory(cat)" ng-model="cat" required>
                        <option ng-repeat="cat in categories" value={{cat.name}}>
                            {{cat.name}}
                        </option>
                    </select>

                        {{cat2.name}}

                    Product Buying Price
                    <input class="form-control" ng-model="item.buyPrice" type="number" min="1" required>

                    Product Starting bid price
                    <input class="form-control" ng-model="item.firstBid" type="number" min="1" required>

                    Product bidding ends
                    <input type="date" class="form-control" ng-model="item.ends"  placeholder="eg 2013-10-22" required>

                    Product Location Name
                    <input type="text" class="form-control" ng-model="item.location.name" required>

                    Product Country
                    <input type="text" class="form-control" ng-model="item.country" required>

Drop images here or click to upload

File Drag/Drop is not supported for this browser

                    Images:

{{f.name}} {{f.$error}} {{f.$errorParam}}

                    Product Description
                    <textarea class="form-control" type="text" ng-model="item.description" placeholder="Add your description here" required></textarea>

                    <button class="col-sm-12 btn btn-primary btn-lg">Create new auction</button>

        </form>

.


text:
package org.fhcrc.cpl.viewer.align.commandline;

import org.fhcrc.cpl.viewer.commandline.modules.BaseViewerCommandLineModuleImpl;
import org.fhcrc.cpl.toolbox.commandline.arguments.*;
import org.fhcrc.cpl.viewer.align.PeptideArrayAnalyzer;
import org.fhcrc.cpl.toolbox.gui.chart.PanelWithScatterPlot;
import org.fhcrc.cpl.toolbox.gui.chart.PanelWithBoxAndWhiskerChart;
import org.fhcrc.cpl.toolbox.proteomics.feature.Feature;
import org.fhcrc.cpl.toolbox.proteomics.feature.FeatureSet;
import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.MS2ExtraInfoDef;
import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.IsotopicLabelExtraInfoDef;
import org.fhcrc.cpl.toolbox.proteomics.ProteinUtilities;
import org.fhcrc.cpl.toolbox.proteomics.filehandler.ProtXmlReader;
import org.fhcrc.cpl.toolbox.proteomics.commandline.arguments.FeatureFileArgumentDefinition;
import org.fhcrc.cpl.toolbox.ApplicationContext;
import org.fhcrc.cpl.toolbox.statistics.BasicStatistics;
import org.fhcrc.cpl.toolbox.datastructure.Pair;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException;
import org.fhcrc.cpl.toolbox.commandline.CommandLineModule;
import org.apache.log4j.Logger;

import java.util.*;
import java.io.*;

/**
 * Command linemodule for feature finding
 */
public class CaseControlRatioAnalyzerCLM extends BaseViewerCommandLineModuleImpl
        implements CommandLineModule
{
    protected static Logger _log = Logger.getLogger(CaseControlRatioAnalyzerCLM.class);

    protected FeatureSet pepXmlFeatureSet;
    protected File protXmlFile;
    protected File pepArrayFile;
    List<String> caseRunNameList;
    List<String> controlRunNameList;

    protected String proteinToAnalyze;

    protected boolean showCharts = false;

    Object[] arrayRows;

    public CaseControlRatioAnalyzerCLM()
    {
        init();
    }

    protected void init()
    {
        mCommandName = "analyzecasecontrolratio";

        mShortDescription = "analyzecasecontrolratio";
        mHelpMessage = "analyzecasecontrolratio";

        CommandLineArgumentDefinition[] argDefs =
                {
                        new FileToReadArgumentDefinition("protxml",true,"protxml"),
                        new FeatureFileArgumentDefinition("pepxml",true,"pepxml"),
                        new FileToReadArgumentDefinition("peparray",true,"peptide array"),

                        new StringArgumentDefinition("protein", true, "Protein to analyze"),

                        new FileToReadArgumentDefinition("caserunlistfile",true,"File containing the names of runs in the case group, one per line"),
                            new FileToReadArgumentDefinition("controlrunlistfile",true,"File containing the names of runs in the control group, one per line"),

                        new BooleanArgumentDefinition("showcharts", false, "show charts?", showCharts),

                };
        addArgumentDefinitions(argDefs);
    }

    public void assignArgumentValues()
            throws ArgumentValidationException
    {
        proteinToAnalyze = getStringArgumentValue("protein");

        showCharts = getBooleanArgumentValue("showcharts");

        protXmlFile = getFileArgumentValue("protXml");
        pepArrayFile = getFileArgumentValue("peparray");

        pepXmlFeatureSet = getFeatureSetArgumentValue("pepxml");

        File caseRunListFile = getFileArgumentValue("caserunlistfile");
        File controlRunListFile = getFileArgumentValue("controlrunlistfile");

        try
        {
            BufferedReader br = new BufferedReader(new FileReader(caseRunListFile));
            caseRunNameList = new ArrayList<String>();
            while (true)
            {
                String line = br.readLine();
                if (null == line)
                    break;
                if (line.length() == 0 || line.charAt(0) == '#')
                    continue;
                caseRunNameList.add(line);
            }

            br = new BufferedReader(new FileReader(controlRunListFile));
            controlRunNameList = new ArrayList<String>();
            while (true)
            {
                String line = br.readLine();
                if (null == line)
                    break;
                if (line.length() == 0 || line.charAt(0) == '#')
                    continue;
                controlRunNameList.add(line);
            }

            ApplicationContext.infoMessage("Case runs:");
            for (String caseRun : caseRunNameList)
                ApplicationContext.infoMessage("\t" + caseRun);
            ApplicationContext.infoMessage("Control runs:");
            for (String controlRun : controlRunNameList)
                ApplicationContext.infoMessage("\t" + controlRun);
        }
        catch (Exception e)
        {
            throw new ArgumentValidationException(e);
        }
    }

    /**
     * do the actual work
     */
    public void execute() throws CommandLineModuleExecutionException
    {
        PeptideArrayAnalyzer pepArrayAnalyzer  = null;
        Map<String, List<Map<String, Object>>> peptideRowsMap = new HashMap<String, List<Map<String, Object>>>();
        try
        {
            pepArrayAnalyzer = new PeptideArrayAnalyzer(pepArrayFile);
            arrayRows = pepArrayAnalyzer.getRowMaps();

                for (Object rowMapObj : arrayRows)
                {
                    Map<String, Object> rowMap = (Map<String, Object>) rowMapObj;
                    Set<String> rowPeptides = pepArrayAnalyzer.getAllRowPeptides(rowMap);
                    if (rowPeptides.size() == 1)
                    {
                        String peptide = rowPeptides.iterator().next();
                        List<Map<String, Object>> rowsThisPeptide = peptideRowsMap.get(peptide);
                        if (rowsThisPeptide == null)
                        {
                            rowsThisPeptide = new ArrayList<Map<String, Object>>();
                            peptideRowsMap.put(peptide, rowsThisPeptide);
                        }
                        rowsThisPeptide.add(rowMap);
                    }
                }
        }
        catch (IOException e)
        {
            throw new CommandLineModuleExecutionException("Failed to open peptide array file");
        }
        try
        {
            ProtXmlReader.Protein protXmlProtein = ProteinUtilities.loadFirstProteinOccurrence(protXmlFile, proteinToAnalyze);
            float proteinRatio = protXmlProtein.getQuantitationRatio().getRatioMean();
            ApplicationContext.infoMessage("Protein: " + protXmlProtein.getProteinName() + ", prob: " +
                    protXmlProtein.getProbability() + ", ratio: " + proteinRatio);
            Map<String, Set<String>> proteinPeptideMap = ProteinUtilities.loadProteinPeptideSequenceMapFromProtXML(protXmlFile, 0f);
            Set<String> proteinPeptides =proteinPeptideMap.get(proteinToAnalyze);

            Map<String, List<Pair<List<Float>, List<Float>>>> peptideCaseControlIntensitiesMap =
                    new HashMap<String, List<Pair<List<Float>, List<Float>>>>();
            Map<String, List<Float>> peptideLogRatiosMap = new HashMap<String, List<Float>>();

            for (Feature feature : pepXmlFeatureSet.getFeatures())
            {
                if (!IsotopicLabelExtraInfoDef.hasRatio(feature))
                    continue;
                String peptide = MS2ExtraInfoDef.getFirstPeptide(feature);
                if (!proteinPeptides.contains(peptide))
                    continue;
                float peptideRatio = (float) IsotopicLabelExtraInfoDef.getRatio(feature);
                List<Float> logRatiosThisPeptide = peptideLogRatiosMap.get(peptide);
                if (logRatiosThisPeptide == null)
                {
                    logRatiosThisPeptide = new ArrayList<Float>();
                    peptideLogRatiosMap.put(peptide, logRatiosThisPeptide);

                }
                logRatiosThisPeptide.add((float) Math.log(peptideRatio));

            }

            PanelWithScatterPlot pwspPeptideLogRatios = new PanelWithScatterPlot();
            pwspPeptideLogRatios.setName("log-ratios by peptide");
            pwspPeptideLogRatios.setPointSize(4);
            pwspPeptideLogRatios.getChart().getXYPlot().setDomainCrosshairValue(Math.log(proteinRatio), true);
            pwspPeptideLogRatios.getChart().getXYPlot().setDomainCrosshairVisible(true);
            int peptideIndex = 0;
            float maxAbsValue = -5000;
            for (String peptide : peptideLogRatiosMap.keySet())
            {
                List<Float> logRatiosThisPeptide = peptideLogRatiosMap.get(peptide);
                float meanRatioThisPeptide = (float) Math.exp(BasicStatistics.mean(logRatiosThisPeptide));
                ApplicationContext.infoMessage("Peptide " + peptide + ": geo mean ratio: " + meanRatioThisPeptide + ", observations: " + logRatiosThisPeptide.size());

                List<Float> yValues = new ArrayList<Float>();
                for (float blah : logRatiosThisPeptide)
                    yValues.add((float) peptideIndex);

                pwspPeptideLogRatios.addData(logRatiosThisPeptide, yValues, peptide);

                for (float value : logRatiosThisPeptide)
                    maxAbsValue = Math.max(maxAbsValue, Math.abs(value));

                peptideIndex++;
            }

            float maxChartAxis = (float) Math.max(Math.log(10), maxAbsValue);
            float minChartAxis = -maxChartAxis;
            pwspPeptideLogRatios.getChart().getXYPlot().getDomainAxis().setLowerBound(minChartAxis);
            pwspPeptideLogRatios.getChart().getXYPlot().getDomainAxis().setUpperBound(maxChartAxis);
            pwspPeptideLogRatios.displayInTab();

            //todo: cut this out when moving to ProtXmlProteinInfoCLM
            for (String peptide : peptideLogRatiosMap.keySet())
            {
                List<Pair<List<Float>, List<Float>>> caseControlIntensitiesThisPeptide = new ArrayList<Pair<List<Float>, List<Float>>>();
                peptideCaseControlIntensitiesMap.put(peptide, caseControlIntensitiesThisPeptide);
                for (Map<String, Object> rowMap : peptideRowsMap.get(peptide))
                {
                    List<Float> caseIntensities = new ArrayList<Float>();
                    for (String run : caseRunNameList)
                    {
                        if (rowMap.containsKey("intensity_" + run))
                            caseIntensities.add(Float.parseFloat(rowMap.get("intensity_" + run).toString()));
                    }
                    List<Float> controlIntensities = new ArrayList<Float>();
                    for (String run : controlRunNameList)
                    {
                        if (rowMap.containsKey("intensity_" + run))
                            controlIntensities.add(Float.parseFloat(rowMap.get("intensity_" + run).toString()));
                    }

                    if (caseIntensities.size() > 1 && controlIntensities.size() > 1)
                    {

                        Pair<List<Float>, List<Float>> caseControlIntensities = new Pair<List<Float>, List<Float>>(caseIntensities, controlIntensities);
                        caseControlIntensitiesThisPeptide.add(caseControlIntensities);

                        PanelWithBoxAndWhiskerChart intensityBoxPlots = new PanelWithBoxAndWhiskerChart("intensities");
                        intensityBoxPlots.addData(caseIntensities, "case");
                        intensityBoxPlots.addData(controlIntensities, "control");

                        intensityBoxPlots.displayInTab();
                    }
                }
            }
            //todo: end cut out part

        }
        catch (Exception e)
        {
            throw new CommandLineModuleExecutionException(e);
        }
    }

}


text:
import {xtract_skewness_kurtosis} from "./xtract_skewness_kurtosis";
export function xtract_skewness(array, mean, standard_deviation) {
    return xtract_skewness_kurtosis(array, mean, standard_deviation)[0];
}


text:
{% extends "layout.html" %}
{% block styles %}
  {{super()}}
  <link rel="stylesheet" href={{ url_for('calendar.static', filename='style.css')}}>
{% endblock %}
{% block content %}
<base target="_parent" />

   <

 Share Calendar

<form method="POST" action="{{ url_for('calendar.calendar_share_cal') }}">

            Google Email:

          <input type="text" name="email" class="form-control" required />

            Calendar:

            {% for item in permissions if item != 'Any'%}
              <input type="checkbox" name="tag" value="{{ item }}">{{ item }}
            {% endfor %}

             Access Level (if you selected multiple and request edit-level, it will apply them automatically
            ):

            <select class="form-control" name="access_level">
              <option value="reader">Read</option>
              {% if permissions %}
                <option value="writer">Edit</option>
              {% endif %}
            </select>

      <input class="btn" type="submit" value="Submit" />

</form>

{% endblock %}


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
namespace DotNetNuke.Build.Tasks
{
    using System;
    using System.Collections.Generic;

    using Cake.Common.Build;
    using Cake.Common.Build.AzurePipelines.Data;
    using Cake.Common.IO;
    using Cake.Common.Tools.MSBuild;
    using Cake.Core.IO;
    using Cake.Frosting;
    using Cake.Issues;
    using Cake.Issues.MsBuild;
    using DotNetNuke.Build;

    /// <summary>A cake task to compile the platform.</summary>
    [IsDependentOn(typeof(CleanWebsite))]
    [IsDependentOn(typeof(RestoreNuGetPackages))]
    public sealed class Build : FrostingTask<Context>
    {
        /// <inheritdoc/>
        public override void Run(Context context)
        {
            // TODO: when Cake.Issues.MsBuild is updated to support Binary Log version 9, can use .EnableBinaryLogger() instead of .WithLogger(…)
            // TODO: also can remove the .InstallTool(…) call for Cake.Issues.MsBuild in Program.cs at that point
            var cleanLog = context.ArtifactsDir.Path.CombineWithFilePath("clean.binlog");
            var buildLog = context.ArtifactsDir.Path.CombineWithFilePath("rebuild.binlog");
            try
            {
                var cleanSettings = CreateMsBuildSettings(context, cleanLog).WithTarget("Clean");
                context.MSBuild(context.DnnSolutionPath, cleanSettings);

                var buildSettings = CreateMsBuildSettings(context, buildLog)
                    .SetPlatformTarget(PlatformTarget.MSIL)
                    .WithTarget("Rebuild")
                    .WithProperty("SourceLinkCreate", "true");
                context.MSBuild(context.DnnSolutionPath, buildSettings);
            }
            finally
            {
                var issues = context.ReadIssues(
                    new List<IIssueProvider>
                    {
                        new MsBuildIssuesProvider(
                            context.Log,
                            new MsBuildIssuesSettings(cleanLog, context.MsBuildBinaryLogFileFormat())),
                        new MsBuildIssuesProvider(
                            context.Log,
                            new MsBuildIssuesSettings(buildLog, context.MsBuildBinaryLogFileFormat())),
                    },
                    context.Directory("."));

                foreach (var issue in issues)
                {
                    var messageData = new AzurePipelinesMessageData
                    {
                        SourcePath = issue.AffectedFileRelativePath?.FullPath,
                        LineNumber = issue.Line,
                    };

                    if (string.Equals(issue.PriorityName, "Error", StringComparison.Ordinal))
                    {
                        context.AzurePipelines().Commands.WriteError(issue.MessageText, messageData);
                    }
                    else
                    {
                        context.AzurePipelines().Commands.WriteWarning(issue.MessageText, messageData);
                    }
                }
            }
        }

        private static MSBuildSettings CreateMsBuildSettings(Context context, FilePath binLogPath)
        {
            return new MSBuildSettings().SetConfiguration(context.BuildConfiguration)
                .SetMaxCpuCount(0)
                .WithLogger(context.Tools.Resolve("Cake.Issues.MsBuild*/**/StructuredLogger.dll").FullPath, "BinaryLogger", binLogPath.FullPath)
                .SetNoConsoleLogger(context.IsRunningInCI);
        }
    }
}


text:
.class final synthetic Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;
.super Ljava/lang/Object;

# interfaces
.implements Ljava/lang/Runnable;

# instance fields
.field private final synthetic -$f0:Ljava/lang/Object;

.field private final synthetic -$f1:Ljava/lang/Object;

# direct methods
.method private final synthetic $m$0()V
    .locals 2

    iget-object v0, p0, Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;->-$f0:Ljava/lang/Object;

    check-cast v0, Landroid/view/accessibility/AccessibilityManager$1;

    iget-object v1, p0, Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;->-$f1:Ljava/lang/Object;

    check-cast v1, Landroid/view/accessibility/AccessibilityManager$AccessibilityServicesStateChangeListener;

    invoke-virtual {v0, v1}, Landroid/view/accessibility/AccessibilityManager$1;->lambda$-android_view_accessibility_AccessibilityManager$1_11097(Landroid/view/accessibility/AccessibilityManager$AccessibilityServicesStateChangeListener;)V

    return-void
.end method

.method public synthetic constructor <init>(Ljava/lang/Object;Ljava/lang/Object;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;->-$f0:Ljava/lang/Object;

    iput-object p2, p0, Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;->-$f1:Ljava/lang/Object;

    return-void
.end method

# virtual methods
.method public final run()V
    .locals 0

    invoke-direct {p0}, Landroid/view/accessibility/-$Lambda$T3m_l9_RA18vCOcakSWp1lZCy5g;->$m$0()V

    return-void
.end method


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('entertainment_tonight', '0019_event_event_creator'),
    ]

    operations = [
        migrations.AlterField(
            model_name='event',
            name='event_creator',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
package authorization;

import (
	"golang.org/x/crypto/bcrypt"
	"fmt"
)

// Внутри массива байт заполняет 0
func clear(b []byte) {
    for i := 0; i < len(b); i++ {
        b[i] = 0;
    }
}

// Шифрование пароля bcrypt
func Crypt(password string) (string, error) {
	bp := []byte(password)
    defer clear(bp)
    hashedBytes, err :=  bcrypt.GenerateFromPassword(bp, bcrypt.DefaultCost)
    return fmt.Sprintf("%s", hashedBytes), err
}

// Проверка пароля (хэш то каждый раз разный)
func CheckPasswordCrypt(hashed, password string) bool {
	bH := []byte(hashed)
	bP := []byte(password)
	return bcrypt.CompareHashAndPassword(bH, bP) == nil
}


text:
<title>Requirements - ECB - the Emacs Code Browser</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="ECB - the Emacs Code Browser">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="ecb.html#Top">
<link rel="up" href="Installation.html#Installation" title="Installation">
<link rel="prev" href="Installation.html#Installation" title="Installation">
<link rel="next" href="ECB-as-XEmacs_002dpackage.html#ECB-as-XEmacs_002dpackage" title="ECB as XEmacs-package">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">

Next: ECB as XEmacs-package,
Previous: Installation,
Up: Installation

1.1.1 Requirements

This section describes the requirements of ECB. Just ensure that these
requirements of ECB are fulfilled.

The short story: With Emacs >= 23.2 there is nothing to do. With XEmacs or
Emacs < 23.2 you have to install the CEDET-suite.

The long story:

Emacs-version:
ECB works only with (X)Emacs >= 21! If you have an older one, please upgrade.

CEDET-suite:
If Emacs >= 23.2 is used then CEDET is already integrated into Emacs and there
is nothing to do.

For users of any XEmacs-version, any Emacs-version < 23.2 or the latest author
CEDET version: Get it from http://cedet.sourceforge.net, read the
setup-instructions in http://cedet.sourceforge.net/setup.shtml and read
also the shipped file <samp>INSTALL</samp>.

Please note: If ECB detects an author version of CEDET (as available
at http://cedet.sourceforge.net) then ECB will ALWAYS try to use that
one even if you use Emacs >= 23.2! This is for users who want to use latest
Emacs >= 23.2 but still prefer using the latest author version of CEDET
instead of the Emacs-integrated one.

So if you want to use the Emacs-integrated CEDET-suite of Emacs >= 23.2 you
have to ensure that no author-version of CEDET is in the load-path!
This means that the library cedet.el of the author-version MUST NOT be loaded
into Emacs (as described in the file INSTALL of CEDET)! This is a valid check:
(locate-library "semantic-ctxt") must return nil!

Only for XEmacs-users:
If you use XEmacs you must have installed the
package c-support (contains hideshow.el). If you want to read the online-help
of ECB in HTML-format you must have the library browse-url (part of the
mail-lib XEmacs package) installed; this package is also needed for submitting
problem-reports to the ECB-maintainers!

Optional for Java-coding:
ECB works very well with the JDEE package (
http://jdee.sourceforge.net) but JDEE is not required by ECB.

Do not install ECB before you have successfully installed the requirements!


text:
<?php

namespace App\Controller\View\Test\Results;

use App\Exception\CoreApplicationRequestException;
use App\Exception\InvalidContentTypeException;
use App\Exception\InvalidCredentialsException;
use App\Services\TestRetriever;
use Symfony\Component\HttpFoundation\JsonResponse;

class PreparingStatsController
{
    private $testRetriever;

    public function __construct(TestRetriever $testRetriever)
    {
        $this->testRetriever = $testRetriever;
    }

    /**
     * @param int $test_id
     *
     * @return JsonResponse
     *
     * @throws CoreApplicationRequestException
     * @throws InvalidCredentialsException
     * @throws InvalidContentTypeException
     */
    public function indexAction(int $test_id): JsonResponse
    {
        $testModel = $this->testRetriever->retrieve($test_id);

        $localTaskCount = $testModel->getLocalTaskCount();
        $remoteTaskCount = $testModel->getRemoteTaskCount();

        $completionPercent = 0 === $remoteTaskCount
            ? 100
            : round(($localTaskCount / $remoteTaskCount) * 100);

        return new JsonResponse([
            'id' => $test_id,
            'completion_percent' => $completionPercent,
            'remaining_tasks_to_retrieve_count' => $remoteTaskCount - $localTaskCount,
            'local_task_count' => $localTaskCount,
            'remote_task_count' => $remoteTaskCount
        ]);
    }
}


text:
#pragma once

#include "precomp.h"

//RFC 4960
typedef struct _OVS_SCTP_HEADER
{
    UINT16 sourcePort;
    UINT16 destinationPort;
    UINT32 verificationTag;
    UINT32 checksum;
}OVS_SCTP_HEADER, *POVS_SCTP_HEADER;

typedef struct _OVS_NET_BUFFER OVS_NET_BUFFER;
typedef struct _OVS_PI_SCTP OVS_PI_SCTP;

BOOLEAN ONB_SetSctp(OVS_NET_BUFFER *pNb, const OVS_PI_SCTP* pSctpPI);
BOOLEAN VerifySctpHeader(BYTE* buffer, ULONG* pLength);


text:
<?php

namespace Marlene\ActasBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;

class JuzgadoFilterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', 'filter_number_range')
            ->add('numero', 'filter_number_range')
            ->add('direccion', 'filter_text')
            ->add('ciudad', 'filter_text')
            ->add('provincia', 'filter_text')
            ->add('rama', 'filter_text')
        ;

        $listener = function(FormEvent $event)
        {
            // Is data empty?
            foreach ($event->getData() as $data) {
                if(is_array($data)) {
                    foreach ($data as $subData) {
                        if(!empty($subData)) return;
                    }
                }
                else {
                    if(!empty($data)) return;
                }
            }

            $event->getForm()->addError(new FormError('Filter empty'));
        };
        $builder->addEventListener(FormEvents::POST_BIND, $listener);
    }

    public function getName()
    {
        return 'marlene_actasbundle_juzgadofiltertype';
    }
}


text:
package com.zg;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
@MapperScan("com.zg.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}


text:
#include <aws/waf/model/DeleteRegexPatternSetRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::WAF::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DeleteRegexPatternSetRequest::DeleteRegexPatternSetRequest() :
    m_regexPatternSetIdHasBeenSet(false),
    m_changeTokenHasBeenSet(false)
{
}

Aws::String DeleteRegexPatternSetRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_regexPatternSetIdHasBeenSet)
  {
   payload.WithString("RegexPatternSetId", m_regexPatternSetId);

  }

  if(m_changeTokenHasBeenSet)
  {
   payload.WithString("ChangeToken", m_changeToken);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection DeleteRegexPatternSetRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSWAF_20150824.DeleteRegexPatternSet"));
  return headers;

}


text:
Get Zulip notifications for your PagerDuty services!

1. {!create-stream.md!}

1. {!create-bot-construct-url-indented.md!}

1. Open the **Integrations** tab, and click **Generic Webhooks (v3)**.

1. Click **Add Webhook**.

1. Set **Webhook URL** to the URL constructed above,
   configure the **Scope Type** and **Scope** you want to receive notifications for,
   select the events you want to send under **Events to Send**,
   and click **Add Webhook**.

{!congrats.md!}

![](/static/images/integrations/pagerduty/001.png)


text:
Lock-free SharedPointer
=============
Lock-free shared pointer without extra allocation for reference counts. Nowadays, STL shared pointer implementation uses lock-free and it's performance became incrediable.
However, its basic design can't allow to remove extra memory allocation for the counter. It's bad for not only performance but also memory fragmentation.

One more thing I added here is SharedReferenceManager and Dispose. You can do retained delete with SharedReferenceManager.
All memory deallocation will be happened when you call SharedReferenceManager::UpdateReferenceManager(). However, Dispose will be called when the reference count become zero so that you can do immediate clean-up of important system resources.

Note:

1. SharedObject itself is thread safe, but SharedPointer and SharedReferenceManager::UpdateReferenceManager() aren't thread safe. You should make sure they are used only on one thread at the same time.

2. If you use SharedReferenceManager, SharedReferenceManager::UpdateReferenceManager() should be called occasionally such as in tick update, otherwise memory won't be released.

3. Thread and timer implementation only support windows platform.

Now it uses C++11 atomic.

This implementation is tested only on Windows x64 with Visual Studio 2013.


text:
namespace Digipost.Api.Client.Common
{
    /// <summary>
    ///     The sender of the message, i.e. what the receiver of the message sees as the sender of the message.
    ///     If you are delivering a message on behalf of an organization with id 5555, set this property
    ///     to 5555. If you are delivering on behalf of yourself, set this to your organization`s sender id.
    ///     The id is created by Digipost.
    /// </summary>
    public class Sender
    {
        /// <summary>
        ///     The sender of the message, i.e. what the receiver of the message sees as the sender of the message.
        /// </summary>
        /// <param name="id">The id of the sender, created by Digipost</param>
        public Sender(long id)
        {
            Id = id;
        }

        /// <summary>
        ///     The id of the sender of the message, i.e. what the receiver of the message sees as the sender of the message. If
        ///     you are delivering a message on behalf of an organization with id 5555, set this property to 5555. If you are
        ///     delivering on behalf of yourself, set this to your organization`s sender id. The id is created by Digipost.
        /// </summary>
        public long Id { get; }
    }
}