text:
module FbGraph
  module Connections
    module Snippets
      def snippets(options = {})
        snippets = self.connection :snippets, options
        snippets.map! do |snippet|
          Snippet.new nil, snippet.merge(
            :access_token => options[:access_token] || self.access_token
          )
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
/*istanbul ignore next*/"use strict";

exports.__esModule = true;

exports.default = function (node) {
  var params = node.params;
  for (var i = 0; i < params.length; i++) {
    var param = params[i];
    if (t.isAssignmentPattern(param) || t.isRestElement(param)) {
      return i;
    }
  }
  return params.length;
};

var /*istanbul ignore next*/_babelTypes = require("babel-types");

/*istanbul ignore next*/
var t = _interopRequireWildcard(_babelTypes);

/*istanbul ignore next*/
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

module.exports = exports["default"];


text:
Collections
===========

Collections allow you to group config files and query them similar to how you would use a database. To create a collection we first need an instance of the `Collection` class.

	use Danzabar\Config\Collections\Collection;

	$collection = new Collection;

Using this instance we can now "query" for files using the methods provided:

	// Set the search directory
	$collection->setDirectory('/directory');

	// Fetch all files from the search directory
	$collection->all();

	// Fetch files from a specific directory within the search directory
	$collection->whereIn('/test')->fetch();

	// Exclude a directory from the search
	$collection->excludeDir('/test')->all();

	// Exclude a file name
	$collection->exclude('testfile')->fetch();

	// Specify a custom filter callback
	$collection->filter( function (\SplFileInfo $file) {

		return $file->getExtension() == 'json';
	});

The collection class uses the Symfony Finder component, so you can use methods provided from that by fetching the finder from the collection instance:

	$collection->finder();

It will always filter the files in directories to make sure they match the file extensions registered with the `ExtensionMap`.

The collection class will return results via the `CollectionResults` class, this class implements `Iterator`, `Countable`, `ArrayAccess` interfaces, which allows a collection result to be accessed in various ways.

	$results = $collection->fetch();

	count($results);

	$results[1];

	foreach ($results as $result)
	{
		echo $result->params()->test;
	}


text:
package com.pineone.icbms.so.virtualobject.proxy;

public interface VirtualObjectControlProxy {
    //
    String executeDevice(String deviceId, String deviceCommand, String sessionId);
}


text:
"""
@file copy_make_border.py
@brief Sample code that shows the functionality of copyMakeBorder
"""
import sys
from random import randint
import cv2

def main(argv):
    ## [variables]
    # First we declare the variables we are going to use
    borderType = cv2.BORDER_CONSTANT
    window_name = "copyMakeBorder Demo"
    ## [variables]
    ## [load]
    imageName = argv[0] if len(argv) > 0 else "../data/lena.jpg"

    # Loads an image
    src = cv2.imread(imageName, cv2.IMREAD_COLOR)

    # Check if image is loaded fine
    if src is None:
        print ('Error opening image!')
        print ('Usage: copy_make_border.py [image_name -- default ../data/lena.jpg] \n')
        return -1
    ## [load]
    # Brief how-to for this program
    print ('\n'
           '\t 	 copyMakeBorder Demo: \n'
           '	 -------------------- \n'
           ' ** Press \'c\' to set the border to a random constant value \n'
           ' ** Press \'r\' to set the border to be replicated \n'
           ' ** Press \'ESC\' to exit the program ')
    ## [create_window]
    cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)
    ## [create_window]
    ## [init_arguments]
    # Initialize arguments for the filter
    top = int(0.05 * src.shape[0])  # shape[0] = rows
    bottom = top
    left = int(0.05 * src.shape[1])  # shape[1] = cols
    right = left
    ## [init_arguments]
    while 1:
        ## [update_value]
        value = [randint(0, 255), randint(0, 255), randint(0, 255)]
        ## [update_value]
        ## [copymakeborder]
        dst = cv2.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
        ## [copymakeborder]
        ## [display]
        cv2.imshow(window_name, dst)
        ## [display]
        ## [check_keypress]
        c = cv2.waitKey(500)

        if c == 27:
            break
        elif c == 99: # 99 = ord('c')
            borderType = cv2.BORDER_CONSTANT
        elif c == 114: # 114 = ord('r')
            borderType = cv2.BORDER_REPLICATE
        ## [check_keypress]
    return 0

if __name__ == "__main__":
    main(sys.argv[1:])


text:
package org.apache.activemq.artemis.core.server;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.journal.EncodingSupport;
import org.apache.activemq.artemis.core.message.impl.MessageInternal;
import org.apache.activemq.artemis.core.paging.PagingStore;

/**
 *
 * A ServerMessage
 */
public interface ServerMessage extends MessageInternal, EncodingSupport
{
   ServerMessage setMessageID(long id);

   MessageReference createReference(Queue queue);

   /**
    * This will force encoding of the address, and will re-check the buffer
    * This is to avoid setMessageTransient which set the address without changing the buffer
    * @param address
    */
   void forceAddress(SimpleString address);

   int incrementRefCount() throws Exception;

   int decrementRefCount() throws Exception;

   int incrementDurableRefCount();

   int decrementDurableRefCount();

   ServerMessage copy(long newID);

   void finishCopy() throws Exception;

   ServerMessage copy();

   int getMemoryEstimate();

   int getRefCount();

   ServerMessage makeCopyForExpiryOrDLA(long newID, MessageReference originalReference, boolean expiry, boolean copyOriginalHeaders) throws Exception;

   void setOriginalHeaders(ServerMessage other, MessageReference originalReference, boolean expiry);

   void setPagingStore(PagingStore store);

   PagingStore getPagingStore();

   // Is there any _AMQ_ property being used
   boolean hasInternalProperties();

   boolean storeIsPaging();

   void encodeMessageIDToBuffer();

   byte [] getDuplicateIDBytes();

   Object getDuplicateProperty();
}


text:
/***************************************************************************//**
 * \file ISC_process_subsample.h
 * \brief Subsampling module.
 *
 * ISC_process_subsample.h contains the data structures and function prototypes
 * necessary for performing fast mean-based and random-based image downsampling
 * on the CMUcam3, as the cc3 API has not finished this functionality yet as
 * of this writing.
*******************************************************************************/

#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

#include "ISC_util_rowqueue.h"
#include "ISC_util_imagecontext.h"

/**
 * \brief Process-Module for Image Subsampling.
 *
 * ISC_process_subsample is a module designed for performing fast image
 * subsampling with mean-based and randon-pixel-based approaches.  Once the
 * cc3 API provides native support for these, this module will become
 * redundant.
 */
typedef struct
{
	//---------------------------USER-DEFINED-------------------------------
	ISC_util_imagecontext theContext; /*!< The Image Context. */
	uint8_t skipFactorX; //!< The horizontal skip factor of the subsample.
       	uint8_t skipFactorY; //!< The vertical skip factor of the subsample.
	cc3_subsample_mode_t subType; //!< The type of subsampling to do.
	//---------------------------SYSTEM-HANDLED-----------------------------
	uint8_t skipShiftFactorX; //!< Right-shifts needed to perform subsample.
	uint8_t skipShiftFactorY; //!< Left-shifts needed to perform subsample.
	uint16_t endWidth; //!< The width after subsampling.
	uint16_t endHeight; //!< The height after subsampling.
	uint16_t linesLeft; //!< The amount of lines left to subsample.

	ISC_util_rowqueue *rq; //!< The rowqueue for storing rows.

	//----------------------ISC_PIPELINE REQUIREMENT------------------------
	bool finished; //!< Is the module finished?
} ISC_process_subsample;

ISC_process_subsample *ISC_process_subsample_start( ISC_util_imagecontext, uint8_t, uint8_t, cc3_subsample_mode_t );
void ISC_process_subsample_feed( ISC_process_subsample *, uint8_t * );
uint8_t *ISC_process_subsample_process( ISC_process_subsample * );
ISC_util_imagecontext ISC_process_subsample_context( ISC_process_subsample * );
void ISC_process_subsample_end( ISC_process_subsample * );
bool ISC_process_subsample_running( ISC_process_subsample * );


text:
<!-- HTML Document -->

<bbn-table class="appui-ide-popup-directories-manager"
           :source="repositoriesArray"
           :tr-style="trStyle">
  <bbns-column field="title"
               title="Nom"
               cls="bbn-b"/>
  <bbns-column field="name"
               title="Root"/>
  <bbns-column field="alias_code"
               title="Type"/>
  <bbns-column field="bcolor"
               title="Color"/>
  <bbns-column field="path"
               title="Path"/>
