text:
import os
from mock import patch

import gulpy
from gulpy.core.task import Task, run_task, tasks
from gulpy.core.stream import Stream

gulpy._testing = True

def test_register_task():
    @Task('T1')
    def t1():
        return True

    assert 'T1' in tasks

@patch('gulpy.core.log.log')
@patch('gulpy.core.log.ok')
def test_run_success(mock_ok, mock_log):
    @Task('T1')
    def t1():
        return True

    run_task('T1')
    mock_log.assert_called_with('T1', 'Started')
    mock_ok.assert_called_with('T1', 'Finished')

@patch('gulpy.core.log.log')
@patch('gulpy.core.log.fail')
def test_run_fail(mock_fail, mock_log):
    @Task('T1')
    def t1():
        return False

    run_task('T1')
    mock_log.assert_called_with('T1', 'Started')
    mock_fail.assert_called_with('T1', 'Failed')

@patch('gulpy.core.log.fail')
def test_run_not_registered_task(mock_fail):
    run_task('other_task')
    mock_fail.assert_called_with('other_task', 'Not found')

@patch('gulpy.core.log.log')
def test_run_silent_mode(mock_log):
    @Task('silent', True)
    def t1():
        return

    run_task('silent')
    mock_log.assert_called_with('silent', 'Started - Silent Mode')

@patch('gulpy.core.log.log')
def test_run_stream(mock_log, tmpdir):
    tmpdir.join('file.txt').open('w+').write('test')

    @Task('stream')
    def task1():
        s = Stream()
        s.src(str(tmpdir.join('file.txt')))
        s.dest(str(tmpdir.join('dist')))
        return s

    run_task('stream')

    assert tmpdir.join('dist').check()
    assert tmpdir.join('dist').join('file.txt').check()


text:
import test from 'ava';
import create from '../src/draught';
import rectangle from '../src/shapes/rectangle';

test('is able to add shapes to the weakmap', t => {

    const element = document.querySelector('svg');
    const diagram = create(element, { width: 200, height: 200 });
    diagram.render(rectangle);
    diagram.render(rectangle);

    t.is(diagram.count(), 2);

});

redpajama_set_name: RedPajamaGithub


text:
A timing wheel is a specialized priority queue for a set of time-based
alarms.


text:
package types

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func TestStrSlice(t *testing.T) {
	Convey("Given StrSlice", t, func() {
		Convey("valid value", func() {
			v := []string{"a", "b", "c"}
			strSlice := StrSlice(v)
			So(len(strSlice), ShouldEqual, len(v))
			vx, err := strSlice.Value()
			So(err, ShouldEqual, nil)
			So(string(vx.([]byte)), ShouldEqual, `["a","b","c"]`)
		})

		Convey("nil value", func() {
			var strSlice StrSlice
			err := strSlice.Scan(nil)
			So(err, ShouldEqual, nil)
			So(len(strSlice), ShouldEqual, 0)
		})

		Convey("invalid value", func() {
			var strSlice StrSlice
			err := strSlice.Scan("1")
			So(err, ShouldNotEqual, nil)
			So(len(strSlice), ShouldEqual, 0)
		})

		Convey("parse null", func() {
			var strSlice StrSlice
			err := strSlice.Scan([]byte("null"))
			So(err, ShouldEqual, nil)
			So(strSlice, ShouldEqual, nil)
			So(len(strSlice), ShouldEqual, 0)
		})

		Convey("parse from JS", func() {
			var strSlice StrSlice
			err := strSlice.Scan([]byte(`["Ankara","Tokyo","Paris"]`))
			So(err, ShouldEqual, nil)
			So(len(strSlice), ShouldEqual, 3)
		})
	})
}


text:
"""Symbols exported by this module are imported into the puls namespace. Usage:

from puls import <symbol>
"""
from __future__ import absolute_import, unicode_literals, division
from puls.compat import range

import math

class AttributeDict(dict):
    def __getattr__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            raise AttributeError(key)
    __setattr__ = dict.__setattr__
    __delattr__ = dict.__delattr__

class Pagination(object):
    def __init__(self, queryset, page, per_page):
        self.current = page
        self.per_page = per_page

        self.total = queryset.count()

        self.start = (page - 1) * per_page
        self.end = min(self.total, page * per_page)

        self.items = queryset[self.start:self.end]

    def __iter__(self):
        return iter(self.items)

    @property
    def last(self):
        return int(math.ceil(self.total / float(self.per_page)))

    @property
    def prev(self):
        return self.current - 1

    @property
    def has_prev(self):
        return self.current > 1

    @property
    def has_next(self):
        return self.current < self.last

    @property
    def next(self):
        """Number of the next page"""
        return self.current + 1

    def all(self, left_edge=2, left_current=2, right_current=2, right_edge=2):
        last = 0
        for num in range(1, self.last + 1):
            if \
                    num <= left_edge or (
                        num > self.current - left_current - 1 and
                        num < self.current + right_current + 1
                    ) or \
                    num > self.last - right_edge:

                if last + 1 != num:
                    yield None
                yield num
                last = num

def paginate(queryset, page, per_page=20):
    return Pagination(queryset, page, per_page)


text:
import matplotlib.pyplot as plt

from pygridtools import viz

import pytest
import numpy.testing as nptest

@pytest.mark.parametrize('engine', ['mpl'])
def test_plot_domain_smoke(simple_boundary_gdf, engine):
    fig3 = viz.plot_domain(simple_boundary_gdf, betacol='beta')

@pytest.mark.parametrize('engine', ['mpl'])
def test_plot_boundaries_smoke(simple_boundary, simple_islands, engine):
    fig5 = viz.plot_boundaries(extent_x='x', extent_y='y', extent=simple_boundary,
                              islands_x='x', islands_y='y', islands_name='island',
                              islands=simple_islands)

    fig6 = viz.plot_boundaries(extent_x=simple_boundary['x'], extent_y=simple_boundary['y'], extent=None,
                              islands_x=simple_islands['x'], islands_y=simple_islands['y'],
                              islands_name=simple_islands['island'], islands=None)

def test_plot_points_smoke(simple_nodes):
    fig1 = viz.plot_points(*simple_nodes)

def test_plot_cells_smoke(simple_nodes):
    fig1 = viz.plot_cells(*simple_nodes)


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>
#include <stdlib.h>

#include <freerdp/primitives.h>

#include "prim_internal.h"

/* Singleton pointer used throughout the program when requested. */
static primitives_t pPrimitives = { 0 };
static primitives_t pPrimitivesGeneric = { 0 };
static BOOL pPrimitivesInitialized = FALSE;
static BOOL pPrimitivesGenericInitialized = FALSE;

/* ------------------------------------------------------------------------- */
static void primitives_init_generic(void)
{
	primitives_init_add(&pPrimitivesGeneric);
	primitives_init_andor(&pPrimitivesGeneric);
	primitives_init_alphaComp(&pPrimitivesGeneric);
	primitives_init_copy(&pPrimitivesGeneric);
	primitives_init_set(&pPrimitivesGeneric);
	primitives_init_shift(&pPrimitivesGeneric);
	primitives_init_sign(&pPrimitivesGeneric);
	primitives_init_colors(&pPrimitivesGeneric);
	primitives_init_YCoCg(&pPrimitivesGeneric);
	primitives_init_YUV(&pPrimitivesGeneric);
	pPrimitivesGenericInitialized = TRUE;
}