</bbn-table>


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Posting source code on WordPress.com | Lee Kelleher - Umbraco Consultant</title>
	<meta name="description" content="I feel like a complete n00b … I’ve only just found out how to mark-up source-code snippets on WordPress.com It’s in their FAQs: How do I post source code? Essentially you use the short-code: [sourcecode language='css']...[/sourcecode] Here’s an example: // A "Hello World!" program in C# class Hello { static void Main() { System.Console.WriteLine("Hello World!"); } } I knew about WP.org plugins that did this, but I’ve been scratching my head on how do this&#8230;">
	<meta name="keywords" content="code,wordpress,wordpress.com">
	<meta name="generator" content="Wyam">
	<meta name="twitter:card" content="summary">
	<meta name="twitter:site" content="@leekelleher">
	<meta name="twitter:url" property="og:url" content="https://leekelleher.com/2008/04/23/posting-source-code-on-wordpresscom/">
	<meta name="twitter:title" property="og:title" content="Posting source code on WordPress.com">
	<meta name="twitter:description" property="og:description" content="I feel like a complete n00b … I’ve only just found out how to mark-up source-code snippets on WordPress.com It’s in their FAQs: How do I post source code? Essentially you use the short-code: [sourcecode language='css']...[/sourcecode] Here’s an example: // A "Hello World!" program in C# class Hello { static void Main() { System.Console.WriteLine("Hello World!"); } } I knew about WP.org plugins that did this, but I’ve been scratching my head on how do this&#8230;">
	<meta name="twitter:image" property="og:image" content="https://leekelleher.com/assets/img/nxnw_300x300.jpg">
	<link rel="alternate" href="https://leekelleher.com/feed/" type="application/rss+xml">
	<link rel="canonical" href="https://leekelleher.com/2008/04/23/posting-source-code-on-wordpresscom/">
	<link rel="pingback" href="https://webmention.io/leekelleher.com/xmlrpc">
	<link rel="webmention" href="https://webmention.io/leekelleher.com/webmention">
	<link rel="stylesheet" href="/assets/css/style.css">

Lee Kelleher

About

Now

Contact

Posting source code on WordPress.com

				Posted on <time datetime="2008-04-23T10:55+01:00" class="dt-published">23/04/2008</time>.
				Estimated read time: under a minute (82 words)

I feel like a complete n00b … I've only just found out how to mark-up source-code snippets on WordPress.com

It's in their FAQs: How do I post source code?

Essentially you use the short-code: [sourcecode language='css']...[/sourcecode]

Here's an example:

// A "Hello World!" program in C#
class Hello
{
   static void Main()
   {
      System.Console.WriteLine("Hello World!");
   }
}

I knew about WP.org plugins that did this, but I've been scratching my head on how do this on WP.com for ages now!

Tags: code, WordPress, WordPress.com

Permalink: https://leekelleher.com/2008/04/23/posting-source-code-on-wordpresscom/

For any feedback, comments or questions, feel free to ask me via my contact page, on Twitter, or on GitHub.

Be notified of new posts, subscribe to my RSS feed.

All content by Lee Kelleher (© 2006-2021) and licensed under Creative Commons. All code snippets are licensed under the MIT license.

This website is statically generated using Wyam. All code and content for this blog is available as open source on GitHub.


text:
namespace blink {

// Error object when a bluetooth request can not be satisfied used to create
// DOMExceptions.
struct WebBluetoothError {
    enum ErrorType {
        NotFoundError,
        SecurityError
    };

    WebBluetoothError(ErrorType errorType, const WebString& message)
        : errorType(errorType)
        , message(message)
    {
    }

    ErrorType errorType;
    WebString message;
};

} // namespace blink

#endif // WebBluetoothError_h


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using TerraFX.Collections;

namespace TerraFX.UnitTests.Collections;

/// Provides a set of tests covering the <see cref="ValueList{T}" /> struct.
public static class ValueListTests
{
    /// Provides validation of the <see cref="ValueList{T}.ValueList()" /> constructor.
    [Test]
    public static void CtorTest()
    {
        Assert.That(() => new ValueList<int>(),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.ValueList(int)" /> constructor.
    [Test]
    public static void CtorInt32Test()
    {
        Assert.That(() => new ValueList<int>(5),
            Has.Property("Capacity").EqualTo(5)
               .And.Count.EqualTo(0)
        );

        Assert.That(() => new ValueList<int>(-5),
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(-5)
                  .And.Property("ParamName").EqualTo("capacity")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.ValueList(IEnumerable{T})" /> constructor.
    [Test]
    public static void CtorIEnumerableTest()
    {
        Assert.That(() => new ValueList<int>(Enumerable.Range(0, 3)),
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        Assert.That(() => new ValueList<int>(Enumerable.Empty<int>()),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );

        Assert.That(() => new ValueList<int>((null as IEnumerable<int>)!),
            Throws.ArgumentNullException
                  .And.Property("ParamName").EqualTo("source")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.ValueList(ReadOnlySpan{T})" /> constructor.
    [Test]
    public static void CtorReadOnlySpanTest()
    {
        Assert.That(() => new ValueList<int>(new int[] { 1, 2, 3 }.AsSpan()),
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        Assert.That(() => new ValueList<int>(Array.Empty<int>().AsSpan()),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );

        Assert.That(() => new ValueList<int>((null as int[]).AsSpan()),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.ValueList(T[], bool)" /> constructor.
    [Test]
    public static void CtorArrayBooleanTest()
    {
        Assert.That(() => new ValueList<int>(new int[] { 1, 2, 3 }, takeOwnership: false),
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        Assert.That(() => new ValueList<int>(new int[] { 1, 2, 3 }, takeOwnership: true),
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        Assert.That(() => new ValueList<int>(Array.Empty<int>(), takeOwnership: false),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );

        Assert.That(() => new ValueList<int>(Array.Empty<int>(), takeOwnership: true),
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );

        Assert.That(() => new ValueList<int>(null!, takeOwnership: false),
            Throws.ArgumentNullException
                  .And.Property("ParamName").EqualTo("array")
        );

        Assert.That(() => new ValueList<int>(null!, takeOwnership: true),
            Throws.ArgumentNullException
                  .And.Property("ParamName").EqualTo("array")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}" /> indexer.
    [Test]
    public static void GetItemTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        Assert.That(() => valueList[1],
            Is.EqualTo(2)
        );

        Assert.That(() => valueList[-1],
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(-1)
                  .And.Property("ParamName").EqualTo("index")
        );

        Assert.That(() => valueList[3],
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(3)
                  .And.Property("ParamName").EqualTo("index")
        );

        Assert.That(() => new ValueList<int>()[0],
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(0)
                  .And.Property("ParamName").EqualTo("index")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}" /> indexer.
    [Test]
    public static void SetItemTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        Assert.That(() => valueList[1] = 4,
            Is.EqualTo(4)
        );

        Assert.That(() => valueList[-1] = 4,
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(-1)
                  .And.Property("ParamName").EqualTo("index")
        );

        Assert.That(() => valueList[3] = 4,
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(3)
                  .And.Property("ParamName").EqualTo("index")
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList[0] = 4,
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(0)
                  .And.Property("ParamName").EqualTo("index")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.Add(T)" /> method.
    [Test]
    public static void AddTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 }) {
            4
        };

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(6)
               .And.Count.EqualTo(4)
        );

        Assert.That(() => valueList[3],
            Is.EqualTo(4)
        );

        valueList.Add(5);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(6)
               .And.Count.EqualTo(5)
        );

        Assert.That(() => valueList[4],
            Is.EqualTo(5)
        );

        valueList = new ValueList<int> {
            6
        };

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(1)
               .And.Count.EqualTo(1)
        );

        Assert.That(() => valueList[0],
            Is.EqualTo(6)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.Clear" /> method.
    [Test]
    public static void ClearTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });
        valueList.Clear();

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(0)
        );

        valueList = new ValueList<int>();
        valueList.Clear();

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.Contains(T)" /> method.
    [Test]
    public static void ContainsTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        Assert.That(() => valueList.Contains(1),
            Is.True
        );

        Assert.That(() => valueList.Contains(4),
            Is.False
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList.Contains(0),
            Is.False
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.CopyTo(Span{T})" /> method.
    [Test]
    public static void CopyToTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        var destination = new int[3];
        valueList.CopyTo(destination);

        Assert.That(() => destination,
            Is.EquivalentTo(new int[] { 1, 2, 3 })
        );

        destination = new int[6];
        valueList.CopyTo(destination);

        Assert.That(() => destination,
            Is.EquivalentTo(new int[] { 1, 2, 3, 0, 0, 0 })
        );

        Assert.That(() => valueList.CopyTo(Array.Empty<int>()),
            Throws.ArgumentException
                  .And.Property("ParamName").EqualTo("destination")
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList.CopyTo(Array.Empty<int>()),
            Throws.Nothing
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.EnsureCapacity(int)" /> method.
    [Test]
    public static void EnsureCapacityTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });
        valueList.EnsureCapacity(-1);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        valueList.EnsureCapacity(0);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        valueList.EnsureCapacity(3);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        valueList.EnsureCapacity(4);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(6)
               .And.Count.EqualTo(3)
        );

        valueList.EnsureCapacity(16);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(16)
               .And.Count.EqualTo(3)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.IndexOf(T)" /> method.
    [Test]
    public static void IndexOfTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        Assert.That(() => valueList.IndexOf(1),
            Is.EqualTo(0)
        );

        Assert.That(() => valueList.IndexOf(4),
            Is.EqualTo(-1)
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList.IndexOf(0),
            Is.EqualTo(-1)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.Insert(int, T)" /> method.
    [Test]
    public static void InsertTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });
        valueList.Insert(3, 4);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(6)
               .And.Count.EqualTo(4)
        );

        Assert.That(() => valueList[3],
            Is.EqualTo(4)
        );

        Assert.That(() => valueList.Insert(5, 5),
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(5)
                  .And.Property("ParamName").EqualTo("index")
        );

        valueList = new ValueList<int>();
        valueList.Insert(0, 1);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(1)
               .And.Count.EqualTo(1)
        );

        Assert.That(() => valueList[0],
            Is.EqualTo(1)
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.Remove(T)" /> method.
    [Test]
    public static void RemoveTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });

        Assert.That(() => valueList.Remove(1),
            Is.True
        );

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(2)
        );

        Assert.That(() => valueList[0],
            Is.EqualTo(2)
        );

        Assert.That(() => valueList[1],
            Is.EqualTo(3)
        );

        Assert.That(() => valueList.Remove(0),
            Is.False
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList.Remove(0),
            Is.False
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.RemoveAt(int)" /> method.
    [Test]
    public static void RemoveAtTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });
        valueList.RemoveAt(0);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(2)
        );

        Assert.That(() => valueList[0],
            Is.EqualTo(2)
        );

        Assert.That(() => valueList[1],
            Is.EqualTo(3)
        );

        Assert.That(() => valueList.RemoveAt(-1),
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(-1)
                  .And.Property("ParamName").EqualTo("index")
        );

        Assert.That(() => valueList.RemoveAt(2),
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(2)
                  .And.Property("ParamName").EqualTo("index")
        );

        valueList = new ValueList<int>();

        Assert.That(() => valueList.RemoveAt(0),
            Throws.InstanceOf<ArgumentOutOfRangeException>()
                  .And.Property("ActualValue").EqualTo(0)
                  .And.Property("ParamName").EqualTo("index")
        );
    }

    /// Provides validation of the <see cref="ValueList{T}.TrimExcess(float)" /> method.
    [Test]
    public static void TrimExcessTest()
    {
        var valueList = new ValueList<int>(new int[] { 1, 2, 3 });
        valueList.TrimExcess();

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(3)
               .And.Count.EqualTo(3)
        );

        valueList.Add(4);
        valueList.Add(5);

        valueList.TrimExcess();

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(5)
               .And.Count.EqualTo(5)
        );

        valueList.EnsureCapacity(15);
        valueList.TrimExcess(0.3f);

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(15)
               .And.Count.EqualTo(5)
        );

        valueList = new ValueList<int>();
        valueList.TrimExcess();

        Assert.That(() => valueList,
            Has.Property("Capacity").EqualTo(0)
               .And.Count.EqualTo(0)
        );
    }
}