static void primitives_init(void)
{
	/* Now call each section's initialization routine. */
	primitives_init_add_opt(&pPrimitives);
	primitives_init_andor_opt(&pPrimitives);
	primitives_init_alphaComp_opt(&pPrimitives);
	primitives_init_copy_opt(&pPrimitives);
	primitives_init_set_opt(&pPrimitives);
	primitives_init_shift_opt(&pPrimitives);
	primitives_init_sign_opt(&pPrimitives);
	primitives_init_colors_opt(&pPrimitives);
	primitives_init_YCoCg_opt(&pPrimitives);
	primitives_init_YUV_opt(&pPrimitives);
	pPrimitivesInitialized = TRUE;
}

/* ------------------------------------------------------------------------- */
primitives_t* primitives_get(void)
{
	if (!pPrimitivesGenericInitialized)
		primitives_init_generic();

	if (!pPrimitivesInitialized)
		primitives_init();

	return &pPrimitives;
}

primitives_t* primitives_get_generic(void)
{
	if (!pPrimitivesGenericInitialized)
		primitives_init_generic();

	return &pPrimitivesGeneric;
}


text:
using Newtonsoft.Json;

namespace Synology.Api.Auth.Results
{
	/// <summary>
	///
	/// </summary>
	internal class AuthResult : IAuthResult
	{
		/// <summary>
		///
		/// </summary>
		[JsonProperty("sid")]
		public string Sid { get; set; }
	}
}


text:
package specialite;

import perso.AbstractPerso;
import specialite.competence.Competence;
import specialite.competence.CompetenceCharge;
import specialite.competence.CompetenceCoupEpee;
import specialite.competence.CompetenceTirArc;

public enum TypeSpecialite {
    GUERRIER, ARCHER, INGENIEUR;

    public Competence[] getCompetences(AbstractPerso source) {
	switch(this) {
	case GUERRIER: return new Competence[] {new CompetenceCoupEpee(source), new CompetenceCharge(source)};
	case ARCHER: return new Competence[] {new CompetenceTirArc(source)};
	case INGENIEUR: return new Competence[] {};
	default: throw new IllegalAccessError("Non implemente");
	}
    }
}


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

<!DOCTYPE document [
  <!ENTITY project SYSTEM "project.xml">
]>
<document url="cluster-listener.html">

  &project;

  <properties>
    <author email="fhanik@apache.org">Filip Hanik</author>
    <title>The ClusterListener object</title>
  </properties>

<toc/>

    The org.apache.catalina.ha.ClusterListener base class
    lets you listen in on messages that are received by the Cluster component.

   When using the DeltaManager, the messages are received by the Cluster object and are propagated to the
   to the manager through this listener.

  <subsection name="Common Attributes">

  <attributes>

    <attribute name="className" required="true">

    </attribute>

  </attributes>

  </subsection>

</document>


text:
<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->date('birthday');
            $table->string('occupation');
            $table->text('notes')->nullable();
            $table->timestamps();
        });
    }

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


text:
from . import config
from . import something
from .cases import XTracebackTestCase, skipIfNoPygments

class TestXTraceback(XTracebackTestCase):

    def test_simple(self):
        self._check_tb_str(config.BASIC_TEST, config.SIMPLE_EXCEPTION)

    def test_simple_str(self):
        exc_info = self._get_exc_info(config.BASIC_TEST)
        xtb = self._factory(*exc_info)
        self._assert_tb_str(str(xtb), config.SIMPLE_EXCEPTION)

    @skipIfNoPygments
    def test_simple_str_color(self):
        exc_info = self._get_exc_info(config.BASIC_TEST)
        xtb = self._factory(*exc_info, **dict(color=True))
        self._assert_tb_str("".join(xtb.format_exception()),
                            config.SIMPLE_EXCEPTION_COLOR)

    def test_simple_no_tb(self):
        etype, value = self._get_exc_info(config.BASIC_TEST)[:-1]
        xtb = self._factory(etype, value, None)
        self._assert_tb_str(str(xtb), config.SIMPLE_EXCEPTION_NO_TB)

    def test_with_globals(self):
        self._check_tb_str(config.BASIC_TEST, config.WITH_GLOBALS_EXCEPTION, one=1)

    def test_with_show_globals(self):
        exc_info = self._get_exc_info(config.BASIC_TEST, one=1)
        xtb = self._factory(show_globals=True, *exc_info)
        self._assert_tb_str(str(xtb), config.WITH_SHOW_GLOBALS_EXCEPTION)

    def test_extended(self):
        exc_info = self._get_exc_info(config.EXTENDED_TEST,
                                      Something=something.Something)
        xtb = self._factory(show_globals=True, *exc_info)
        self._assert_tb_str(str(xtb), config.EXTENDED_EXCEPTION)

    def test_syntax(self):
        self._check_tb_str(config.SYNTAX_TEST, config.SYNTAX_EXCEPTION)

    def test_format_variable_bad_repr(self):
        class AClass(object):
            def __repr__(self):
                raise Exception("repr fail")
        instance = AClass()
        xtb = self._factory(None, None, None)
        result = xtb._format_variable("a", instance)
        self.assertEqual(result, "    a = <unprintable AClass object>")

    def test_format_long_variable(self):
        xtb = self._factory(None, None, None)
        long_str = "a" * (2 * xtb.print_width + 1)
        formatted_str = xtb._format_variable("a", long_str)
        assert formatted_str.endswith("...'")
        assert len(formatted_str) == xtb.print_width

    def test_reformat_variable(self):
        xtb = self._factory(None, None, None)
        value = dict()
        for i in range(0, 10):
            value["a%s" % i] = i
        formatted_str = xtb._format_variable("a", value)
        assert formatted_str.startswith("    a = {")
        assert formatted_str.endswith("}")


text:
using System;

namespace GeneticSharp.Domain.Randomizations
{
    /// <summary>
    /// An IRandomization implementation using System.Random has pseudo-number generator.
    /// </summary>
    public class BasicRandomization : RandomizationBase
    {
        #region Fields
        private Random m_random = new Random(DateTime.Now.Millisecond);
        #endregion

        #region Methods
        /// <summary>
        /// Gets an integer value between minimum value (inclusive) and maximum value (exclusive).
        /// </summary>
        /// <returns>The integer.</returns>
        /// <param name="min">Minimum value (inclusive).</param>
        /// <param name="max">Maximum value (exclusive).</param>
        public override int GetInt(int min, int max)
        {
            return m_random.Next(min, max);
        }

        /// <summary>
        /// Gets a float value between 0.0 and 1.0.
        /// </summary>
        /// <returns>
        /// The float value.
        /// </returns>
        public override float GetFloat()
        {
            return (float)m_random.NextDouble();
        }

        /// <summary>
        /// Gets a double value between 0.0 and 1.0.
        /// </summary>
        /// <returns>The double value.</returns>
        public override double GetDouble()
        {
            return m_random.NextDouble();
        }
        #endregion
    }
}


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

<title>StringCodec (JADE v4.3.2 API)</title>
<meta name="date" content="2014-03-28">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

jade.content.lang

Class StringCodec

java.lang.Object

jade.content.lang.Codec

jade.content.lang.StringCodec

All Implemented Interfaces:

java.io.Serializable

Direct Known Subclasses:

SimpleSLCodec, SLCodec