text:
package org.ehcache.xml.service;

import org.ehcache.config.CacheConfiguration;
import org.ehcache.impl.config.event.DefaultCacheEventDispatcherConfiguration;
import org.ehcache.xml.XmlConfiguration;
import org.ehcache.xml.model.CacheType;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder;
import static org.ehcache.config.builders.ResourcePoolsBuilder.heap;
import static org.ehcache.core.spi.service.ServiceUtils.findSingletonAmongst;

public class DefaultCacheEventDispatcherConfigurationParserTest {

  @Test
  public void parseServiceConfiguration() throws Exception {
    CacheConfiguration<?, ?> cacheConfiguration = new XmlConfiguration(getClass().getResource("/configs/ehcache-cacheEventListener.xml")).getCacheConfigurations().get("template1");

    DefaultCacheEventDispatcherConfiguration eventDispatcherConfig =
      findSingletonAmongst(DefaultCacheEventDispatcherConfiguration.class, cacheConfiguration.getServiceConfigurations());

    assertThat(eventDispatcherConfig).isNotNull();
    assertThat(eventDispatcherConfig.getThreadPoolAlias()).isEqualTo("listeners-pool");
  }

  @Test
  public void unparseServiceConfiguration() {
    CacheConfiguration<?, ?> cacheConfig =
      newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).add(new DefaultCacheEventDispatcherConfiguration("foo")).build();
    CacheType cacheType = new CacheType();
    cacheType = new DefaultCacheEventDispatcherConfigurationParser().unparseServiceConfiguration(cacheConfig, cacheType);

    assertThat(cacheType.getListeners().getDispatcherThreadPool()).isEqualTo("foo");
  }
}


text:
"""
Miscellaneous TCP networking functionality.

The functionality in this module originated in the :class:`executor.ssh.server`
module with the purpose of facilitating a robust automated test suite for the
:class:`executor.ssh.client` module. While working on SSH tunnel support I
needed similar logic again and I decided to extract this code from the
:class:`executor.ssh.server` module.
"""

# Standard library modules.
import itertools
import logging
import random
import socket

# Modules included in our package.
from executor import ExternalCommand

# External dependencies.
from humanfriendly import Timer, format_timespan
from humanfriendly.terminal.spinners import Spinner
from humanfriendly.text import format, pluralize
from property_manager import (
    PropertyManager,
    lazy_property,
    mutable_property,
    required_property,
    set_property,
)

# Public identifiers that require documentation.
__all__ = (
    'EphemeralPortAllocator',
    'EphemeralTCPServer',
    'TimeoutError',
    'WaitUntilConnected',
    'logger',
)

# Initialize a logger.
logger = logging.getLogger(__name__)

class WaitUntilConnected(PropertyManager):

    """Wait for a TCP endpoint to start accepting connections."""

    @mutable_property
    def connect_timeout(self):
        """The timeout in seconds for individual connection attempts (a number, defaults to 2)."""
        return 2

    @property
    def endpoint(self):
        """A human friendly representation of the TCP endpoint (a string containing a URL)."""
        return format("%s://%s:%i", self.scheme, self.hostname, self.port_number)

    @mutable_property
    def hostname(self):
        """The host name or IP address to connect to (a string, defaults to ``localhost``)."""
        return 'localhost'

    @property
    def is_connected(self):
        """:data:`True` if a connection was accepted, :data:`False` otherwise."""
        timer = Timer()
        logger.debug("Checking whether %s is accepting connections ..", self.endpoint)
        try:
            socket.create_connection((self.hostname, self.port_number), self.connect_timeout)
            logger.debug("Yes %s is accepting connections (took %s).", self.endpoint, timer)
            return True
        except Exception:
            logger.debug("No %s isn't accepting connections (took %s).", self.endpoint, timer)
            return False

    @required_property
    def port_number(self):
        """The port number to connect to (an integer)."""

    @mutable_property
    def scheme(self):
        """A URL scheme that indicates the purpose of the ephemeral port (a string, defaults to 'tcp')."""
        return 'tcp'

    @mutable_property
    def wait_timeout(self):
        """The timeout in seconds for :func:`wait_until_connected()` (a number, defaults to 30)."""
        return 30

    def wait_until_connected(self):
        """
        Wait until connections are being accepted.

        :raises: :exc:`TimeoutError` when the SSH server isn't fast enough to
                 initialize.
        """
        timer = Timer()
        with Spinner(timer=timer) as spinner:
            while not self.is_connected:
                if timer.elapsed_time > self.wait_timeout:
                    raise TimeoutError(format(
                        "Failed to establish connection to %s within configured timeout of %s!",
                        self.endpoint, format_timespan(self.wait_timeout),
                    ))
                spinner.step(label="Waiting for %s to accept connections" % self.endpoint)
                spinner.sleep()
        logger.debug("Waited %s for %s to accept connections.", timer, self.endpoint)

class EphemeralPortAllocator(WaitUntilConnected):

    """
    Allocate a free `ephemeral port number`_.

    .. _ephemeral port number: \
        http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Dynamic.2C_private_or_ephemeral_ports
    """

    @lazy_property
    def port_number(self):
        """A dynamically selected free ephemeral port number (an integer between 49152 and 65535)."""
        timer = Timer()
        logger.debug("Looking for free ephemeral port number ..")
        for i in itertools.count(1):
            value = self.ephemeral_port_number
            set_property(self, 'port_number', value)
            if not self.is_connected:
                logger.debug("Found free ephemeral port number %s after %s (took %s).",
                             value, pluralize(i, "attempt"), timer)
                return value

    @property
    def ephemeral_port_number(self):
        """A random ephemeral port number (an integer between 49152 and 65535)."""
        return random.randint(49152, 65535)

class EphemeralTCPServer(ExternalCommand, EphemeralPortAllocator):

    """
    Make it easy to launch ephemeral TCP servers.

    The :class:`EphemeralTCPServer` class makes it easy to allocate an
    `ephemeral port number`_ that is not (yet) in use.

    .. _ephemeral port number: \
        http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Dynamic.2C_private_or_ephemeral_ports
    """

    @property
    def asynchronous(self):
        """Ephemeral TCP servers always set :attr:`.ExternalCommand.asynchronous` to :data:`True`."""
        return True

    def start(self, **options):
        """
        Start the TCP server and wait for it to start accepting connections.

        :param options: Any keyword arguments are passed to the
                        :func:`~executor.ExternalCommand.start()` method of the
                        superclass.
        :raises: Any exceptions raised by :func:`~executor.ExternalCommand.start()`
                 and :func:`~executor.tcp.WaitUntilConnected.wait_until_connected()`.

        If the TCP server doesn't start accepting connections within the
        configured timeout (see :attr:`~executor.tcp.WaitUntilConnected.wait_timeout`)
        the process will be terminated and the timeout exception is propagated.
        """
        if not self.was_started:
            logger.debug("Preparing to start %s server ..", self.scheme.upper())
            super(EphemeralTCPServer, self).start(**options)
            try:
                self.wait_until_connected()
            except TimeoutError:
                self.terminate()
                raise