public abstract class StringCodec
extends Codec

Base class for content language codecs that transform
 AbsContentElements to/from sequences of strings

Author:

Giovanni Caire - TILAB

See Also:

Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from class jade.content.lang.Codec

Codec.CodecException

Field Summary

Fields inherited from class jade.content.lang.Codec

UNNAMEDPREFIX

Constructor Summary

Constructors

Constructor and Description

StringCodec(java.lang.String name)

Construct a StringCodec object with the given name

Method Summary

Methods

Modifier and Type
Method and Description

abstract AbsContentElement
decode(Ontology ontology,
      java.lang.String content)

Decodes the content to an abstract description using a
 given ontology.

abstract AbsContentElement
decode(java.lang.String content)

Decodes the content to an abstract description.

abstract java.lang.String
encode(AbsContentElement content)

Encodes a content into a string.

abstract java.lang.String
encode(Ontology ontology,
      AbsContentElement content)

Encodes a content into a string using a given ontology.

Methods inherited from class jade.content.lang.Codec

getInnerOntology, getName

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StringCodec

public StringCodec(java.lang.String name)

Construct a StringCodec object with the given name

Method Detail

encode

public abstract java.lang.String encode(AbsContentElement content)
                                 throws Codec.CodecException

Encodes a content into a string.

Parameters:

content - the content as an abstract descriptor.

Returns:

the content as a string.

Throws:

CodecException

Codec.CodecException

encode

public abstract java.lang.String encode(Ontology ontology,
                      AbsContentElement content)
                                 throws Codec.CodecException

Encodes a content into a string using a given ontology.

Parameters:

ontology - the ontology

content - the content as an abstract descriptor.

Returns:

the content as a string.

Throws:

CodecException

Codec.CodecException

decode

public abstract AbsContentElement decode(java.lang.String content)
                                  throws Codec.CodecException

Decodes the content to an abstract description.

Parameters:

content - the content as a string.

Returns:

the content as an abstract description.

Throws:

CodecException

Codec.CodecException

decode

public abstract AbsContentElement decode(Ontology ontology,
                       java.lang.String content)
                                  throws Codec.CodecException

Decodes the content to an abstract description using a
 given ontology.

Parameters:

ontology - the ontology.

content - the content as a string.

Returns:

the content as an abstract description.

Throws:

CodecException

Codec.CodecException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

These are the official JADE API. For these API backward compatibility is guaranteed accross JADE versions


text:
// Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.objects.messages;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vk.api.sdk.objects.Validable;
import com.vk.api.sdk.objects.annotations.Required;
import com.vk.api.sdk.objects.base.BoolInt;
import com.vk.api.sdk.objects.base.Geo;
import java.util.List;
import java.util.Objects;

/**
 * Message object
 */
public class Message implements Validable {
    @SerializedName("action")
    private MessageAction action;

    /**
     * Only for messages from community. Contains user ID of community admin, who sent this message.
     */
    @SerializedName("admin_author_id")
    private Integer adminAuthorId;

    @SerializedName("attachments")
    private List<MessageAttachment> attachments;

    /**
     * Unique auto-incremented number for all messages with this peer
     */
    @SerializedName("conversation_message_id")
    private Integer conversationMessageId;

    /**
     * Date when the message has been sent in Unixtime
     */
    @SerializedName("date")
    @Required
    private Integer date;

    /**
     * Is it an deleted message
     */
    @SerializedName("deleted")
    private BoolInt deleted;

    /**
     * Message author's ID
     */
    @SerializedName("from_id")
    private Integer fromId;

    /**
     * Forwarded messages
     */
    @SerializedName("fwd_messages")
    private List<ForeignMessage> fwdMessages;

    @SerializedName("geo")
    private Geo geo;

    /**
     * Message ID
     */
    @SerializedName("id")
    @Required
    private Integer id;

    /**
     * Is it an important message
     */
    @SerializedName("important")
    private Boolean important;

    @SerializedName("is_hidden")
    private Boolean isHidden;

    /**
     * this message is cropped for bot
     */
    @SerializedName("is_cropped")
    private Boolean isCropped;

    @SerializedName("keyboard")
    private Keyboard keyboard;

    /**
     * Members number
     */
    @SerializedName("members_count")
    private Integer membersCount;

    /**
     * Information whether the message is outcoming
     */
    @SerializedName("out")
    @Required
    private BoolInt out;

    @SerializedName("payload")
    private String payload;

    /**
     * Peer ID
     */
    @SerializedName("peer_id")
    private Integer peerId;

    /**
     * ID used for sending messages. It returned only for outgoing messages
     */
    @SerializedName("random_id")
    private Integer randomId;

    @SerializedName("ref")
    private String ref;

    @SerializedName("ref_source")
    private String refSource;

    @SerializedName("reply_message")
    private ForeignMessage replyMessage;

    /**
     * Message text
     */
    @SerializedName("text")
    @Required
    private String text;

    /**
     * Date when the message has been updated in Unixtime
     */
    @SerializedName("update_time")
    private Integer updateTime;

    /**
     * Was the audio message inside already listened by you
     */
    @SerializedName("was_listened")
    private Boolean wasListened;

    /**
     * Date when the message has been pinned in Unixtime
     */
    @SerializedName("pinned_at")
    private Integer pinnedAt;

    /**
     * Is silent message, push without sound
     */
    @SerializedName("is_silent")
    private Boolean isSilent;

    public MessageAction getAction() {
        return action;
    }

    public Message setAction(MessageAction action) {
        this.action = action;
        return this;
    }

    public Integer getAdminAuthorId() {
        return adminAuthorId;
    }

    public Message setAdminAuthorId(Integer adminAuthorId) {
        this.adminAuthorId = adminAuthorId;
        return this;
    }

    public List<MessageAttachment> getAttachments() {
        return attachments;
    }

    public Message setAttachments(List<MessageAttachment> attachments) {
        this.attachments = attachments;
        return this;
    }

    public Integer getConversationMessageId() {
        return conversationMessageId;
    }

    public Message setConversationMessageId(Integer conversationMessageId) {
        this.conversationMessageId = conversationMessageId;
        return this;
    }

    public Integer getDate() {
        return date;
    }

    public Message setDate(Integer date) {
        this.date = date;
        return this;
    }

    public boolean isDeleted() {
        return deleted == BoolInt.YES;
    }

    public BoolInt getDeleted() {
        return deleted;
    }

    public Integer getFromId() {
        return fromId;
    }

    public Message setFromId(Integer fromId) {
        this.fromId = fromId;
        return this;
    }

    public List<ForeignMessage> getFwdMessages() {
        return fwdMessages;
    }

    public Message setFwdMessages(List<ForeignMessage> fwdMessages) {
        this.fwdMessages = fwdMessages;
        return this;
    }

    public Geo getGeo() {
        return geo;
    }

    public Message setGeo(Geo geo) {
        this.geo = geo;
        return this;
    }

    public Integer getId() {
        return id;
    }

    public Message setId(Integer id) {
        this.id = id;
        return this;
    }

    public Boolean getImportant() {
        return important;
    }

    public Message setImportant(Boolean important) {
        this.important = important;
        return this;
    }

    public Boolean getIsHidden() {
        return isHidden;
    }

    public Message setIsHidden(Boolean isHidden) {
        this.isHidden = isHidden;
        return this;
    }

    public Boolean getIsCropped() {
        return isCropped;
    }

    public Message setIsCropped(Boolean isCropped) {
        this.isCropped = isCropped;
        return this;
    }

    public Keyboard getKeyboard() {
        return keyboard;
    }

    public Message setKeyboard(Keyboard keyboard) {
        this.keyboard = keyboard;
        return this;
    }

    public Integer getMembersCount() {
        return membersCount;
    }

    public Message setMembersCount(Integer membersCount) {
        this.membersCount = membersCount;
        return this;
    }

    public boolean isOut() {
        return out == BoolInt.YES;
    }

    public BoolInt getOut() {
        return out;
    }

    public String getPayload() {
        return payload;
    }

    public Message setPayload(String payload) {
        this.payload = payload;
        return this;
    }

    public Integer getPeerId() {
        return peerId;
    }

    public Message setPeerId(Integer peerId) {
        this.peerId = peerId;
        return this;
    }

    public Integer getRandomId() {
        return randomId;
    }

    public Message setRandomId(Integer randomId) {
        this.randomId = randomId;
        return this;
    }

    public String getRef() {
        return ref;
    }

    public Message setRef(String ref) {
        this.ref = ref;
        return this;
    }

    public String getRefSource() {
        return refSource;
    }

    public Message setRefSource(String refSource) {
        this.refSource = refSource;
        return this;
    }

    public ForeignMessage getReplyMessage() {
        return replyMessage;
    }

    public Message setReplyMessage(ForeignMessage replyMessage) {
        this.replyMessage = replyMessage;
        return this;
    }

    public String getText() {
        return text;
    }

    public Message setText(String text) {
        this.text = text;
        return this;
    }

    public Integer getUpdateTime() {
        return updateTime;
    }

    public Message setUpdateTime(Integer updateTime) {
        this.updateTime = updateTime;
        return this;
    }

    public Boolean getWasListened() {
        return wasListened;
    }

    public Message setWasListened(Boolean wasListened) {
        this.wasListened = wasListened;
        return this;
    }

    public Integer getPinnedAt() {
        return pinnedAt;
    }

    public Message setPinnedAt(Integer pinnedAt) {
        this.pinnedAt = pinnedAt;
        return this;
    }

    public Boolean getIsSilent() {
        return isSilent;
    }

    public Message setIsSilent(Boolean isSilent) {
        this.isSilent = isSilent;
        return this;
    }

    @Override
    public int hashCode() {
        return Objects.hash(date, peerId, attachments, adminAuthorId, out, pinnedAt, refSource, geo, ref, fwdMessages, randomId, conversationMessageId, payload, replyMessage, wasListened, action, id, text, keyboard, membersCount, isCropped, updateTime, fromId, isHidden, important, deleted, isSilent);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Message message = (Message) o;
        return Objects.equals(date, message.date) &&
                Objects.equals(attachments, message.attachments) &&
                Objects.equals(fromId, message.fromId) &&
                Objects.equals(isHidden, message.isHidden) &&
                Objects.equals(out, message.out) &&
                Objects.equals(peerId, message.peerId) &&
                Objects.equals(geo, message.geo) &&
                Objects.equals(ref, message.ref) &&
                Objects.equals(updateTime, message.updateTime) &&
                Objects.equals(payload, message.payload) &&
                Objects.equals(pinnedAt, message.pinnedAt) &&
                Objects.equals(action, message.action) &&
                Objects.equals(id, message.id) &&
                Objects.equals(text, message.text) &&
                Objects.equals(keyboard, message.keyboard) &&
                Objects.equals(isCropped, message.isCropped) &&
                Objects.equals(wasListened, message.wasListened) &&
                Objects.equals(isSilent, message.isSilent) &&
                Objects.equals(refSource, message.refSource) &&
                Objects.equals(conversationMessageId, message.conversationMessageId) &&
                Objects.equals(important, message.important) &&
                Objects.equals(deleted, message.deleted) &&
                Objects.equals(adminAuthorId, message.adminAuthorId) &&
                Objects.equals(fwdMessages, message.fwdMessages) &&
                Objects.equals(membersCount, message.membersCount) &&
                Objects.equals(randomId, message.randomId) &&
                Objects.equals(replyMessage, message.replyMessage);
    }

    @Override
    public String toString() {
        final Gson gson = new Gson();
        return gson.toJson(this);
    }

    public String toPrettyString() {
        final StringBuilder sb = new StringBuilder("Message{");
        sb.append("date=").append(date);
        sb.append(", attachments=").append(attachments);
        sb.append(", fromId=").append(fromId);
        sb.append(", isHidden=").append(isHidden);
        sb.append(", out=").append(out);
        sb.append(", peerId=").append(peerId);
        sb.append(", geo=").append(geo);
        sb.append(", ref='").append(ref).append("'");
        sb.append(", updateTime=").append(updateTime);
        sb.append(", payload='").append(payload).append("'");
        sb.append(", pinnedAt=").append(pinnedAt);
        sb.append(", action=").append(action);
        sb.append(", id=").append(id);
        sb.append(", text='").append(text).append("'");
        sb.append(", keyboard=").append(keyboard);
        sb.append(", isCropped=").append(isCropped);
        sb.append(", wasListened=").append(wasListened);
        sb.append(", isSilent=").append(isSilent);
        sb.append(", refSource='").append(refSource).append("'");
        sb.append(", conversationMessageId=").append(conversationMessageId);
        sb.append(", important=").append(important);
        sb.append(", deleted=").append(deleted);
        sb.append(", adminAuthorId=").append(adminAuthorId);
        sb.append(", fwdMessages=").append(fwdMessages);
        sb.append(", membersCount=").append(membersCount);
        sb.append(", randomId=").append(randomId);
        sb.append(", replyMessage=").append(replyMessage);
        sb.append('}');
        return sb.toString();
    }
}


text:
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
	"text/template"
)

type skill struct {
	Name        string  `json:name`
	Cost        int     `json:cost`
	Description string  `json:decription`
	Passive     bool    `json:passive`
	Subskills   []skill `json:subskills`

	CodeName string
}

// We need a code name for each skill, for use as html id and JS variable.
// Generate these by lowercasing and replacing spaces with underscores.
// "My Cool Skill" -> "my_cool_skill"
func generateCodeNames(skills []skill) {
	for i := range skills {
		skills[i].CodeName = strings.Replace(strings.ToLower(skills[i].Name), " ", "_", -1)
		generateCodeNames(skills[i].Subskills)
	}
}

func main() {

	tmpl := template.Must(template.ParseFiles("skills.html.template"))

	file, err := os.Open("sword_skills.json")
	if err != nil {
		panic(err)
	}

	dec := json.NewDecoder(file)

	var skills []skill
	err = dec.Decode(&skills)
	if err != nil {
		panic(err)
	}

	generateCodeNames(skills)

	fmt.Println("<ul>")

	for i := range skills {
		err = tmpl.Execute(os.Stdout, skills[i])
		if err != nil {
			panic(err)
		}
	}

	fmt.Println("</ul>")
}


text:
package org.jboss.hal.testsuite.test.configuration.messaging.server.connections.connector.remote;

import java.io.IOException;