class TimeoutError(Exception):

    """
    Raised when a TCP server doesn't start accepting connections quickly enough.

    This exception is raised by :func:`~executor.tcp.WaitUntilConnected.wait_until_connected()`
    when the TCP server doesn't start accepting connections within a reasonable time.
    """


text:
<?php

namespace Cake\Network\Session;

use Cake\ORM\Entity;
use Cake\ORM\TableRegistry;
use SessionHandlerInterface;

/**
 * DatabaseSession provides methods to be used with Session.
 */
class DatabaseSession implements SessionHandlerInterface
{

    /**
     * Reference to the table handling the session data
     *
     * @var \Cake\ORM\Table
     */
    protected $_table;

    /**
     * Number of seconds to mark the session as expired
     *
     * @var int
     */
    protected $_timeout;

    /**
     * Constructor. Looks at Session configuration information and
     * sets up the session model.
     *
     * @param array $config The configuration for this engine. It requires the 'model'
     * key to be present corresponding to the Table to use for managing the sessions.
     */
    public function __construct(array $config = [])
    {
        $tableLocator = isset($config['tableLocator']) ? $config['tableLocator'] : TableRegistry::locator();

        if (empty($config['model'])) {
            $config = $tableLocator->exists('Sessions') ? [] : ['table' => 'sessions'];
            $this->_table = $tableLocator->get('Sessions', $config);
        } else {
            $this->_table = $tableLocator->get($config['model']);
        }

        $this->_timeout = ini_get('session.gc_maxlifetime');
    }

    /**
     * Method called on open of a database session.
     *
     * @param string $savePath The path where to store/retrieve the session.
     * @param string $name The session name.
     * @return bool Success
     */
    public function open($savePath, $name)
    {
        return true;
    }

    /**
     * Method called on close of a database session.
     *
     * @return bool Success
     */
    public function close()
    {
        return true;
    }

    /**
     * Method used to read from a database session.
     *
     * @param int|string $id The key of the value to read
     * @return string The value of the key or empty if it does not exist
     */
    public function read($id)
    {
        $result = $this->_table
            ->find('all')
            ->select(['data'])
            ->where([$this->_table->getPrimaryKey() => $id])
            ->enableHydration(false)
            ->first();

        if (empty($result)) {
            return '';
        }

        if (is_string($result['data'])) {
            return $result['data'];
        }

        $session = stream_get_contents($result['data']);

        if ($session === false) {
            return '';
        }

        return $session;
    }

    /**
     * Helper function called on write for database sessions.
     *
     * @param int $id ID that uniquely identifies session in database
     * @param mixed $data The value of the data to be saved.
     * @return bool True for successful write, false otherwise.
     */
    public function write($id, $data)
    {
        if (!$id) {
            return false;
        }
        $expires = time() + $this->_timeout;
        $record = compact('data', 'expires');
        $record[$this->_table->getPrimaryKey()] = $id;
        $result = $this->_table->save(new Entity($record));

        return (bool)$result;
    }

    /**
     * Method called on the destruction of a database session.
     *
     * @param int $id ID that uniquely identifies session in database
     * @return bool True for successful delete, false otherwise.
     */
    public function destroy($id)
    {
        $this->_table->delete(new Entity(
            [$this->_table->getPrimaryKey() => $id],
            ['markNew' => false]
        ));

        return true;
    }

    /**
     * Helper function called on gc for database sessions.
     *
     * @param string $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed.
     * @return bool True on success, false on failure.
     */
    public function gc($maxlifetime)
    {
        $this->_table->deleteAll(['expires <' => time()]);

        return true;
    }
}


text:
require 'spec_helper_min'

describe Carto::RedisExportService do
  before(:all) do
    sequel_organization = FactoryGirl.create(:organization)
    @organization = Carto::Organization.find(sequel_organization.id)
    @user = FactoryGirl.create(:carto_user)
  end

  after(:all) do
    @organization.destroy
    @user.destroy
  end

  def with_redis_keys(prefix)
    $users_metadata.set("#{prefix}:string", 'something')
    $users_metadata.zincrby("#{prefix}:set", 5, 'set_key')
    $users_metadata.hset("#{prefix}:hash", 'hash_key', 'qwerty')

    yield
  ensure
    $users_metadata.del("#{prefix}:string", "#{prefix}:set", "#{prefix}:hash")
  end

  def check_export(export, prefix)
    expect(export[:redis][:users_metadata].keys.sort).to eq(["#{prefix}:hash", "#{prefix}:set", "#{prefix}:string"])
  end

  def check_redis(prefix)
    expect($users_metadata.get("#{prefix}:string")).to eq('something')
    expect($users_metadata.zrange("#{prefix}:set", 0, -1, withscores: true)).to eq([['set_key', 5.0]])
    expect($users_metadata.hgetall("#{prefix}:hash")).to eq('hash_key' => 'qwerty')
  end

  let(:service) { Carto::RedisExportService.new }

  describe '#export' do
    it 'exports an empty dictionary' do
      export = service.export_user_json_hash(@user)
      expect(export[:redis][:users_metadata]).to eq({})
    end

    it 'includes all keys under org:name for organizations' do
      prefix = "org:#{@organization.name}"
      with_redis_keys(prefix) do
        export = service.export_organization_json_hash(@organization)
        check_export(export, prefix)
      end
    end

    it 'includes all keys under user:username for users' do
      prefix = "user:#{@user.username}"
      with_redis_keys(prefix) do
        export = service.export_user_json_hash(@user)
        check_export(export, prefix)
      end
    end
  end

  describe '#export + import' do
    it 'copies all keys under org:name for organizations' do
      prefix = "org:#{@organization.name}"
      export = with_redis_keys(prefix) { service.export_organization_json_hash(@organization) }
      service.restore_redis_from_hash_export(export)
      check_redis(prefix)
    end

    it 'copies all keys under user:username for users' do
      prefix = "user:#{@user.username}"
      export = with_redis_keys(prefix) { service.export_user_json_hash(@user) }
      service.restore_redis_from_hash_export(export)
      check_redis(prefix)
    end
  end
end


text:
#pragma once

#include <folly/Conv.h>
#include <folly/Format.h>
#include <folly/experimental/logging/LogCategory.h>
#include <folly/experimental/logging/LogLevel.h>
#include <folly/experimental/logging/LogStream.h>
#include <folly/experimental/logging/LogStreamProcessor.h>

/**
 * Helper macro for implementing FB_LOG() and FB_LOGF().
 *
 * This macro generally should not be used directly by end users.
 */
/* clang-format off */
#define FB_LOG_IMPL(logger, level, type, ...)                                \
  (!(logger).getCategory()->logCheck(level))                                 \
      ? ::folly::logDisabledHelper(                                          \
            std::integral_constant<bool, ::folly::isLogLevelFatal(level)>{}) \
      : ::folly::LogStreamVoidify< ::folly::isLogLevelFatal(level)>{} &      \
          ::folly::LogStreamProcessor{(logger).getCategory(),                \
                                      (level),                               \
                                      __FILE__,                              \
                                      __LINE__,                              \
                                      (type),                                \
                                      ##__VA_ARGS__}                         \
              .stream()
/* clang-format on */

/**
 * Log a message to the specified logger.
 *
 * This macro avoids evaluating the log arguments unless the log level check
 * succeeds.
 *
 * Beware that the logger argument is evaluated twice, so this argument should
 * be an expression with no side-effects.
 */
#define FB_LOG(logger, level, ...)         \
  FB_LOG_IMPL(                             \
      logger,                              \
      ::folly::LogLevel::level,            \
      ::folly::LogStreamProcessor::APPEND, \
      ##__VA_ARGS__)

/**
 * Log a message to the specified logger, using a folly::format() string.
 *
 * The arguments will be processed using folly::format().  The format syntax
 * is similar to Python format strings.
 *
 * This macro avoids evaluating the log arguments unless the log level check
 * succeeds.
 *
 * Beware that the logger argument is evaluated twice, so this argument should
 * be an expression with no side-effects.
 */
#define FB_LOGF(logger, level, fmt, arg1, ...) \
  FB_LOG_IMPL(                                 \
      logger,                                  \
      ::folly::LogLevel::level,                \
      ::folly::LogStreamProcessor::FORMAT,     \
      fmt,                                     \
      arg1,                                    \
      ##__VA_ARGS__)

namespace folly {

class LoggerDB;
class LogMessage;

/**
 * Logger is the class you will normally use to log messages.
 *
 * The Logger is really just a small wrapper class that contains a pointer
 * to the appropriate LogCategory object.  It exists to allow for easy static
 * initialization of log categories, as well as to provide fast checking of the
 * current effective log level.
 */
class Logger {
 public:
  /**
   * Construct a Logger for the given category name.
   *
   * A LogCategory object for this category will be created if one does not
   * already exist.
   */
  explicit Logger(folly::StringPiece name);

  /**
   * Construct a Logger pointing to an existing LogCategory object.
   */
  explicit Logger(LogCategory* cat);

  /**
   * Construct a Logger for a specific LoggerDB object, rather than the main
   * singleton.
   *
   * This is primarily intended for use in unit tests.
   */
  Logger(LoggerDB* db, folly::StringPiece name);

  /**
   * Get the LogCategory that this Logger refers to.
   */
  LogCategory* getCategory() const {
    return category_;
  }

 private:
  LogCategory* const category_{nullptr};
};
} // namespace folly


text:
<?php
/**
 * CakePHP ModuloModel
 * @author Gustavo Cardoso
 */
class Modulo extends AppModel {

    public $hasMany = array('Funcionalidade');

    public $virtualFields = array(
        'ativo' => "CASE WHEN Modulo.active = 1 THEN 'Sim' ELSE 'Não' END",
        'totalFuncionalidades' => "(SELECT count(1) FROM funcionalidades WHERE Modulo.id = funcionalidades.modulo_id)",
    );

    public $order = 'Modulo.name asc';

    public $validate = array(
        'name' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'required' => true,
                'message' => 'Campo obrigatório'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'message' => 'Nome em uso. Favor informar outro.'
            )
        ),
        'active' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'Campo obrigatório'
            )
        ),
    );

    public function afterSave($created, $options = array()) {
        // ASSOCIA FUNCIONALIDADES AO MÓDULO
        foreach($this->data['Modulo']['funcionalidade'] as $v){
            $this->Funcionalidade->id = $v;
            $this->Funcionalidade->saveField('modulo_id', $this->data['Modulo']['id']);
        }

        parent::afterSave($created, $options);
    }
}