import org.jboss.arquillian.junit.Arquillian;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.testsuite.fragment.FormFragment;
import org.jboss.hal.testsuite.fragment.TableFragment;
import org.jboss.hal.testsuite.test.configuration.messaging.server.connections.AbstractServerConnectionsTest;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extras.creaper.core.online.operations.OperationException;
import org.wildfly.extras.creaper.core.online.operations.Values;

import static org.jboss.hal.dmr.ModelDescriptionConstants.GROUP;
import static org.jboss.hal.dmr.ModelDescriptionConstants.HTTP;
import static org.jboss.hal.dmr.ModelDescriptionConstants.HTTPS;
import static org.jboss.hal.dmr.ModelDescriptionConstants.NAME;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SERVER;
import static org.jboss.hal.dmr.ModelDescriptionConstants.SOCKET_BINDING;
import static org.jboss.hal.resources.Ids.ITEM;
import static org.jboss.hal.resources.Ids.MESSAGING_CONNECTOR;
import static org.jboss.hal.resources.Ids.MESSAGING_REMOTE_CONNECTOR;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.CONN_REM_CREATE;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.CONN_REM_DELETE;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.CONN_REM_UPDATE;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.SRV_UPDATE;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.connectorRemoteAddress;
import static org.jboss.hal.testsuite.fixtures.MessagingFixtures.serverAddress;

@RunWith(Arquillian.class)
public class RemoteConnectorTest extends AbstractServerConnectionsTest {

    @BeforeClass
    public static void createResources() throws IOException {
        createServer(SRV_UPDATE);
        operations.add(connectorRemoteAddress(SRV_UPDATE, CONN_REM_UPDATE), Values.of(SOCKET_BINDING, HTTP))
            .assertSuccess();
        operations.add(connectorRemoteAddress(SRV_UPDATE, CONN_REM_DELETE), Values.of(SOCKET_BINDING, HTTP))
            .assertSuccess();
    }

    @AfterClass
    public static void removeResources() throws IOException, OperationException {
        operations.removeIfExists(serverAddress(SRV_UPDATE));
    }

    @Before
    public void setUp() throws Exception {
        page.navigate(SERVER, SRV_UPDATE);
    }

    @Test
    public void connectorRemoteCreate() throws Exception {
        console.verticalNavigation()
            .selectSecondary(Ids.build(MESSAGING_CONNECTOR, GROUP, ITEM),
                Ids.build(MESSAGING_REMOTE_CONNECTOR, ITEM));
        TableFragment table = page.getConnectorRemoteTable();
        FormFragment form = page.getConnectorRemoteForm();
        table.bind(form);

        crudOperations.create(connectorRemoteAddress(SRV_UPDATE, CONN_REM_CREATE), table,
            formFragment -> {
                formFragment.text(NAME, CONN_REM_CREATE);
                formFragment.text(SOCKET_BINDING, HTTP);
            }
        );
    }

    @Test
    public void connectorRemoteTryCreate() {
        console.verticalNavigation()
            .selectSecondary(Ids.build(MESSAGING_CONNECTOR, GROUP, ITEM),
                Ids.build(MESSAGING_REMOTE_CONNECTOR, ITEM));
        TableFragment table = page.getConnectorRemoteTable();
        FormFragment form = page.getConnectorRemoteForm();
        table.bind(form);

        crudOperations.createWithErrorAndCancelDialog(table, CONN_REM_CREATE, SOCKET_BINDING);
    }

    @Test
    public void connectorRemoteUpdate() throws Exception {
        console.verticalNavigation()
            .selectSecondary(Ids.build(MESSAGING_CONNECTOR, GROUP, ITEM),
                Ids.build(MESSAGING_REMOTE_CONNECTOR, ITEM));
        TableFragment table = page.getConnectorRemoteTable();
        FormFragment form = page.getConnectorRemoteForm();
        table.bind(form);
        table.select(CONN_REM_UPDATE);
        crudOperations.update(connectorRemoteAddress(SRV_UPDATE, CONN_REM_UPDATE), form, SOCKET_BINDING, HTTPS);
    }

    @Test
    public void connectorRemoteTryUpdate() {
        console.verticalNavigation()
            .selectSecondary(Ids.build(MESSAGING_CONNECTOR, GROUP, ITEM),
                Ids.build(MESSAGING_REMOTE_CONNECTOR, ITEM));
        TableFragment table = page.getConnectorRemoteTable();
        FormFragment form = page.getConnectorRemoteForm();
        table.bind(form);
        table.select(CONN_REM_UPDATE);
        crudOperations.updateWithError(form, f -> f.clear(SOCKET_BINDING), SOCKET_BINDING);
    }

    @Test
    public void connectorRemoteRemove() throws Exception {
        console.verticalNavigation()
            .selectSecondary(Ids.build(MESSAGING_CONNECTOR, GROUP, ITEM),
                Ids.build(MESSAGING_REMOTE_CONNECTOR, ITEM));
        TableFragment table = page.getConnectorRemoteTable();
        FormFragment form = page.getConnectorRemoteForm();
        table.bind(form);

        crudOperations.delete(connectorRemoteAddress(SRV_UPDATE, CONN_REM_DELETE), table, CONN_REM_DELETE);
    }
}


text:
.summary_report_project h1 {
    text-align: center;
}

.summary_report_project {
    margin-right: 2em;
    margin-top: 5em;
}

.summary_report_field {
    margin-top: 1em;
}

.summary_report_field span:first-child {
    font-weight: bold;
    padding-right: 0.7em;
}

.summary_report_field span:first-child:after {
    content: ":";
}

.summary_report_table {
  border: 1px solid black;
  border-collapse: collapse;
}

.summary_report_table th {
    border: 1px solid black;
    padding: 0.6em;
}

.summary_report_table td {
    border: 1px solid black;
    padding: 0.6em;
}

.summary_report_sortable .headerSortDown {
    background-color: #333;
    color: #fff;
}

.summary_report_sortable .headerSortUp {
    background-color: #333;
    color: #fff;
}


text:
let password = 148302;

function modify_password(password){
    password = password*12;
    let i = 42
    password = password/(42/2)
    return password
}

function check_password() {
    let pass = modify_password(password);
    if (prompt("Entrez le mot de passe : ") == pass){
        window.open("https://bros-bioinfo.github.io/tutorats_2020/tutorats_webpages/latex/rapport/get_rapport.html");
    } else {
        alert("Erreur : mauvais mot de passe !");
    }
}


text:
COMPILER="gcc"
COMPILER_PP="g++"
CSMITH_PATH="/home/jacek/Desktop/Imperial/UROP/csmith/"
ADAPTER_OBJECT_PATH="/home/jacek/Desktop/Imperial/UROP/Adapter/boost_interval_adapter/adapter.o"
GEN_ERROR_FILE="genError.txt"
COMP_ERROR_FILE="compError.txt"
RUN_ERROR_FILE="runError.txt"
TIMEOUT_MACRO="timeout 60 "
TEMP_DIR="temp"
RESULTS_DIR="results"
GEN_ERROR_FILE="${RESULTS_DIR}/genError.txt"
COMP_ERROR_FILE="${RESULTS_DIR}/compError.txt"
RUN_ERROR_FILE="${RESULTS_DIR}/runError.txt"
RESULT_ERROR_FILE="${RESULTS_DIR}/resError.txt"
WIDE_COUNT_FILE="${RESULTS_DIR}/wideCount.txt"

makeProg(){
  ${TIMEOUT_MACRO} ${CSMITH_PATH}src/csmith --seed ${1} --strict-float --float-test --check-global > ${TEMP_DIR}/prog.c
  return $?
}

compileInFloatTestMode(){
  ${TIMEOUT_MACRO} ${COMPILER} ${TEMP_DIR}/prog.c -O0 -w -c -I${CSMITH_PATH}runtime -DUNSAFE_FLOAT -DFLOAT_TEST_ENABLED -o ${TEMP_DIR}/progFloatTestMode.o && \
  ${TIMEOUT_MACRO} g++ ${TEMP_DIR}/progFloatTestMode.o ${ADAPTER_OBJECT_PATH} -o ${TEMP_DIR}/progFloatTestMode
  return $?
}

runInFloatTestMode(){
  ${TIMEOUT_MACRO} ${TEMP_DIR}/progFloatTestMode > ${TEMP_DIR}/outFloatTestMode.txt
  return $?
}

compileInNormalMode(){
  ${TIMEOUT_MACRO} ${COMPILER} ${TEMP_DIR}/prog.c -O1 -w -c -I${CSMITH_PATH}runtime -DUNSAFE_FLOAT -o ${TEMP_DIR}/progNormalMode1.o && \
  ${TIMEOUT_MACRO} ${COMPILER_PP} ${TEMP_DIR}/progNormalMode1.o ${ADAPTER_OBJECT_PATH} -o ${TEMP_DIR}/progNormal1 && \
  ${TIMEOUT_MACRO} ${COMPILER} ${TEMP_DIR}/prog.c -O2 -w -c -I${CSMITH_PATH}runtime -DUNSAFE_FLOAT -o ${TEMP_DIR}/progNormalMode2.o && \
  ${TIMEOUT_MACRO} ${COMPILER_PP} ${TEMP_DIR}/progNormalMode2.o ${ADAPTER_OBJECT_PATH} -o ${TEMP_DIR}/progNormal2 && \
  ${TIMEOUT_MACRO} ${COMPILER} ${TEMP_DIR}/prog.c -O3 -w -c -I${CSMITH_PATH}runtime -DUNSAFE_FLOAT -o ${TEMP_DIR}/progNormalMode3.o && \
  ${TIMEOUT_MACRO} ${COMPILER_PP} ${TEMP_DIR}/progNormalMode3.o ${ADAPTER_OBJECT_PATH} -o ${TEMP_DIR}/progNormal3
  return $?
}

runInNormalMode(){
  ${TIMEOUT_MACRO} ${TEMP_DIR}/progNormal1 > ${TEMP_DIR}/outNormalMode1.txt && \
  ${TIMEOUT_MACRO} ${TEMP_DIR}/progNormal2 > ${TEMP_DIR}/outNormalMode2.txt && \
  ${TIMEOUT_MACRO} ${TEMP_DIR}/progNormal3 > ${TEMP_DIR}/outNormalMode3.txt
  return $?
}

validateResults(){
  python3 validate.py ${TEMP_DIR}/outNormalMode1.txt ${TEMP_DIR}/outFloatTestMode.txt >> "${WIDE_COUNT_FILE}" && \
  python3 validate.py ${TEMP_DIR}/outNormalMode2.txt ${TEMP_DIR}/outFloatTestMode.txt >> "${WIDE_COUNT_FILE}" && \
  python3 validate.py ${TEMP_DIR}/outNormalMode3.txt ${TEMP_DIR}/outFloatTestMode.txt >> "${WIDE_COUNT_FILE}"
  return $?
}

checkpoint(){
  if [ $1 -ne 0 ]; then
    echo "$2" >> "$3"
    return 1
  fi
  return 0
}

testSeed(){
  makeProg $1
  checkpoint $? $1 $GEN_ERROR_FILE || return 1
  compileInFloatTestMode
  checkpoint $? $1 $COMP_ERROR_FILE || return 1
  runInFloatTestMode
  checkpoint $? $1 $RUN_ERROR_FILE || return 1
  compileInNormalMode
  checkpoint $? $1 $COMP_ERROR_FILE || return 1
  runInNormalMode
  checkpoint $? $1 $RUN_ERROR_FILE || return 1
  validateResults
  checkpoint $? $1 $RESULT_ERROR_FILE || return 1
  return 0
}

mkdir -p $TEMP_DIR
mkdir -p $RESULTS_DIR
touch ${GEN_ERROR_FILE}
touch ${COMP_ERROR_FILE}
touch ${RUN_ERROR_FILE}
touch ${RESULT_ERROR_FILE}
touch ${WIDE_COUNT_FILE}

for seed in $(seq $1 $2); do
  echo "$seed"
  if testSeed $seed; then
    echo 'OK'
  else
    echo 'ERROR'
  fi
done


text:
.class public Lcom/umeng/analytics/MobclickAgentJSInterface;
.super Ljava/lang/Object;

# instance fields
.field private a:Landroid/content/Context;

# direct methods
.method public constructor <init>(Landroid/content/Context;Landroid/webkit/WebView;)V
    .locals 2

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

    iput-object p1, p0, Lcom/umeng/analytics/MobclickAgentJSInterface;->a:Landroid/content/Context;

    invoke-virtual {p2}, Landroid/webkit/WebView;->getSettings()Landroid/webkit/WebSettings;

    move-result-object v0

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/webkit/WebSettings;->setJavaScriptEnabled(Z)V

    new-instance v0, Lcom/umeng/analytics/k;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v1}, Lcom/umeng/analytics/k;-><init>(Lcom/umeng/analytics/MobclickAgentJSInterface;Landroid/webkit/WebChromeClient;)V

    invoke-virtual {p2, v0}, Landroid/webkit/WebView;->setWebChromeClient(Landroid/webkit/WebChromeClient;)V

    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/webkit/WebView;Landroid/webkit/WebChromeClient;)V
    .locals 2

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

    iput-object p1, p0, Lcom/umeng/analytics/MobclickAgentJSInterface;->a:Landroid/content/Context;

    invoke-virtual {p2}, Landroid/webkit/WebView;->getSettings()Landroid/webkit/WebSettings;

    move-result-object v0

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/webkit/WebSettings;->setJavaScriptEnabled(Z)V

    new-instance v0, Lcom/umeng/analytics/k;

    invoke-direct {v0, p0, p3}, Lcom/umeng/analytics/k;-><init>(Lcom/umeng/analytics/MobclickAgentJSInterface;Landroid/webkit/WebChromeClient;)V

    invoke-virtual {p2, v0}, Landroid/webkit/WebView;->setWebChromeClient(Landroid/webkit/WebChromeClient;)V

    return-void
.end method

.method static synthetic a(Lcom/umeng/analytics/MobclickAgentJSInterface;)Landroid/content/Context;
    .locals 1

    iget-object v0, p0, Lcom/umeng/analytics/MobclickAgentJSInterface;->a:Landroid/content/Context;

    return-object v0
.end method


text:
using System;
using System.Collections.Generic;
using System.Text;
using MO.Common.Lang;

namespace MO.Core.Window.Core {

   public class FThreadInfoCollection : FObjects<FThreadInfo> {
   }

}


text:
package org.springframework.boot.cli.command.options;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import joptsimple.OptionSet;

import org.springframework.boot.cli.util.ResourceUtils;
import org.springframework.util.Assert;

/**
 * Extract source file options (anything following '--' in an {@link OptionSet}).
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Greg Turnquist
 * @author Andy Wilkinson
 */