text:
package com.jcwhatever.nucleus.utils.nms;

import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.NucleusPlugin;
import com.jcwhatever.nucleus.internal.NucMsg;
import com.jcwhatever.nucleus.internal.managed.nms.InternalNmsManager;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.plugin.Plugin;

import javax.annotation.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * NMS utilities.
 */
public final class NmsUtils {

    private NmsUtils() {}

    static Pattern PATTERN_VERSION = Pattern.compile(".*\\.(v\\d+_\\d+_\\w*\\d+)(\\.[\\.a-zA-Z0-9_]*)?");

    private static String _version; // package version

    static {
        loadPackageVersion();
    }

    /**
     * Get the detected NMS package version.
     */
    public static String getNmsVersion() {
        return _version;
    }

    /**
     * Determine if one of the provided NMS package versions is compatible with the
     * current NMS package version.
     *
     * @param versions  The versions to check.
     */
    public static boolean isVersionCompatible(String... versions) {
        for (String version : versions) {
            if (version.equals(getNmsVersion())) {
                return true;
            }
        }

        return false;
    }

    /**
     * Enforce the compatible NMS versions on the specified plugin.
     *
     *
If the current NMS version is not compatible, the plugin is
     * disabled.

     *
     *
Server operators can override this in the config of plugins
     * that extend {@link NucleusPlugin}.

     *
     * @param plugin              The plugin to check.
     * @param compatibleVersions  The NMS versions the plugin is compatible with.
     *
     * @return  True if the plugin is compatible.
     */
    public static boolean enforceNmsVersion(Plugin plugin, String... compatibleVersions) {

        if (!isVersionCompatible(compatibleVersions)) {

            if (plugin instanceof NucleusPlugin) {

                // allow server administrator the option to disable NMS version enforcement
                boolean enforceNmsVersion = ((NucleusPlugin) plugin).getDataNode()
                        .getBoolean("enforce-nms-version", true);

                if (!enforceNmsVersion) {
                    NucMsg.warning(plugin, "Plugin {0} is not compatible with NMS version {1}.",
                            plugin.getName(), getNmsVersion());

                    NucMsg.warning(plugin, "enforce-nms-version has been set to " +
                            "false in the plugins config.");
                    return true;
                }
            }

            // disable incompatible plugin
            Bukkit.getPluginManager().disablePlugin(plugin);

            NucMsg.warning(plugin, "Disabling {0} because it's not compatible with NMS version {1}",
                    plugin.getName(), getNmsVersion());
            return false;
        }

        return true;
    }

    /**
     * Get NucleusFrameworks internal action bar handler.
     *
     * @return  The action bar handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsActionBarHandler getActionBarHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.ACTION_BAR);
    }

    /**
     * Get NucleusFrameworks internal list header/footer handler.
     *
     * @return  The list header/footer handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsListHeaderFooterHandler getListHeaderFooterHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.LIST_HEADER_FOOTER);
    }

    /**
     * Get NucleusFrameworks internal misc. effect handler.
     *
     * @return  The particle effect handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsEffectHandler getEffectHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.EFFECT);
    }

    /**
     * Get NucleusFrameworks internal particle effect handler.
     *
     * @return  The particle effect handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsParticleEffectHandler getParticleEffectHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.PARTICLE_EFFECT);
    }

    /**
     * Get NucleusFramework's internal sound effect handler.
     *
     * @return  The sound effect handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsSoundEffectHandler getSoundEffectHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.SOUND_EFFECT);
    }

    /**
     * Get NucleusFramework's internal title handler.
     *
     * @return  The title handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsTitleHandler getTitleHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.TITLES);
    }

    /**
     * Get NucleusFramework's internal anvil view handler.
     *
     * @return  The anvil view handler or null if a handler for the current version
     * of Minecraft does not exist.
     */
    @Nullable
    public static INmsAnvilViewHandler getAnvilViewHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.ANVIL_VIEW);
    }

    /**
     * Get NucleusFramework's internal potion handler.
     *
     * @return  The potion handler or null if a handler for the current version
     * of Minecraft does not exist.
     */
    @Nullable
    public static INmsPotionHandler getPotionHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.POTIONS);
    }

    /**
     * Get NucleusFramework's internal entity handler.
     *
     * @return  The handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsEntityHandler getEntityHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.ENTITY);
    }

    /**
     * Get NucleusFramework's internal chat handler.
     *
     * @return  The handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsChatHandler getChatHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.CHAT);
    }

    /**
     * Get NucleusFramework's internal vehicle handler.
     *
     * @return  The handler or null if a handler for the current version of
     * Minecraft does not exist.
     */
    @Nullable
    public static INmsVehicleHandler getVehicleHandler() {
        return Nucleus.getNmsManager().getHandler(InternalNmsManager.VEHICLE);
    }

    // load the the craft package version from NucleusFramework's config
    // or detect the version.
    private static void loadPackageVersion() {
        _version = Nucleus.getPlugin().getDataNode().getString("package-version");
        if (_version == null) {

            Class<? extends Server> serverClass = Bukkit.getServer().getClass();

            Matcher versionMatcher = PATTERN_VERSION.matcher(serverClass.getName());

            if (versionMatcher.matches()) {
                _version = versionMatcher.group(1);

                NucMsg.info("Reflection: CraftBukkit version found: {0}", _version);
            }
        }
        else {
            NucMsg.info("Reflection: Using craft version from NucleusFramework config: {0}", _version);
        }

        if (_version == null) {
            NucMsg.severe("Failed to find CraftBukkit version for reflection purposes.");
        }
    }
}


text:
using VRageMath;

namespace HoverRail {
	class SlidingAverageVector {
		double factor;
		public Vector3D value;
		public SlidingAverageVector(double factor) { this.factor = factor; this.value = Vector3D.Zero; }
		public void update(Vector3D newValue) { this.value = this.value * (1 - factor) + newValue * factor; }
	}
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Battle ship</title>
	<link rel="stylesheet" href="css/main.css">
	<meta name="viewport" content="width=device-width">

	<form id="form">
		<input type="text" id="coordinates" placeholder="Ex. A6" maxlength="2" />
		<button type="submit" id="submit">Submit</button>
	</form>


text:
module.exports = {
  $vuetify: {
    functions: [
      {
        name: 'goTo',
        signature: '(target: string | number | HTMLElement | VueComponent, options?: object): void',
      },
    ],
  },
}


text:
package client

// DefaultDockerHost defines os specific default if DOCKER_HOST is unset
const DefaultDockerHost = "unix:///var/run/docker.sock"

const defaultProto = "unix"
const defaultAddr = "/var/run/docker.sock"


text:
package cgeo.geocaching.brouter.util;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.storage.ContentStorage;
import cgeo.geocaching.storage.PersistableFolder;
import cgeo.geocaching.utils.Log;

import android.net.Uri;

import androidx.annotation.RawRes;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class DefaultFilesUtils {

    private enum DefaultFiles {
        CAR_ECO(R.raw.routing_car_eco, "car-eco.brf"),
        CAR_FAST(R.raw.routing_car_fast, "car-fast.brf"),
        FASTBIKE(R.raw.routing_fastbike, "fastbike.brf"),
        MOPED(R.raw.routing_moped, "moped.brf"),
        SHORTEST(R.raw.routing_shortest, "shortest.brf"),
        TREKKING(R.raw.routing_trekking, "trekking.brf"),
        LOOKUPS(R.raw.routing_lookups, "lookups.dat");

        @RawRes
        public final int resId;
        public final String filename;

        DefaultFiles(final @RawRes int resId, final String filename) {
            this.resId = resId;
            this.filename = filename;
        }
    }

    private DefaultFilesUtils() {
        // utility class
    }

    public static void checkDefaultFiles() {
        final List<ContentStorage.FileInformation> files = ContentStorage.get().list(PersistableFolder.ROUTING_BASE);
        for (DefaultFiles file : DefaultFiles.values()) {
            boolean found = false;
            for (ContentStorage.FileInformation fi : files) {
                if (fi.name.equals(file.filename)) {
                    found = true;
                    break;
                }
            }
            // try to recreate missing file
            if (!found) {
                Log.i("Recreating routing default file " + file.filename);
                final Uri newFile = ContentStorage.get().create(PersistableFolder.ROUTING_BASE.getFolder(), file.filename);
                if (newFile == null) {
                    Log.w("Couldn't create file '" + file.filename + "' in '" + PersistableFolder.ROUTING_BASE.getFolder() + "'");
                } else {
                    try (OutputStream os = ContentStorage.get().openForWrite(newFile); InputStream in = CgeoApplication.getInstance().getResources().openRawResource(file.resId)) {
                        final byte[] buff = new byte[1024];
                        int read;
                        while ((read = in.read(buff)) > 0) {
                            os.write(buff, 0, read);
                        }
                    } catch (IOException e) {
                        Log.w("error creating default file " + newFile + " ' in '" + PersistableFolder.ROUTING_BASE.getFolder() + "'", e);
                    }
                }
            }
        }
    }
}


text:
package io.warp10.script.ext.shm;

import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;

public class SHMLOAD extends NamedWarpScriptFunction implements WarpScriptStackFunction {
  public SHMLOAD(String name) {
    super(name);
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();

    if (!(top instanceof String)) {
      throw new WarpScriptException(getName() + " expects a symbol name on top of the stack.");
    }

    String symbol = String.valueOf(top);

    stack.push(SharedMemoryWarpScriptExtension.load(symbol));

    return stack;
  }
}


text:
use super::*;
use crate::message::BufferMessageEncoder;
use futures::prelude::*;
use futures::task::{Waker, Poll};
use futures_timer::Delay;
use std::cell::Cell;
use std::fmt::{Display, Formatter};
use std::ops::Bound;
use std::pin::Pin;
use std::sync::{Arc, Mutex, Weak};
use std::time::{Duration, Instant};

#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub(super) enum UdpSendFutureState<R> {
    /// This send future hasn't been polled yet.
    Uninit,

    /// We are waiting for either an Ack or a response, and we will retransmit
    /// occasionally.
    ActivelyWaiting,

    /// We are still waiting for a response. We are not retransmitting.
    PassivelyWaiting,

    /// We are finished and waiting for our final result to be polled.
    Finished(Result<R, Error>),

    /// We are completely finished.
    Expired,
}

impl<R> Display for UdpSendFutureState<R> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            UdpSendFutureState::Uninit => f.write_str("Uninit"),
            UdpSendFutureState::ActivelyWaiting => f.write_str("ActivelyWaiting"),
            UdpSendFutureState::PassivelyWaiting => f.write_str("PassivelyWaiting"),
            UdpSendFutureState::Finished(Ok(_)) => f.write_str("Finished"),
            UdpSendFutureState::Finished(Err(e)) => write!(f, "Errored({:?})", e),
            UdpSendFutureState::Expired => f.write_str("Expired"),
        }
    }
}

impl<R> UdpSendFutureState<R> {
    pub fn is_waiting(&self) -> bool {
        match self {
            UdpSendFutureState::ActivelyWaiting | UdpSendFutureState::PassivelyWaiting => true,
            _ => false,
        }
    }

    pub fn is_finished(&self) -> bool {
        match self {
            UdpSendFutureState::Finished(_) | UdpSendFutureState::Expired => true,
            _ => false,
        }
    }

    pub fn finished(self) -> Option<Result<R, Error>> {
        match self {
            UdpSendFutureState::Finished(x) => Some(x),
            _ => None,
        }
    }
}

pub(super) struct UdpSendFutureInner<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    send_desc: SD,
    state: UdpSendFutureState<R>,
    waker: Option<futures::task::Waker>,
    local_endpoint: Weak<DatagramLocalEndpointInner<US>>,
    dest: US::SocketAddr,

    msg_id: Cell<MsgId>,
    msg_token: Cell<MsgToken>,
    retransmit_count: Cell<u32>,
    delay: Option<Delay>,
    timeout: Cell<Option<Instant>>,
    _trans_params: TP, // <datagram::DatagramLocalEndpoint<US> as LocalEndpoint>::DefaultTransParams
}

impl<R, SD, US, TP> UdpSendFutureInner<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket + Sized,
    TP: TransParams,
{
    fn state(&self) -> &UdpSendFutureState<R> {
        &self.state
    }

    fn change_state(&mut self, mut state: UdpSendFutureState<R>) -> UdpSendFutureState<R> {
        if state.is_finished() {
            self.update_timeout(None);
        }
        std::mem::swap(&mut self.state, &mut state);
        state
    }

    fn update_waker(&mut self, waker_ref: &Waker) {
        if let Some(waker) = self.waker.take() {
            self.waker = Some(if waker_ref.will_wake(&waker) {
                waker
            } else {
                waker_ref.clone()
            });
        } else {
            self.waker = Some(waker_ref.clone());
        }
    }

    fn update_timeout(&mut self, d: Option<Duration>) {
        if let Some(d) = d {
            if let Some(delay) = self.delay.as_mut() {
                delay.reset(Instant::now() + d);
            } else {
                self.delay = Some(Delay::new(d));
            }
        } else {
            self.delay = None;
        }
    }

    fn poll_timeout(
        &mut self,
        cx: &mut futures::task::Context<'_>,
    ) -> Poll<()> {
        if let Some(delay) = self.delay.as_mut() {
            Pin::new(delay).poll(cx)
        } else {
            Poll::Pending
        }
    }

    pub fn transmit(&self) -> Result<(), Error> {
        let mut buffer = [0u8; StandardCoapConstants::MAX_OUTBOUND_PACKET_LENGTH];
        let mut builder = BufferMessageEncoder::new(&mut buffer);

        let mut token = self.msg_token.get();

        // We allocate a new msg_id for every call to `transmit()`.
        self.msg_id.replace(self.local_endpoint
            .upgrade()
            .ok_or(Error::Cancelled)?
            .next_msg_id()
        );

        if token.is_empty() {
            token = MsgToken::from(self.msg_id.get());
        }

        builder.set_msg_token(token);

        self.send_desc.write_options(
            &mut builder,
            &self.dest,
            Bound::Unbounded,
            Bound::Unbounded,
        )?;
        self.send_desc.write_payload(&mut builder, &self.dest)?;

        let builder_token = builder.msg_token();

        self.msg_token.replace(builder_token);

        // We always control the msg_id.
        builder.set_msg_id(self.msg_id.get());

        println!("OUTBOUND: {} {}", self.dest, builder);

        let buffer: &[u8] = &builder;

        if let Some(e) = self
            .local_endpoint
            .upgrade()
            .ok_or(Error::Cancelled)?
            .socket()
            .send_to(&buffer, self.dest)
            .now_or_never()
            .expect("send_to blocked")
            .err()
        {
            println!("send_to: io error: {:?} (dest={:?})", e, self.dest);
            return Err(Error::IOError);
        }

        println!("Did transmit.");

        self.retransmit_count.set(0);

        Ok(())
    }

    pub fn retransmit(&self) -> Result<(), Error> {
        let mut buffer = [0u8; StandardCoapConstants::MAX_OUTBOUND_PACKET_LENGTH];
        let mut builder = BufferMessageEncoder::new(&mut buffer);

        if let Some(timeout) = self.timeout.get() {
            if Instant::now() > timeout {
                return Err(Error::ResponseTimeout);
            }
        }

        builder.set_msg_token(self.msg_token.get());

        self.send_desc.write_options(
            &mut builder,
            &self.dest,
            Bound::Unbounded,
            Bound::Unbounded,
        )?;
        self.send_desc.write_payload(&mut builder, &self.dest)?;

        builder.set_msg_id(self.msg_id.get());

        println!(
            "OUTBOUND[{}]: {} {}",
            self.retransmit_count.get() + 1,
            self.dest,
            builder
        );

        let buffer: &[u8] = &builder;

        if let Some(e) = self
            .local_endpoint
            .upgrade()
            .ok_or(Error::Cancelled)?
            .socket()
            .send_to(buffer, self.dest)
            .now_or_never()
            .expect("send_to blocked")
            .err()
        {
            println!("send_to: io error: {:?} (dest={:?})", e, self.dest);
            return Err(Error::IOError);
        }

        self.retransmit_count.set(self.retransmit_count.get() + 1);

        println!("Did retransmit, count {}", self.retransmit_count.get());

        Ok(())
    }

    fn wake(&mut self) {
        if let Some(waker) = self.waker.take() {
            waker.wake();
        }
    }
}