public class SourceOptions {

	private final List<String> sources;

	private final List<?> args;

	/**
	 * Create a new {@link SourceOptions} instance.
	 * @param options the source option set
	 */
	public SourceOptions(OptionSet options) {
		this(options, null);
	}

	/**
	 * Create a new {@link SourceOptions} instance.
	 * @param arguments the source arguments
	 */
	public SourceOptions(List<?> arguments) {
		this(arguments, null);
	}

	/**
	 * Create a new {@link SourceOptions} instance. If it is an error to pass options that
	 * specify non-existent sources, but the default paths are allowed not to exist (the
	 * paths are tested before use). If default paths are provided and the option set
	 * contains no source file arguments it is not an error even if none of the default
	 * paths exist).
	 * @param optionSet the source option set
	 * @param classLoader an optional classloader used to try and load files that are not
	 * found in the local filesystem
	 */
	public SourceOptions(OptionSet optionSet, ClassLoader classLoader) {
		this(optionSet.nonOptionArguments(), classLoader);
	}

	private SourceOptions(List<?> nonOptionArguments, ClassLoader classLoader) {
		List<String> sources = new ArrayList<>();
		int sourceArgCount = 0;
		for (Object option : nonOptionArguments) {
			if (option instanceof String) {
				String filename = (String) option;
				if ("--".equals(filename)) {
					break;
				}
				List<String> urls = new ArrayList<>();
				File fileCandidate = new File(filename);
				if (fileCandidate.isFile()) {
					urls.add(fileCandidate.getAbsoluteFile().toURI().toString());
				}
				else if (!isAbsoluteWindowsFile(fileCandidate)) {
					urls.addAll(ResourceUtils.getUrls(filename, classLoader));
				}
				for (String url : urls) {
					if (isSource(url)) {
						sources.add(url);
					}
				}
				if (isSource(filename)) {
					if (urls.isEmpty()) {
						throw new IllegalArgumentException("Can't find " + filename);
					}
					else {
						sourceArgCount++;
					}
				}
			}
		}
		this.args = Collections.unmodifiableList(
				nonOptionArguments.subList(sourceArgCount, nonOptionArguments.size()));
		Assert.isTrue(!sources.isEmpty(), "Please specify at least one file");
		this.sources = Collections.unmodifiableList(sources);
	}

	private boolean isAbsoluteWindowsFile(File file) {
		return isWindows() && file.isAbsolute();
	}

	private boolean isWindows() {
		return File.separatorChar == '\\';
	}

	private boolean isSource(String name) {
		return name.endsWith(".java") || name.endsWith(".groovy");
	}

	public List<?> getArgs() {
		return this.args;
	}

	public String[] getArgsArray() {
		return this.args.toArray(new String[this.args.size()]);
	}

	public List<String> getSources() {
		return this.sources;
	}

	public String[] getSourcesArray() {
		return this.sources.toArray(new String[this.sources.size()]);
	}

}


text:
package io.dropwizard.validation.valuehandling;

import com.google.common.base.Optional;
import org.hibernate.validator.HibernateValidator;
import org.junit.jupiter.api.Test;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.valueextraction.Unwrapping;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

public class GuavaOptionalValueExtractorTest {

    public static class Example {

        @Min(value = 3, payload = Unwrapping.Unwrap.class)
        Optional<Integer> three = Optional.absent();

        @NotNull(payload = Unwrapping.Unwrap.class)
        Optional<Integer> notNull = Optional.of(123);
    }

    private final Validator validator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .addValueExtractor(GuavaOptionalValueExtractor.DESCRIPTOR.getValueExtractor())
            .buildValidatorFactory()
            .getValidator();

    @Test
    public void succeedsWhenAbsent() {
        Example example = new Example();
        Set<ConstraintViolation<Example>> violations = validator.validate(example);
        assertThat(violations).isEmpty();
    }

    @Test
    public void failsWhenFailingConstraint() {
        Example example = new Example();
        example.three = Optional.of(2);
        Set<ConstraintViolation<Example>> violations = validator.validate(example);
        assertThat(violations).hasSize(1);
    }

    @Test
    public void succeedsWhenConstraintsMet() {
        Example example = new Example();
        example.three = Optional.of(10);
        Set<ConstraintViolation<Example>> violations = validator.validate(example);
        assertThat(violations).isEmpty();
    }

    @Test
    public void notNullFailsWhenAbsent() {
        Example example = new Example();
        example.notNull = Optional.absent();
        Set<ConstraintViolation<Example>> violations = validator.validate(example);
        assertThat(violations).hasSize(1);
    }
}


text:
package csvutil_test

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"strconv"
	"time"

	"github.com/jszwec/csvutil"
)

func ExampleEncoder_Encode_streaming() {
	type Address struct {
		City    string
		Country string
	}

	type User struct {
		Name string
		Address
		Age int `csv:"age,omitempty"`
	}

	users := []User{
		{Name: "John", Address: Address{"Boston", "USA"}, Age: 26},
		{Name: "Bob", Address: Address{"LA", "USA"}, Age: 27},
		{Name: "Alice", Address: Address{"SF", "USA"}},
	}

	var buf bytes.Buffer
	w := csv.NewWriter(&buf)
	enc := csvutil.NewEncoder(w)

	for _, u := range users {
		if err := enc.Encode(u); err != nil {
			fmt.Println("error:", err)
		}
	}

	w.Flush()
	if err := w.Error(); err != nil {
		fmt.Println("error:", err)
	}

	fmt.Println(buf.String())

	// Output:
	// Name,City,Country,age
	// John,Boston,USA,26
	// Bob,LA,USA,27
	// Alice,SF,USA,
}

func ExampleEncoder_Encode_all() {
	type Address struct {
		City    string
		Country string
	}

	type User struct {
		Name string
		Address
		Age int `csv:"age,omitempty"`
	}

	users := []User{
		{Name: "John", Address: Address{"Boston", "USA"}, Age: 26},
		{Name: "Bob", Address: Address{"LA", "USA"}, Age: 27},
		{Name: "Alice", Address: Address{"SF", "USA"}},
	}

	var buf bytes.Buffer
	w := csv.NewWriter(&buf)
	if err := csvutil.NewEncoder(w).Encode(users); err != nil {
		fmt.Println("error:", err)
	}

	w.Flush()
	if err := w.Error(); err != nil {
		fmt.Println("error:", err)
	}

	fmt.Println(buf.String())

	// Output:
	// Name,City,Country,age
	// John,Boston,USA,26
	// Bob,LA,USA,27
	// Alice,SF,USA,
}

func ExampleEncoder_EncodeHeader() {
	type User struct {
		Name string
		Age  int `csv:"age,omitempty"`
	}

	var buf bytes.Buffer
	w := csv.NewWriter(&buf)
	enc := csvutil.NewEncoder(w)

	if err := enc.EncodeHeader(User{}); err != nil {
		fmt.Println("error:", err)
	}

	w.Flush()
	if err := w.Error(); err != nil {
		fmt.Println("error:", err)
	}

	fmt.Println(buf.String())

	// Output:
	// Name,age
}