impl<R, SD, US, TP> HandleResponse<DatagramInboundContext<US::SocketAddr>>
    for UdpSendFutureInner<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    fn handle_response(&mut self, context: Result<&DatagramInboundContext<US::SocketAddr>, Error>) -> bool {
        // This should only be called if we are waiting for a response.
        assert!(self.state().is_waiting(), "Invalid state: {}", self.state());

        // If this is an ack, we don't pass this along to the send_desc.
        if let Some(context) = context.ok() {
            let message = context.message();

            if !self.dest.is_multicast()
                && message.msg_code().is_empty()
                && message.msg_type().is_ack()
            {
                println!("Got ack!");

                self.change_state(UdpSendFutureState::PassivelyWaiting);
                let d = self.send_desc.max_rtt();
                self.update_timeout(Some(d));
                self.wake();
                return self.state.is_finished();
            }
        }

        // Pass the full context along to our `send_desc.handler()`
        match self.send_desc.handler(context) {
            Ok(ResponseStatus::Done(x)) => {
                // Stick a fork in us, we are done.
                self.change_state(UdpSendFutureState::Finished(Ok(x)));
            }
            Ok(ResponseStatus::Continue) => {
                if !self.dest.is_multicast() {
                    self.change_state(UdpSendFutureState::PassivelyWaiting);
                    let d = self.send_desc.max_rtt();
                    self.update_timeout(Some(d));
                }
            }
            Ok(ResponseStatus::SendNext) => {
                // Allocate a new msg-id, Reset retransmit count, and resend.
                self.change_state(UdpSendFutureState::Uninit);
            }
            Err(e) => {
                self.change_state(UdpSendFutureState::Finished(Err(e)));
            }
        }

        self.wake();

        self.state.is_finished()
    }
}

pub(super) struct UdpSendFuture<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    inner: Arc<Mutex<UdpSendFutureInner<R, SD, US, TP>>>,
}

impl<'lep, R, SD, US, TP> UdpSendFuture<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    pub(super) fn new(
        local_endpoint: &Arc<DatagramLocalEndpointInner<US>>,
        dest: US::SocketAddr,
        send_desc: SD,
        trans_params: TP,
    ) -> UdpSendFuture<R, SD, US, TP> {
        UdpSendFuture {
            inner: Arc::new(Mutex::new(UdpSendFutureInner {
                send_desc,
                state: UdpSendFutureState::Uninit,
                waker: None,
                msg_id: Cell::new(0),
                msg_token: Cell::new(MsgToken::EMPTY),
                local_endpoint: Arc::downgrade(&local_endpoint),
                dest,
                retransmit_count: Cell::new(0),
                delay: None,
                timeout: Cell::new(None),
                _trans_params: trans_params,
            })),
        }
    }

    fn poll(
        &mut self,
        cx: &mut futures::task::Context<'_>,
    ) -> futures::task::Poll<Result<R, Error>> {
        let mut inner = self
            .inner
            .lock()
            .expect("UdpSendFuture inner mutex poisoned");

        match inner.state() {
            UdpSendFutureState::Uninit => {
                // TODO(#4): Figure out how this can be set programmatically.
                inner.timeout.set(Some(
                    Instant::now() + inner.send_desc.transmit_wait_duration(),
                ));

                if let Some(error) = inner.transmit().err() {
                    inner.change_state(UdpSendFutureState::Finished(Err(error)));
                } else {
                    inner
                        .local_endpoint
                        .upgrade()
                        .ok_or(Error::Cancelled)?
                        .add_response_handler(
                            inner.msg_id.get(),
                            inner.msg_token.get(),
                            inner.dest.clone(),
                            self.inner.clone(),
                        );

                    if let Some(d) = inner
                        .send_desc
                        .delay_to_retransmit(inner.retransmit_count.get())
                    {
                        inner.change_state(UdpSendFutureState::ActivelyWaiting);
                        inner.update_timeout(Some(d));
                        let _ = inner.poll_timeout(cx);
                    } else {
                        inner.change_state(UdpSendFutureState::PassivelyWaiting);
                        let d = inner.send_desc.max_rtt();
                        inner.update_timeout(Some(d));
                        let _ = inner.poll_timeout(cx);
                    }
                }
            }

            UdpSendFutureState::ActivelyWaiting => {
                // We are waiting to retransmit.
                if inner.poll_timeout(cx).is_ready() {
                    if let Some(error) = inner.retransmit().err() {
                        inner.change_state(UdpSendFutureState::Finished(Err(error)));
                    } else if let Some(d) = inner
                        .send_desc
                        .delay_to_retransmit(inner.retransmit_count.get())
                    {
                        inner.update_timeout(Some(d));
                        let _ = inner.poll_timeout(cx);
                    } else {
                        inner.change_state(UdpSendFutureState::PassivelyWaiting);
                        let d = inner.send_desc.max_rtt();
                        inner.update_timeout(Some(d));
                        let _ = inner.poll_timeout(cx);
                    }
                }
            }

            UdpSendFutureState::PassivelyWaiting => {
                // We are waiting for the end of the RTT
                if inner.poll_timeout(cx).is_ready() {
                    inner.handle_response(Err(Error::ResponseTimeout));
                }
            }

            UdpSendFutureState::Finished(_) | UdpSendFutureState::Expired => {
                // We are done, nothing to do here.
            }
        }

        if inner.state().is_finished() {
            let ret = inner
                .change_state(UdpSendFutureState::Expired)
                .finished()
                .unwrap();
            futures::task::Poll::Ready(ret)
        } else {
            inner.update_waker(cx.waker());

            futures::task::Poll::Pending
        }
    }
}

impl<R, SD, US, TP> Drop for UdpSendFuture<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    fn drop(&mut self) {
        let inner = match self.inner.lock() {
            Ok(guard) => guard,
            Err(poisoned) => {
                eprintln!("UdpSendFuture mutex inner was poisoned, locking anyway to drop");
                poisoned.into_inner()
            }
        };

        if let Some(le) = inner.local_endpoint.upgrade() {
            le.remove_response_handler(inner.msg_id.get(), inner.msg_token.get(), inner.dest.clone());
        }
    }
}