func ExampleEncoder_Encode_inline() {
	type Address struct {
		Street string `csv:"street"`
		City   string `csv:"city"`
	}

	type User struct {
		Name        string  `csv:"name"`
		Address     Address `csv:",inline"`
		HomeAddress Address `csv:"home_address_,inline"`
		WorkAddress Address `csv:"work_address_,inline"`
		Age         int     `csv:"age,omitempty"`
	}

	users := []User{
		{
			Name:        "John",
			Address:     Address{"Washington", "Boston"},
			HomeAddress: Address{"Boylston", "Boston"},
			WorkAddress: Address{"River St", "Cambridge"},
			Age:         26,
		},
	}

	b, err := csvutil.Marshal(users)
	if err != nil {
		fmt.Println("error:", err)
	}

	fmt.Printf("%s\n", b)

	// Output:
	// name,street,city,home_address_street,home_address_city,work_address_street,work_address_city,age
	// John,Washington,Boston,Boylston,Boston,River St,Cambridge,26
}

func ExampleEncoder_Register() {
	type Foo struct {
		Time   time.Time     `csv:"time"`
		Hex    int           `csv:"hex"`
		PtrHex *int          `csv:"ptr_hex"`
		Buffer *bytes.Buffer `csv:"buffer"`
	}

	foos := []Foo{
		{
			Time:   time.Date(2020, 6, 20, 12, 0, 0, 0, time.UTC),
			Hex:    15,
			Buffer: bytes.NewBufferString("hello"),
		},
	}

	marshalInt := func(n *int) ([]byte, error) {
		if n == nil {
			return []byte("NULL"), nil
		}
		return strconv.AppendInt(nil, int64(*n), 16), nil
	}

	marshalTime := func(t time.Time) ([]byte, error) {
		return t.AppendFormat(nil, time.Kitchen), nil
	}

	// all fields which implement String method will use this, unless their
	// concrete type was already overriden.
	marshalStringer := func(s fmt.Stringer) ([]byte, error) {
		return []byte(s.String()), nil
	}

	var buf bytes.Buffer
	w := csv.NewWriter(&buf)
	enc := csvutil.NewEncoder(w)

	enc.Register(marshalInt)
	enc.Register(marshalTime)
	enc.Register(marshalStringer)

	if err := enc.Encode(foos); err != nil {
		fmt.Println("error:", err)
	}

	w.Flush()
	if err := w.Error(); err != nil {
		fmt.Println("error:", err)
	}

	fmt.Println(buf.String())

	// Output:
	// time,hex,ptr_hex,buffer
	// 12:00PM,f,NULL,hello
}


text:
/*-------------------------------------------------------
 * This file was generated by XpeCodeGen
 * Version 1.0.0
 *
 * Do not make changes to this file
 *-------------------------------------------------------*/
package com.badlogic.gdx.physics.bullet;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.bullet.linearmath.btIDebugDraw;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.viewport.Viewport;

/** @author xoppa */
public class DebugDrawer extends btIDebugDraw implements Disposable {

    private ShapeRenderer shapeRenderer = new ShapeRenderer();

    private SpriteBatch spriteBatch;

    private BitmapFont font;

    private boolean ownsShapeRenderer = true, ownsSpriteBatch = true, ownsFont = true;

    private Camera camera;

    private Viewport viewport;

    private int debugMode = btIDebugDraw.DebugDrawModes.DBG_NoDebug;

    @Override
    public void drawLine(Vector3 from, Vector3 to, Vector3 color) {
        shapeRenderer.setColor(color.x, color.y, color.z, 1f);
        shapeRenderer.line(from, to);
    }

    @Override
    public void drawContactPoint(Vector3 pointOnB, Vector3 normalOnB, float distance, int lifeTime, Vector3 color) {
        shapeRenderer.setColor(color.x, color.y, color.z, 1f);
        float size = 0.04f;
        shapeRenderer.box(pointOnB.x - size / 2f, pointOnB.y - size / 2f, pointOnB.z + size / 2f, size, size, size);
        shapeRenderer.setColor(1, 0, 0, 1f);
        shapeRenderer.line(pointOnB, normalOnB.scl(distance + 0.2f).add(pointOnB));
    }

    @Override
    public void reportErrorWarning(String warningString) {
        Gdx.app.error("Bullet", warningString);
    }

    @Override
    public void draw3dText(Vector3 location, String textString) {
        if (spriteBatch == null) {
            spriteBatch = new SpriteBatch();
        }
        if (font == null) {
            font = new BitmapFont();
        }
        // this check is necessary to avoid "mirrored" instances of the text
        if (camera.frustum.pointInFrustum(location)) {
            if (viewport != null) {
                camera.project(location, viewport.getScreenX(), viewport.getScreenY(), viewport.getScreenWidth(), viewport.getScreenHeight());
            } else {
                camera.project(location);
            }
            shapeRenderer.end();
            spriteBatch.begin();
            // the text will be centered on the position
            font.draw(spriteBatch, textString, location.x, location.y, 0, textString.length(), 0, Align.center, false);
            spriteBatch.end();
            shapeRenderer.begin(ShapeType.Line);
        }
    }

    @Override
    public void setDebugMode(int debugMode) {
		checkPointer();
		this.debugMode = debugMode;
    }

    @Override
    public int getDebugMode() {
        return debugMode;
    }

    /** Use this in case no {@code glViewport} is in use. Otherwise please supply the used {@link Viewport} to
	 * {@link #begin(Viewport)}.
	 * @param camera The (perspective) camera to be used when doing the debug rendering. */
    public void begin(Camera camera) {
        this.camera = camera;
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeType.Line);
    }

    /** This has to be used in case the camera to be used is managed via a {@link Viewport}.
	 * @param viewport The currently used viewport with its managed (perspective) camera. */
    public void begin(Viewport viewport) {
        this.viewport = viewport;
        begin(viewport.getCamera());
    }

    /** Ends the debug rendering process and leads to a flush. */
    public void end() {
        shapeRenderer.end();
    }

    public ShapeRenderer getShapeRenderer() {
        return shapeRenderer;
    }

    /** Switches the {@link ShapeRenderer}. The given shape renderer won't be disposed when {@link #dispose()} is called. */
    public void setShapeRenderer(ShapeRenderer shapeRenderer) {
        if (ownsShapeRenderer) {
            this.shapeRenderer.dispose();
        }
        this.shapeRenderer = shapeRenderer;
        ownsShapeRenderer = false;
    }

    public SpriteBatch getSpriteBatch() {
        return spriteBatch;
    }

    /** Switches the {@link SpriteBatch}. The given sprite batch won't be disposed when {@link #dispose()} is called. */
    public void setSpriteBatch(SpriteBatch spriteBatch) {
        if (ownsSpriteBatch && this.spriteBatch != null) {
            this.spriteBatch.dispose();
        }
        this.spriteBatch = spriteBatch;
        ownsSpriteBatch = false;
    }

    public BitmapFont getFont() {
        return font;
    }

    /** Switches the {@link BitmapFont}. The given font won't be disposed when {@link #dispose()} is called. */
    public void setFont(BitmapFont font) {
        if (ownsFont && this.font != null) {
            this.font.dispose();
        }
        this.font = font;
        ownsFont = false;
    }

    @Override
    protected void delete() {
        super.delete();
        if (ownsShapeRenderer) {
            shapeRenderer.dispose();
        }
        if (ownsSpriteBatch && spriteBatch != null) {
            spriteBatch.dispose();
        }
        if (ownsFont && font != null) {
            font.dispose();
        }
    }
}