impl<R, SD, US, TP> Future for UdpSendFuture<R, SD, US, TP>
where
    R: Send,
    SD: SendDesc<DatagramInboundContext<US::SocketAddr>, R>,
    US: AsyncDatagramSocket,
    TP: TransParams,
{
    type Output = Result<R, Error>;

    fn poll(
        self: Pin<&mut Self>,
        cx: &mut futures::task::Context<'_>,
    ) -> futures::task::Poll<Self::Output> {
        self.get_mut().poll(cx)
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.oastem.frc.pid;

import edu.wpi.first.wpilibj.PIDController;

/**
 *
 * @author KTOmega
 */
public class PIDControllerCollection {
    private PIDController[] ctrl;
    private int i = 0;
    private int max;

    public PIDControllerCollection(int size) {
        ctrl = new PIDController[size];
        max = size;
    }

    public void add(PIDController c) {
        if (i >= max) {
            throw new IndexOutOfBoundsException("Reached the limit of " +
                    max + " PID controllers!");
        }
        ctrl[i++] = c;
    }

    public PIDController get(int index) {
        return ctrl[index];
    }

    public boolean isEnabled(int index) {
        return ctrl[index].isEnable();
    }

    public void enableAll() {
        for (int j = 0; j < max; j++) {
            ctrl[j].enable();
        }
    }

    public void disableAll() {
        for (int j = 0; j < max; j++) {
            ctrl[j].disable();
        }
    }

    public void freeAll() {
        for (int j = 0; j < max; j++) {
            ctrl[j].free();
        }
    }
}


text:
<?php

namespace Frontend\CorresponsaliaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Corresponsalia
 *
 * @ORM\Table(name="rendicion.cambio")
 * @ORM\Entity
 */
class Cambio
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="rendicion.cambio_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

     /**
     * @var integer
     *
     * @ORM\Column(name="montocambiodolar", type="decimal", precision=20, scale= 3, nullable=false)
     * @Assert\NotBlank(message="El monto no debe estar vacío.")
     */
    private $montocambiodolar;

        /**
     * @var \DateTime
     *
     * @ORM\Column(name="fechahoraresgistro", type="datetime", nullable=false)
     */
    private $fechahoraregistro;

    /**
     * @var \Perfil
     *
     * @ORM\ManyToOne(targetEntity="Administracion\UsuarioBundle\Entity\Perfil")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="responsable_id", referencedColumnName="id", nullable=false)
     * })
     */
    private $responsable;

    /**
     * @var \Tipogasto
     *
     * @ORM\ManyToOne(targetEntity="Periodorendicion")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="periodorendicion_id", referencedColumnName="id", nullable=false)
     * })
     */
    private $periodorendicion;

        /**
     * @var \Descripciongasto
     *
     * @ORM\ManyToOne(targetEntity="Tipomoneda")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="tipomoneda_id", referencedColumnName="id", nullable=false)
     * })
     * @Assert\NotBlank(message="Debe seleccionar un tipo de moneda.")

     */
    private $tipomoneda;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set montocambiodolar
     *
     * @param string $montocambiodolar
     * @return Relaciongastos
     */
    public function setMontocambiodolar($montocambiodolar)
    {
        $this->montocambiodolar = $montocambiodolar;

        return $this;
    }

    /**
     * Get montocambiodolar
     *
     * @return string
     */
    public function getMontocambiodolar()
    {
        return $this->montocambiodolar;
    }

    /**
     * Set fechahoraregistro
     *
     * @param \DateTime $fechahoraregistro
     * @return Ticket
     */
    public function setFechahoraregistro($fechahoraregistro)
    {
        $this->fechahoraregistro = $fechahoraregistro;

        return $this;
    }

    /**
     * Set tipomoneda
     *
     * @param integer $tipomoneda
     * @return Relaciongastos
     */
    public function setTipomoneda(\Frontend\CorresponsaliaBundle\Entity\Tipomoneda $tipomoneda = null )
    {
        $this->tipomoneda = $tipomoneda;

        return $this;
    }

    /**
     * Get tipomoneda
     *
     * @return integer
     */
    public function getTipomoneda()
    {
        return $this->tipomoneda;
    }

    /**
     * Get fechahoraregistro
     *
     * @return \DateTime
     */
    public function getFechahoraregistro()
    {
        return $this->fechahoraregistro;
    }

     /**
     * Set responsable
     *
     * @param \Administracion\UsuarioBundle\Entity\Perfil $responsable
     * @return Operador
     */
    public function setResponsable(\Administracion\UsuarioBundle\Entity\Perfil $responsable = null)
    {
        $this->responsable = $responsable;

        return $this;
    }

    /**
     * Get responsable
     *
     * @return \Administracion\UsuarioBundle\Entity\Perfil
     */
    public function getResponsable()
    {
        return $this->responsable;
    }

    public function __toString()
    {
        return $this->getMonto();
    }

    /**
     * Set periodorendicion
     *
     * @param \Frontend\CorresponsaliaBundle\Entity\Periodorendicion $periodorendicion
     * @return Relaciongastos
     */
    public function setPeriodorendicion(\Frontend\CorresponsaliaBundle\Entity\Periodorendicion $periodorendicion = null)
    {
        $this->periodorendicion = $periodorendicion;

        return $this;
    }

    /**
     * Get periodorendicion
     *
     * @return \Frontend\CorresponsaliaBundle\Entity\Periodorendicion
     */
    public function getPeriodorendicion()
    {
        return $this->periodorendicion;
    }
}


text:
#include <aws/cloudfront/model/ParametersInCacheKeyAndForwardedToOrigin.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudFront
{
namespace Model
{

ParametersInCacheKeyAndForwardedToOrigin::ParametersInCacheKeyAndForwardedToOrigin() :
    m_enableAcceptEncodingGzip(false),
    m_enableAcceptEncodingGzipHasBeenSet(false),
    m_enableAcceptEncodingBrotli(false),
    m_enableAcceptEncodingBrotliHasBeenSet(false),
    m_headersConfigHasBeenSet(false),
    m_cookiesConfigHasBeenSet(false),
    m_queryStringsConfigHasBeenSet(false)
{
}

ParametersInCacheKeyAndForwardedToOrigin::ParametersInCacheKeyAndForwardedToOrigin(const XmlNode& xmlNode) :
    m_enableAcceptEncodingGzip(false),
    m_enableAcceptEncodingGzipHasBeenSet(false),
    m_enableAcceptEncodingBrotli(false),
    m_enableAcceptEncodingBrotliHasBeenSet(false),
    m_headersConfigHasBeenSet(false),
    m_cookiesConfigHasBeenSet(false),
    m_queryStringsConfigHasBeenSet(false)
{
  *this = xmlNode;
}

ParametersInCacheKeyAndForwardedToOrigin& ParametersInCacheKeyAndForwardedToOrigin::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode enableAcceptEncodingGzipNode = resultNode.FirstChild("EnableAcceptEncodingGzip");
    if(!enableAcceptEncodingGzipNode.IsNull())
    {
      m_enableAcceptEncodingGzip = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(enableAcceptEncodingGzipNode.GetText()).c_str()).c_str());
      m_enableAcceptEncodingGzipHasBeenSet = true;
    }
    XmlNode enableAcceptEncodingBrotliNode = resultNode.FirstChild("EnableAcceptEncodingBrotli");
    if(!enableAcceptEncodingBrotliNode.IsNull())
    {
      m_enableAcceptEncodingBrotli = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(enableAcceptEncodingBrotliNode.GetText()).c_str()).c_str());
      m_enableAcceptEncodingBrotliHasBeenSet = true;
    }
    XmlNode headersConfigNode = resultNode.FirstChild("HeadersConfig");
    if(!headersConfigNode.IsNull())
    {
      m_headersConfig = headersConfigNode;
      m_headersConfigHasBeenSet = true;
    }
    XmlNode cookiesConfigNode = resultNode.FirstChild("CookiesConfig");
    if(!cookiesConfigNode.IsNull())
    {
      m_cookiesConfig = cookiesConfigNode;
      m_cookiesConfigHasBeenSet = true;
    }
    XmlNode queryStringsConfigNode = resultNode.FirstChild("QueryStringsConfig");
    if(!queryStringsConfigNode.IsNull())
    {
      m_queryStringsConfig = queryStringsConfigNode;
      m_queryStringsConfigHasBeenSet = true;
    }
  }

  return *this;
}

void ParametersInCacheKeyAndForwardedToOrigin::AddToNode(XmlNode& parentNode) const
{
  Aws::StringStream ss;
  if(m_enableAcceptEncodingGzipHasBeenSet)
  {
   XmlNode enableAcceptEncodingGzipNode = parentNode.CreateChildElement("EnableAcceptEncodingGzip");
   ss << std::boolalpha << m_enableAcceptEncodingGzip;
   enableAcceptEncodingGzipNode.SetText(ss.str());
   ss.str("");
  }

  if(m_enableAcceptEncodingBrotliHasBeenSet)
  {
   XmlNode enableAcceptEncodingBrotliNode = parentNode.CreateChildElement("EnableAcceptEncodingBrotli");
   ss << std::boolalpha << m_enableAcceptEncodingBrotli;
   enableAcceptEncodingBrotliNode.SetText(ss.str());
   ss.str("");
  }

  if(m_headersConfigHasBeenSet)
  {
   XmlNode headersConfigNode = parentNode.CreateChildElement("HeadersConfig");
   m_headersConfig.AddToNode(headersConfigNode);
  }

  if(m_cookiesConfigHasBeenSet)
  {
   XmlNode cookiesConfigNode = parentNode.CreateChildElement("CookiesConfig");
   m_cookiesConfig.AddToNode(cookiesConfigNode);
  }

  if(m_queryStringsConfigHasBeenSet)
  {
   XmlNode queryStringsConfigNode = parentNode.CreateChildElement("QueryStringsConfig");
   m_queryStringsConfig.AddToNode(queryStringsConfigNode);
  }

}

} // namespace Model
} // namespace CloudFront
} // namespace Aws


text:
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public bool MajorVersionSpecified { get; set; }
```

### Property Value
Type: System.Boolean

## See also
- [PublishingDesignPackage](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.PublishingDesignPackage.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace LiteDB_V6
{
    internal class CollectionService
    {
        private PageService _pager;

        public CollectionService(PageService pager)
        {
            _pager = pager;
        }

        /// <summary>
        /// Get a exist collection. Returns null if not exists
        /// </summary>
        public CollectionPage Get(string name)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

            var header = _pager.GetPage<HeaderPage>(0);

            uint pageID;

            if (header.CollectionPages.TryGetValue(name, out pageID))
            {
                return _pager.GetPage<CollectionPage>(pageID);
            }

            throw new Exception("Collection not found: " + name);
        }
    }
}


text:
#ifndef libcss_hint_h_
#define libcss_hint_h_

#ifdef __cplusplus
extern "C"
{
#endif

#include <libwapcaplet/libwapcaplet.h>

#include <libcss/computed.h>
#include <libcss/errors.h>
#include <libcss/functypes.h>
#include <libcss/types.h>

/**
 * Length object for use in presentational hints
 */
typedef struct css_hint_length {
	css_fixed value;
	css_unit unit;
} css_hint_length;

/**
 * Presentational hints
 */
typedef struct css_hint {
	/* Ownership of all data is passed to libcss */
	union {
		css_computed_clip_rect *clip;
		css_color color;
		css_computed_content_item *content;
		css_computed_counter *counter;
		css_computed_image *image;
		css_fixed fixed;
		int32_t integer;
		css_hint_length length;
		struct {
			css_hint_length h;
			css_hint_length v;
		} position;
		lwc_string *string;
		lwc_string **strings;
	} data;

	uint32_t prop;		/**< Property index */
	uint8_t status;		/**< Property value */
} css_hint;

#ifdef __cplusplus
}
#endif

#endif